window-basic-main.cpp 300 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 "ui-config.h"
  17. #include <cstddef>
  18. #include <ctime>
  19. #include <functional>
  20. #include <unordered_set>
  21. #include <obs-data.h>
  22. #include <obs.h>
  23. #include <obs.hpp>
  24. #include <QGuiApplication>
  25. #include <QMessageBox>
  26. #include <QShowEvent>
  27. #include <QDesktopServices>
  28. #include <QFileDialog>
  29. #include <QScreen>
  30. #include <QColorDialog>
  31. #include <QSizePolicy>
  32. #include <QScrollBar>
  33. #include <QTextStream>
  34. #include <QActionGroup>
  35. #include <util/dstr.h>
  36. #include <util/util.hpp>
  37. #include <util/platform.h>
  38. #include <util/profiler.hpp>
  39. #include <util/dstr.hpp>
  40. #include "obs-app.hpp"
  41. #include "platform.hpp"
  42. #include "visibility-item-widget.hpp"
  43. #include "item-widget-helpers.hpp"
  44. #include "window-basic-settings.hpp"
  45. #include "window-namedialog.hpp"
  46. #include "window-basic-auto-config.hpp"
  47. #include "window-basic-source-select.hpp"
  48. #include "window-basic-main.hpp"
  49. #include "window-basic-stats.hpp"
  50. #include "window-basic-main-outputs.hpp"
  51. #include "window-basic-vcam-config.hpp"
  52. #include "window-log-reply.hpp"
  53. #ifdef __APPLE__
  54. #include "window-permissions.hpp"
  55. #endif
  56. #include "window-projector.hpp"
  57. #include "window-remux.hpp"
  58. #ifdef YOUTUBE_ENABLED
  59. #include "auth-youtube.hpp"
  60. #include "window-youtube-actions.hpp"
  61. #include "youtube-api-wrappers.hpp"
  62. #endif
  63. #include "qt-wrappers.hpp"
  64. #include "context-bar-controls.hpp"
  65. #include "obs-proxy-style.hpp"
  66. #include "display-helpers.hpp"
  67. #include "volume-control.hpp"
  68. #include "remote-text.hpp"
  69. #include "ui-validation.hpp"
  70. #include "media-controls.hpp"
  71. #include "undo-stack-obs.hpp"
  72. #include <fstream>
  73. #include <sstream>
  74. #ifdef _WIN32
  75. #include "update/win-update.hpp"
  76. #include "update/shared-update.hpp"
  77. #include "windows.h"
  78. #endif
  79. #if !defined(_WIN32) && defined(WHATSNEW_ENABLED)
  80. #include "update/shared-update.hpp"
  81. #endif
  82. #ifdef ENABLE_SPARKLE_UPDATER
  83. #include "update/mac-update.hpp"
  84. #endif
  85. #include "ui_OBSBasic.h"
  86. #include "ui_ColorSelect.h"
  87. #include <QWindow>
  88. #include "update/models/whatsnew.hpp"
  89. #ifdef ENABLE_WAYLAND
  90. #include <obs-nix-platform.h>
  91. #endif
  92. using namespace std;
  93. #ifdef BROWSER_AVAILABLE
  94. #include <browser-panel.hpp>
  95. #endif
  96. #include "ui-config.h"
  97. struct QCef;
  98. struct QCefCookieManager;
  99. QCef *cef = nullptr;
  100. QCefCookieManager *panel_cookies = nullptr;
  101. bool cef_js_avail = false;
  102. void DestroyPanelCookieManager();
  103. namespace {
  104. template<typename OBSRef> struct SignalContainer {
  105. OBSRef ref;
  106. vector<shared_ptr<OBSSignal>> handlers;
  107. };
  108. }
  109. extern volatile long insideEventLoop;
  110. Q_DECLARE_METATYPE(OBSScene);
  111. Q_DECLARE_METATYPE(OBSSceneItem);
  112. Q_DECLARE_METATYPE(OBSSource);
  113. Q_DECLARE_METATYPE(obs_order_movement);
  114. Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
  115. QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
  116. {
  117. out << v.ref;
  118. return out;
  119. }
  120. QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
  121. {
  122. in >> v.ref;
  123. return in;
  124. }
  125. template<typename T> static T GetOBSRef(QListWidgetItem *item)
  126. {
  127. return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
  128. }
  129. template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
  130. {
  131. item->setData(static_cast<int>(QtDataRole::OBSRef),
  132. QVariant::fromValue(val));
  133. }
  134. static void AddExtraModulePaths()
  135. {
  136. string plugins_path, plugins_data_path;
  137. char *s;
  138. s = getenv("OBS_PLUGINS_PATH");
  139. if (s)
  140. plugins_path = s;
  141. s = getenv("OBS_PLUGINS_DATA_PATH");
  142. if (s)
  143. plugins_data_path = s;
  144. if (!plugins_path.empty() && !plugins_data_path.empty()) {
  145. string data_path_with_module_suffix;
  146. data_path_with_module_suffix += plugins_data_path;
  147. data_path_with_module_suffix += "/%module%";
  148. obs_add_module_path(plugins_path.c_str(),
  149. data_path_with_module_suffix.c_str());
  150. }
  151. if (portable_mode)
  152. return;
  153. char base_module_dir[512];
  154. #if defined(_WIN32)
  155. int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
  156. "obs-studio/plugins/%module%");
  157. #elif defined(__APPLE__)
  158. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  159. "obs-studio/plugins/%module%.plugin");
  160. #else
  161. int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
  162. "obs-studio/plugins/%module%");
  163. #endif
  164. if (ret <= 0)
  165. return;
  166. string path = base_module_dir;
  167. #if defined(__APPLE__)
  168. /* User Application Support Search Path */
  169. obs_add_module_path((path + "/Contents/MacOS").c_str(),
  170. (path + "/Contents/Resources").c_str());
  171. #ifndef __aarch64__
  172. /* Legacy System Library Search Path */
  173. char system_legacy_module_dir[PATH_MAX];
  174. GetProgramDataPath(system_legacy_module_dir,
  175. sizeof(system_legacy_module_dir),
  176. "obs-studio/plugins/%module%");
  177. std::string path_system_legacy = system_legacy_module_dir;
  178. obs_add_module_path((path_system_legacy + "/bin").c_str(),
  179. (path_system_legacy + "/data").c_str());
  180. /* Legacy User Application Support Search Path */
  181. char user_legacy_module_dir[PATH_MAX];
  182. GetConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir),
  183. "obs-studio/plugins/%module%");
  184. std::string path_user_legacy = user_legacy_module_dir;
  185. obs_add_module_path((path_user_legacy + "/bin").c_str(),
  186. (path_user_legacy + "/data").c_str());
  187. #endif
  188. #else
  189. #if ARCH_BITS == 64
  190. obs_add_module_path((path + "/bin/64bit").c_str(),
  191. (path + "/data").c_str());
  192. #else
  193. obs_add_module_path((path + "/bin/32bit").c_str(),
  194. (path + "/data").c_str());
  195. #endif
  196. #endif
  197. }
  198. /* First-party modules considered to be potentially unsafe to load in Safe Mode
  199. * due to them allowing external code (e.g. scripts) to modify OBS's state. */
  200. static const unordered_set<string> unsafe_modules = {
  201. "frontend-tools", // Scripting
  202. "obs-websocket", // Allows outside modifications
  203. };
  204. static void SetSafeModuleNames()
  205. {
  206. #ifndef SAFE_MODULES
  207. return;
  208. #else
  209. string module;
  210. stringstream modules(SAFE_MODULES);
  211. while (getline(modules, module, '|')) {
  212. /* When only disallowing third-party plugins, still add
  213. * "unsafe" bundled modules to the safe list. */
  214. if (disable_3p_plugins || !unsafe_modules.count(module))
  215. obs_add_safe_module(module.c_str());
  216. }
  217. #endif
  218. }
  219. extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);
  220. void assignDockToggle(QDockWidget *dock, QAction *action)
  221. {
  222. auto handleWindowToggle = [action](bool vis) {
  223. action->blockSignals(true);
  224. action->setChecked(vis);
  225. action->blockSignals(false);
  226. };
  227. auto handleMenuToggle = [dock](bool check) {
  228. dock->blockSignals(true);
  229. dock->setVisible(check);
  230. dock->blockSignals(false);
  231. };
  232. dock->connect(dock->toggleViewAction(), &QAction::toggled,
  233. handleWindowToggle);
  234. dock->connect(action, &QAction::toggled, handleMenuToggle);
  235. }
  236. void setupDockAction(QDockWidget *dock)
  237. {
  238. QAction *action = dock->toggleViewAction();
  239. auto neverDisable = [action]() {
  240. QSignalBlocker block(action);
  241. action->setEnabled(true);
  242. };
  243. auto newToggleView = [dock](bool check) {
  244. QSignalBlocker block(dock);
  245. dock->setVisible(check);
  246. };
  247. // Replace the slot connected by default
  248. QObject::disconnect(action, &QAction::triggered, nullptr, 0);
  249. dock->connect(action, &QAction::triggered, newToggleView);
  250. // Make the action unable to be disabled
  251. action->connect(action, &QAction::enabledChanged, neverDisable);
  252. }
  253. extern void RegisterTwitchAuth();
  254. extern void RegisterRestreamAuth();
  255. #ifdef YOUTUBE_ENABLED
  256. extern void RegisterYoutubeAuth();
  257. #endif
  258. OBSBasic::OBSBasic(QWidget *parent)
  259. : OBSMainWindow(parent),
  260. undo_s(ui),
  261. ui(new Ui::OBSBasic)
  262. {
  263. setAttribute(Qt::WA_NativeWindow);
  264. #ifdef TWITCH_ENABLED
  265. RegisterTwitchAuth();
  266. #endif
  267. #ifdef RESTREAM_ENABLED
  268. RegisterRestreamAuth();
  269. #endif
  270. #ifdef YOUTUBE_ENABLED
  271. RegisterYoutubeAuth();
  272. #endif
  273. setAcceptDrops(true);
  274. setContextMenuPolicy(Qt::CustomContextMenu);
  275. api = InitializeAPIInterface(this);
  276. ui->setupUi(this);
  277. ui->previewDisabledWidget->setVisible(false);
  278. QStyle *contextBarStyle = new OBSContextBarProxyStyle();
  279. contextBarStyle->setParent(ui->contextContainer);
  280. ui->contextContainer->setStyle(contextBarStyle);
  281. ui->broadcastButton->setVisible(false);
  282. startingDockLayout = saveState();
  283. statsDock = new OBSDock();
  284. statsDock->setObjectName(QStringLiteral("statsDock"));
  285. statsDock->setFeatures(QDockWidget::DockWidgetClosable |
  286. QDockWidget::DockWidgetMovable |
  287. QDockWidget::DockWidgetFloatable);
  288. statsDock->setWindowTitle(QTStr("Basic.Stats"));
  289. addDockWidget(Qt::BottomDockWidgetArea, statsDock);
  290. statsDock->setVisible(false);
  291. statsDock->setFloating(true);
  292. statsDock->resize(700, 200);
  293. copyActionsDynamicProperties();
  294. qRegisterMetaType<int64_t>("int64_t");
  295. qRegisterMetaType<uint32_t>("uint32_t");
  296. qRegisterMetaType<OBSScene>("OBSScene");
  297. qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
  298. qRegisterMetaType<OBSSource>("OBSSource");
  299. qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
  300. qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
  301. ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
  302. ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);
  303. bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  304. "gridMode");
  305. ui->scenes->SetGridMode(sceneGrid);
  306. if (sceneGrid)
  307. ui->actionSceneGridMode->setChecked(true);
  308. else
  309. ui->actionSceneListMode->setChecked(true);
  310. ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));
  311. auto displayResize = [this]() {
  312. struct obs_video_info ovi;
  313. if (obs_get_video_info(&ovi))
  314. ResizePreview(ovi.base_width, ovi.base_height);
  315. UpdateContextBarVisibility();
  316. dpi = devicePixelRatioF();
  317. };
  318. dpi = devicePixelRatioF();
  319. connect(windowHandle(), &QWindow::screenChanged, displayResize);
  320. connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
  321. delete shortcutFilter;
  322. shortcutFilter = CreateShortcutFilter();
  323. installEventFilter(shortcutFilter);
  324. stringstream name;
  325. name << "OBS " << App()->GetVersionString();
  326. blog(LOG_INFO, "%s", name.str().c_str());
  327. blog(LOG_INFO, "---------------------------------");
  328. UpdateTitleBar();
  329. connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor,
  330. this, &OBSBasic::SceneNameEdited);
  331. cpuUsageInfo = os_cpu_usage_info_start();
  332. cpuUsageTimer = new QTimer(this);
  333. connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar,
  334. &OBSBasicStatusBar::UpdateCPUUsage);
  335. cpuUsageTimer->start(3000);
  336. diskFullTimer = new QTimer(this);
  337. connect(diskFullTimer, &QTimer::timeout, this,
  338. &OBSBasic::CheckDiskSpaceRemaining);
  339. renameScene = new QAction(QTStr("Rename"), ui->scenesDock);
  340. renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  341. connect(renameScene, &QAction::triggered, this,
  342. &OBSBasic::EditSceneName);
  343. ui->scenesDock->addAction(renameScene);
  344. renameSource = new QAction(QTStr("Rename"), ui->sourcesDock);
  345. renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  346. connect(renameSource, &QAction::triggered, this,
  347. &OBSBasic::EditSceneItemName);
  348. ui->sourcesDock->addAction(renameSource);
  349. #ifdef __APPLE__
  350. renameScene->setShortcut({Qt::Key_Return});
  351. renameSource->setShortcut({Qt::Key_Return});
  352. ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
  353. ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
  354. ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole);
  355. ui->action_Settings->setMenuRole(QAction::PreferencesRole);
  356. ui->actionShowMacPermissions->setMenuRole(
  357. QAction::ApplicationSpecificRole);
  358. ui->actionE_xit->setMenuRole(QAction::QuitRole);
  359. #else
  360. renameScene->setShortcut({Qt::Key_F2});
  361. renameSource->setShortcut({Qt::Key_F2});
  362. #endif
  363. #ifdef __linux__
  364. ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q);
  365. #endif
  366. auto addNudge = [this](const QKeySequence &seq, MoveDir direction,
  367. int distance) {
  368. QAction *nudge = new QAction(ui->preview);
  369. nudge->setShortcut(seq);
  370. nudge->setShortcutContext(Qt::WidgetShortcut);
  371. ui->preview->addAction(nudge);
  372. connect(nudge, &QAction::triggered,
  373. [this, distance, direction]() {
  374. Nudge(distance, direction);
  375. });
  376. };
  377. addNudge(Qt::Key_Up, MoveDir::Up, 1);
  378. addNudge(Qt::Key_Down, MoveDir::Down, 1);
  379. addNudge(Qt::Key_Left, MoveDir::Left, 1);
  380. addNudge(Qt::Key_Right, MoveDir::Right, 1);
  381. addNudge(Qt::SHIFT | Qt::Key_Up, MoveDir::Up, 10);
  382. addNudge(Qt::SHIFT | Qt::Key_Down, MoveDir::Down, 10);
  383. addNudge(Qt::SHIFT | Qt::Key_Left, MoveDir::Left, 10);
  384. addNudge(Qt::SHIFT | Qt::Key_Right, MoveDir::Right, 10);
  385. /* Setup dock toggle action
  386. * And hide all docks before restoring parent geometry */
  387. #define SETUP_DOCK(dock) \
  388. setupDockAction(dock); \
  389. ui->menuDocks->addAction(dock->toggleViewAction()); \
  390. dock->setVisible(false);
  391. SETUP_DOCK(ui->scenesDock);
  392. SETUP_DOCK(ui->sourcesDock);
  393. SETUP_DOCK(ui->mixerDock);
  394. SETUP_DOCK(ui->transitionsDock);
  395. SETUP_DOCK(ui->controlsDock);
  396. SETUP_DOCK(statsDock);
  397. #undef SETUP_DOCK
  398. // Register shortcuts for Undo/Redo
  399. ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z);
  400. QList<QKeySequence> shrt;
  401. shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z)
  402. << QKeySequence(Qt::CTRL | Qt::Key_Y);
  403. ui->actionMainRedo->setShortcuts(shrt);
  404. ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut);
  405. ui->actionMainRedo->setShortcutContext(Qt::ApplicationShortcut);
  406. QPoint curPos;
  407. //restore parent window geometry
  408. const char *geometry = config_get_string(App()->GlobalConfig(),
  409. "BasicWindow", "geometry");
  410. if (geometry != NULL) {
  411. QByteArray byteArray =
  412. QByteArray::fromBase64(QByteArray(geometry));
  413. restoreGeometry(byteArray);
  414. QRect windowGeometry = normalGeometry();
  415. if (!WindowPositionValid(windowGeometry)) {
  416. QRect rect =
  417. QGuiApplication::primaryScreen()->geometry();
  418. setGeometry(QStyle::alignedRect(Qt::LeftToRight,
  419. Qt::AlignCenter, size(),
  420. rect));
  421. }
  422. curPos = pos();
  423. } else {
  424. QRect desktopRect =
  425. QGuiApplication::primaryScreen()->geometry();
  426. QSize adjSize = desktopRect.size() / 2 - size() / 2;
  427. curPos = QPoint(adjSize.width(), adjSize.height());
  428. }
  429. QPoint curSize(width(), height());
  430. QPoint statsDockSize(statsDock->width(), statsDock->height());
  431. QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
  432. QPoint newPos = curPos + statsDockPos;
  433. statsDock->move(newPos);
  434. ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
  435. connect(ui->enablePreviewButton, &QPushButton::clicked, this,
  436. &OBSBasic::TogglePreview);
  437. connect(ui->scenes, &SceneTree::scenesReordered,
  438. []() { OBSProjector::UpdateMultiviewProjectors(); });
  439. connect(ui->broadcastButton, &QPushButton::clicked, this,
  440. &OBSBasic::BroadcastButtonClicked);
  441. connect(App(), &OBSApp::StyleChanged, this, &OBSBasic::ThemeChanged);
  442. QActionGroup *actionGroup = new QActionGroup(this);
  443. actionGroup->addAction(ui->actionSceneListMode);
  444. actionGroup->addAction(ui->actionSceneGridMode);
  445. UpdatePreviewSafeAreas();
  446. UpdatePreviewSpacingHelpers();
  447. UpdatePreviewOverflowSettings();
  448. }
  449. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
  450. vector<OBSSource> &audioSources)
  451. {
  452. OBSSourceAutoRelease source = obs_get_output_source(channel);
  453. if (!source)
  454. return;
  455. audioSources.push_back(source.Get());
  456. OBSDataAutoRelease data = obs_save_source(source);
  457. obs_data_set_obj(parent, name, data);
  458. }
  459. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
  460. obs_data_array_t *quickTransitionData,
  461. int transitionDuration,
  462. obs_data_array_t *transitions,
  463. OBSScene &scene, OBSSource &curProgramScene,
  464. obs_data_array_t *savedProjectorList)
  465. {
  466. obs_data_t *saveData = obs_data_create();
  467. vector<OBSSource> audioSources;
  468. audioSources.reserve(6);
  469. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  470. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  471. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  472. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  473. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  474. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  475. /* -------------------------------- */
  476. /* save non-group sources */
  477. auto FilterAudioSources = [&](obs_source_t *source) {
  478. if (obs_source_is_group(source))
  479. return false;
  480. return find(begin(audioSources), end(audioSources), source) ==
  481. end(audioSources);
  482. };
  483. using FilterAudioSources_t = decltype(FilterAudioSources);
  484. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  485. [](void *data, obs_source_t *source) {
  486. auto &func = *static_cast<FilterAudioSources_t *>(data);
  487. return func(source);
  488. },
  489. static_cast<void *>(&FilterAudioSources));
  490. /* -------------------------------- */
  491. /* save group sources separately */
  492. /* saving separately ensures they won't be loaded in older versions */
  493. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  494. [](void *, obs_source_t *source) {
  495. return obs_source_is_group(source);
  496. },
  497. nullptr);
  498. /* -------------------------------- */
  499. OBSSourceAutoRelease transition = obs_get_output_source(0);
  500. obs_source_t *currentScene = obs_scene_get_source(scene);
  501. const char *sceneName = obs_source_get_name(currentScene);
  502. const char *programName = obs_source_get_name(curProgramScene);
  503. const char *sceneCollection = config_get_string(
  504. App()->GlobalConfig(), "Basic", "SceneCollection");
  505. obs_data_set_string(saveData, "current_scene", sceneName);
  506. obs_data_set_string(saveData, "current_program_scene", programName);
  507. obs_data_set_array(saveData, "scene_order", sceneOrder);
  508. obs_data_set_string(saveData, "name", sceneCollection);
  509. obs_data_set_array(saveData, "sources", sourcesArray);
  510. obs_data_set_array(saveData, "groups", groupsArray);
  511. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  512. obs_data_set_array(saveData, "transitions", transitions);
  513. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  514. obs_data_array_release(sourcesArray);
  515. obs_data_array_release(groupsArray);
  516. obs_data_set_string(saveData, "current_transition",
  517. obs_source_get_name(transition));
  518. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  519. return saveData;
  520. }
  521. void OBSBasic::copyActionsDynamicProperties()
  522. {
  523. // Themes need the QAction dynamic properties
  524. for (QAction *x : ui->scenesToolbar->actions()) {
  525. QWidget *temp = ui->scenesToolbar->widgetForAction(x);
  526. if (!temp)
  527. continue;
  528. for (QByteArray &y : x->dynamicPropertyNames()) {
  529. temp->setProperty(y, x->property(y));
  530. }
  531. }
  532. for (QAction *x : ui->sourcesToolbar->actions()) {
  533. QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
  534. if (!temp)
  535. continue;
  536. for (QByteArray &y : x->dynamicPropertyNames()) {
  537. temp->setProperty(y, x->property(y));
  538. }
  539. }
  540. for (QAction *x : ui->mixerToolbar->actions()) {
  541. QWidget *temp = ui->mixerToolbar->widgetForAction(x);
  542. if (!temp)
  543. continue;
  544. for (QByteArray &y : x->dynamicPropertyNames()) {
  545. temp->setProperty(y, x->property(y));
  546. }
  547. }
  548. }
  549. void OBSBasic::UpdateVolumeControlsDecayRate()
  550. {
  551. double meterDecayRate =
  552. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  553. for (size_t i = 0; i < volumes.size(); i++) {
  554. volumes[i]->SetMeterDecayRate(meterDecayRate);
  555. }
  556. }
  557. void OBSBasic::UpdateVolumeControlsPeakMeterType()
  558. {
  559. uint32_t peakMeterTypeIdx =
  560. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  561. enum obs_peak_meter_type peakMeterType;
  562. switch (peakMeterTypeIdx) {
  563. case 0:
  564. peakMeterType = SAMPLE_PEAK_METER;
  565. break;
  566. case 1:
  567. peakMeterType = TRUE_PEAK_METER;
  568. break;
  569. default:
  570. peakMeterType = SAMPLE_PEAK_METER;
  571. break;
  572. }
  573. for (size_t i = 0; i < volumes.size(); i++) {
  574. volumes[i]->setPeakMeterType(peakMeterType);
  575. }
  576. }
  577. void OBSBasic::ClearVolumeControls()
  578. {
  579. for (VolControl *vol : volumes)
  580. delete vol;
  581. volumes.clear();
  582. }
  583. void OBSBasic::RefreshVolumeColors()
  584. {
  585. for (VolControl *vol : volumes) {
  586. vol->refreshColors();
  587. }
  588. }
  589. obs_data_array_t *OBSBasic::SaveSceneListOrder()
  590. {
  591. obs_data_array_t *sceneOrder = obs_data_array_create();
  592. for (int i = 0; i < ui->scenes->count(); i++) {
  593. OBSDataAutoRelease data = obs_data_create();
  594. obs_data_set_string(data, "name",
  595. QT_TO_UTF8(ui->scenes->item(i)->text()));
  596. obs_data_array_push_back(sceneOrder, data);
  597. }
  598. return sceneOrder;
  599. }
  600. obs_data_array_t *OBSBasic::SaveProjectors()
  601. {
  602. obs_data_array_t *savedProjectors = obs_data_array_create();
  603. auto saveProjector = [savedProjectors](OBSProjector *projector) {
  604. if (!projector)
  605. return;
  606. OBSDataAutoRelease data = obs_data_create();
  607. ProjectorType type = projector->GetProjectorType();
  608. switch (type) {
  609. case ProjectorType::Scene:
  610. case ProjectorType::Source: {
  611. OBSSource source = projector->GetSource();
  612. const char *name = obs_source_get_name(source);
  613. obs_data_set_string(data, "name", name);
  614. break;
  615. }
  616. default:
  617. break;
  618. }
  619. obs_data_set_int(data, "monitor", projector->GetMonitor());
  620. obs_data_set_int(data, "type", static_cast<int>(type));
  621. obs_data_set_string(
  622. data, "geometry",
  623. projector->saveGeometry().toBase64().constData());
  624. if (projector->IsAlwaysOnTopOverridden())
  625. obs_data_set_bool(data, "alwaysOnTop",
  626. projector->IsAlwaysOnTop());
  627. obs_data_set_bool(data, "alwaysOnTopOverridden",
  628. projector->IsAlwaysOnTopOverridden());
  629. obs_data_array_push_back(savedProjectors, data);
  630. };
  631. for (size_t i = 0; i < projectors.size(); i++)
  632. saveProjector(static_cast<OBSProjector *>(projectors[i]));
  633. return savedProjectors;
  634. }
  635. void OBSBasic::Save(const char *file)
  636. {
  637. OBSScene scene = GetCurrentScene();
  638. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  639. if (!curProgramScene)
  640. curProgramScene = obs_scene_get_source(scene);
  641. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  642. OBSDataArrayAutoRelease transitions = SaveTransitions();
  643. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  644. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  645. OBSDataAutoRelease saveData = GenerateSaveData(
  646. sceneOrder, quickTrData, ui->transitionDuration->value(),
  647. transitions, scene, curProgramScene, savedProjectorList);
  648. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  649. obs_data_set_bool(saveData, "scaling_enabled",
  650. ui->preview->IsFixedScaling());
  651. obs_data_set_int(saveData, "scaling_level",
  652. ui->preview->GetScalingLevel());
  653. obs_data_set_double(saveData, "scaling_off_x",
  654. ui->preview->GetScrollX());
  655. obs_data_set_double(saveData, "scaling_off_y",
  656. ui->preview->GetScrollY());
  657. if (vcamEnabled) {
  658. OBSDataAutoRelease obj = obs_data_create();
  659. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  660. switch (vcamConfig.type) {
  661. case VCamOutputType::Invalid:
  662. case VCamOutputType::ProgramView:
  663. case VCamOutputType::PreviewOutput:
  664. break;
  665. case VCamOutputType::SceneOutput:
  666. obs_data_set_string(obj, "scene",
  667. vcamConfig.scene.c_str());
  668. break;
  669. case VCamOutputType::SourceOutput:
  670. obs_data_set_string(obj, "source",
  671. vcamConfig.source.c_str());
  672. break;
  673. }
  674. obs_data_set_obj(saveData, "virtual-camera", obj);
  675. }
  676. if (api) {
  677. if (safeModeModuleData) {
  678. /* If we're in Safe Mode and have retained unloaded
  679. * plugin data, update the existing data object instead
  680. * of creating a new one. */
  681. api->on_save(safeModeModuleData);
  682. obs_data_set_obj(saveData, "modules",
  683. safeModeModuleData);
  684. } else {
  685. OBSDataAutoRelease moduleObj = obs_data_create();
  686. api->on_save(moduleObj);
  687. obs_data_set_obj(saveData, "modules", moduleObj);
  688. }
  689. }
  690. if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
  691. blog(LOG_ERROR, "Could not save scene data to %s", file);
  692. }
  693. void OBSBasic::DeferSaveBegin()
  694. {
  695. os_atomic_inc_long(&disableSaving);
  696. }
  697. void OBSBasic::DeferSaveEnd()
  698. {
  699. long result = os_atomic_dec_long(&disableSaving);
  700. if (result == 0) {
  701. SaveProject();
  702. }
  703. }
  704. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  705. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  706. {
  707. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  708. if (!data)
  709. return;
  710. OBSSourceAutoRelease source = obs_load_source(data);
  711. if (!source)
  712. return;
  713. obs_set_output_source(channel, source);
  714. const char *source_name = obs_source_get_name(source);
  715. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  716. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  717. obs_monitoring_type monitoring_type =
  718. obs_source_get_monitoring_type(source);
  719. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  720. const char *type =
  721. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  722. ? "monitor only"
  723. : "monitor and output";
  724. blog(LOG_INFO, " - monitoring: %s", type);
  725. }
  726. }
  727. static inline bool HasAudioDevices(const char *source_id)
  728. {
  729. const char *output_id = source_id;
  730. obs_properties_t *props = obs_get_source_properties(output_id);
  731. size_t count = 0;
  732. if (!props)
  733. return false;
  734. obs_property_t *devices = obs_properties_get(props, "device_id");
  735. if (devices)
  736. count = obs_property_list_item_count(devices);
  737. obs_properties_destroy(props);
  738. return count != 0;
  739. }
  740. void OBSBasic::CreateFirstRunSources()
  741. {
  742. bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
  743. bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
  744. if (hasDesktopAudio)
  745. ResetAudioDevice(App()->OutputAudioSource(), "default",
  746. Str("Basic.DesktopDevice1"), 1);
  747. if (hasInputAudio)
  748. ResetAudioDevice(App()->InputAudioSource(), "default",
  749. Str("Basic.AuxDevice1"), 3);
  750. }
  751. void OBSBasic::CreateDefaultScene(bool firstStart)
  752. {
  753. disableSaving++;
  754. ClearSceneData();
  755. InitDefaultTransitions();
  756. CreateDefaultQuickTransitions();
  757. ui->transitionDuration->setValue(300);
  758. SetTransition(fadeTransition);
  759. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  760. if (firstStart)
  761. CreateFirstRunSources();
  762. SetCurrentScene(scene, true);
  763. disableSaving--;
  764. }
  765. static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
  766. {
  767. for (int i = 0; i < lw->count(); i++) {
  768. QListWidgetItem *item = lw->item(i);
  769. if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
  770. if (newIndex != i) {
  771. item = lw->takeItem(i);
  772. lw->insertItem(newIndex, item);
  773. }
  774. break;
  775. }
  776. }
  777. }
  778. void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
  779. {
  780. size_t num = obs_data_array_count(array);
  781. for (size_t i = 0; i < num; i++) {
  782. OBSDataAutoRelease data = obs_data_array_item(array, i);
  783. const char *name = obs_data_get_string(data, "name");
  784. ReorderItemByName(ui->scenes, name, (int)i);
  785. }
  786. }
  787. void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
  788. {
  789. for (SavedProjectorInfo *info : savedProjectorsArray) {
  790. delete info;
  791. }
  792. savedProjectorsArray.clear();
  793. size_t num = obs_data_array_count(array);
  794. for (size_t i = 0; i < num; i++) {
  795. OBSDataAutoRelease data = obs_data_array_item(array, i);
  796. SavedProjectorInfo *info = new SavedProjectorInfo();
  797. info->monitor = obs_data_get_int(data, "monitor");
  798. info->type = static_cast<ProjectorType>(
  799. obs_data_get_int(data, "type"));
  800. info->geometry =
  801. std::string(obs_data_get_string(data, "geometry"));
  802. info->name = std::string(obs_data_get_string(data, "name"));
  803. info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop");
  804. info->alwaysOnTopOverridden =
  805. obs_data_get_bool(data, "alwaysOnTopOverridden");
  806. savedProjectorsArray.emplace_back(info);
  807. }
  808. }
  809. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  810. {
  811. const char *name = obs_source_get_name(filter);
  812. const char *id = obs_source_get_id(filter);
  813. int val = (int)(intptr_t)v_val;
  814. string indent;
  815. for (int i = 0; i < val; i++)
  816. indent += " ";
  817. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  818. }
  819. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  820. {
  821. obs_source_t *source = obs_sceneitem_get_source(item);
  822. const char *name = obs_source_get_name(source);
  823. const char *id = obs_source_get_id(source);
  824. int indent_count = (int)(intptr_t)v_val;
  825. string indent;
  826. for (int i = 0; i < indent_count; i++)
  827. indent += " ";
  828. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  829. obs_monitoring_type monitoring_type =
  830. obs_source_get_monitoring_type(source);
  831. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  832. const char *type =
  833. (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
  834. ? "monitor only"
  835. : "monitor and output";
  836. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  837. }
  838. int child_indent = 1 + indent_count;
  839. obs_source_enum_filters(source, LogFilter,
  840. (void *)(intptr_t)child_indent);
  841. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  842. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  843. if (show_tn)
  844. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(),
  845. obs_source_get_name(show_tn), obs_source_get_id(show_tn));
  846. if (hide_tn)
  847. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(),
  848. obs_source_get_name(hide_tn), obs_source_get_id(hide_tn));
  849. if (obs_sceneitem_is_group(item))
  850. obs_sceneitem_group_enum_items(item, LogSceneItem,
  851. (void *)(intptr_t)child_indent);
  852. return true;
  853. }
  854. void OBSBasic::LogScenes()
  855. {
  856. blog(LOG_INFO, "------------------------------------------------");
  857. blog(LOG_INFO, "Loaded scenes:");
  858. for (int i = 0; i < ui->scenes->count(); i++) {
  859. QListWidgetItem *item = ui->scenes->item(i);
  860. OBSScene scene = GetOBSRef<OBSScene>(item);
  861. obs_source_t *source = obs_scene_get_source(scene);
  862. const char *name = obs_source_get_name(source);
  863. blog(LOG_INFO, "- scene '%s':", name);
  864. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  865. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  866. }
  867. blog(LOG_INFO, "------------------------------------------------");
  868. }
  869. void OBSBasic::Load(const char *file)
  870. {
  871. disableSaving++;
  872. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  873. if (!data) {
  874. disableSaving--;
  875. blog(LOG_INFO, "No scene file found, creating default scene");
  876. CreateDefaultScene(true);
  877. SaveProject();
  878. return;
  879. }
  880. LoadData(data, file);
  881. }
  882. static inline void AddMissingFiles(void *data, obs_source_t *source)
  883. {
  884. obs_missing_files_t *f = (obs_missing_files_t *)data;
  885. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  886. obs_missing_files_append(f, sf);
  887. obs_missing_files_destroy(sf);
  888. }
  889. void OBSBasic::LoadData(obs_data_t *data, const char *file)
  890. {
  891. ClearSceneData();
  892. ClearContextBar();
  893. /* Exit OBS if clearing scene data failed for some reason. */
  894. if (clearingFailed) {
  895. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"),
  896. QTStr("SourceLeak.Text"));
  897. close();
  898. return;
  899. }
  900. InitDefaultTransitions();
  901. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  902. devicePropertiesThread->wait();
  903. devicePropertiesThread.reset();
  904. }
  905. QApplication::sendPostedEvents(nullptr);
  906. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  907. if (api)
  908. api->on_preload(modulesObj);
  909. if (safe_mode || disable_3p_plugins) {
  910. /* Keep a reference to "modules" data so plugins that are not
  911. * loaded do not have their collection specific data lost. */
  912. safeModeModuleData = obs_data_get_obj(data, "modules");
  913. }
  914. OBSDataArrayAutoRelease sceneOrder =
  915. obs_data_get_array(data, "scene_order");
  916. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  917. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  918. OBSDataArrayAutoRelease transitions =
  919. obs_data_get_array(data, "transitions");
  920. const char *sceneName = obs_data_get_string(data, "current_scene");
  921. const char *programSceneName =
  922. obs_data_get_string(data, "current_program_scene");
  923. const char *transitionName =
  924. obs_data_get_string(data, "current_transition");
  925. if (!opt_starting_scene.empty()) {
  926. programSceneName = opt_starting_scene.c_str();
  927. if (!IsPreviewProgramMode())
  928. sceneName = opt_starting_scene.c_str();
  929. }
  930. int newDuration = obs_data_get_int(data, "transition_duration");
  931. if (!newDuration)
  932. newDuration = 300;
  933. if (!transitionName)
  934. transitionName = obs_source_get_name(fadeTransition);
  935. const char *curSceneCollection = config_get_string(
  936. App()->GlobalConfig(), "Basic", "SceneCollection");
  937. obs_data_set_default_string(data, "name", curSceneCollection);
  938. const char *name = obs_data_get_string(data, "name");
  939. OBSSourceAutoRelease curScene;
  940. OBSSourceAutoRelease curProgramScene;
  941. obs_source_t *curTransition;
  942. if (!name || !*name)
  943. name = curSceneCollection;
  944. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  945. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  946. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  947. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  948. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  949. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  950. if (!sources) {
  951. sources = std::move(groups);
  952. } else {
  953. obs_data_array_push_back_array(sources, groups);
  954. }
  955. obs_missing_files_t *files = obs_missing_files_create();
  956. obs_load_sources(sources, AddMissingFiles, files);
  957. if (transitions)
  958. LoadTransitions(transitions, AddMissingFiles, files);
  959. if (sceneOrder)
  960. LoadSceneListOrder(sceneOrder);
  961. curTransition = FindTransition(transitionName);
  962. if (!curTransition)
  963. curTransition = fadeTransition;
  964. ui->transitionDuration->setValue(newDuration);
  965. SetTransition(curTransition);
  966. retryScene:
  967. curScene = obs_get_source_by_name(sceneName);
  968. curProgramScene = obs_get_source_by_name(programSceneName);
  969. /* if the starting scene command line parameter is bad at all,
  970. * fall back to original settings */
  971. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  972. sceneName = obs_data_get_string(data, "current_scene");
  973. programSceneName =
  974. obs_data_get_string(data, "current_program_scene");
  975. opt_starting_scene.clear();
  976. goto retryScene;
  977. }
  978. SetCurrentScene(curScene.Get(), true);
  979. if (!curProgramScene)
  980. curProgramScene = std::move(curScene);
  981. if (IsPreviewProgramMode())
  982. TransitionToScene(curProgramScene.Get(), true);
  983. /* ------------------- */
  984. bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
  985. "SaveProjectors");
  986. if (projectorSave) {
  987. OBSDataArrayAutoRelease savedProjectors =
  988. obs_data_get_array(data, "saved_projectors");
  989. if (savedProjectors) {
  990. LoadSavedProjectors(savedProjectors);
  991. OpenSavedProjectors();
  992. activateWindow();
  993. }
  994. }
  995. /* ------------------- */
  996. std::string file_base = strrchr(file, '/') + 1;
  997. file_base.erase(file_base.size() - 5, 5);
  998. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
  999. name);
  1000. config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
  1001. file_base.c_str());
  1002. OBSDataArrayAutoRelease quickTransitionData =
  1003. obs_data_get_array(data, "quick_transitions");
  1004. LoadQuickTransitions(quickTransitionData);
  1005. RefreshQuickTransitions();
  1006. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1007. ui->preview->SetLocked(previewLocked);
  1008. ui->actionLockPreview->setChecked(previewLocked);
  1009. /* ---------------------- */
  1010. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1011. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1012. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1013. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1014. if (fixedScaling) {
  1015. ui->preview->SetScalingLevel(scalingLevel);
  1016. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1017. }
  1018. ui->preview->SetFixedScaling(fixedScaling);
  1019. emit ui->preview->DisplayResized();
  1020. if (vcamEnabled) {
  1021. OBSDataAutoRelease obj =
  1022. obs_data_get_obj(data, "virtual-camera");
  1023. vcamConfig.type =
  1024. (VCamOutputType)obs_data_get_int(obj, "type2");
  1025. if (vcamConfig.type == VCamOutputType::Invalid)
  1026. vcamConfig.type =
  1027. (VCamOutputType)obs_data_get_int(obj, "type");
  1028. if (vcamConfig.type == VCamOutputType::Invalid) {
  1029. VCamInternalType internal =
  1030. (VCamInternalType)obs_data_get_int(obj,
  1031. "internal");
  1032. switch (internal) {
  1033. case VCamInternalType::Default:
  1034. vcamConfig.type = VCamOutputType::ProgramView;
  1035. break;
  1036. case VCamInternalType::Preview:
  1037. vcamConfig.type = VCamOutputType::PreviewOutput;
  1038. break;
  1039. }
  1040. }
  1041. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1042. vcamConfig.source = obs_data_get_string(obj, "source");
  1043. }
  1044. /* ---------------------- */
  1045. if (api)
  1046. api->on_load(modulesObj);
  1047. obs_data_release(data);
  1048. if (!opt_starting_scene.empty())
  1049. opt_starting_scene.clear();
  1050. if (opt_start_streaming && !safe_mode) {
  1051. blog(LOG_INFO, "Starting stream due to command line parameter");
  1052. QMetaObject::invokeMethod(this, "StartStreaming",
  1053. Qt::QueuedConnection);
  1054. opt_start_streaming = false;
  1055. }
  1056. if (opt_start_recording && !safe_mode) {
  1057. blog(LOG_INFO,
  1058. "Starting recording due to command line parameter");
  1059. QMetaObject::invokeMethod(this, "StartRecording",
  1060. Qt::QueuedConnection);
  1061. opt_start_recording = false;
  1062. }
  1063. if (opt_start_replaybuffer && !safe_mode) {
  1064. QMetaObject::invokeMethod(this, "StartReplayBuffer",
  1065. Qt::QueuedConnection);
  1066. opt_start_replaybuffer = false;
  1067. }
  1068. if (opt_start_virtualcam && !safe_mode) {
  1069. QMetaObject::invokeMethod(this, "StartVirtualCam",
  1070. Qt::QueuedConnection);
  1071. opt_start_virtualcam = false;
  1072. }
  1073. LogScenes();
  1074. if (!App()->IsMissingFilesCheckDisabled())
  1075. ShowMissingFilesDialog(files);
  1076. disableSaving--;
  1077. if (vcamEnabled)
  1078. outputHandler->UpdateVirtualCamOutputSource();
  1079. if (api) {
  1080. api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1081. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1082. }
  1083. }
  1084. #define SERVICE_PATH "service.json"
  1085. void OBSBasic::SaveService()
  1086. {
  1087. if (!service)
  1088. return;
  1089. char serviceJsonPath[512];
  1090. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1091. SERVICE_PATH);
  1092. if (ret <= 0)
  1093. return;
  1094. OBSDataAutoRelease data = obs_data_create();
  1095. OBSDataAutoRelease settings = obs_service_get_settings(service);
  1096. obs_data_set_string(data, "type", obs_service_get_type(service));
  1097. obs_data_set_obj(data, "settings", settings);
  1098. if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
  1099. blog(LOG_WARNING, "Failed to save service");
  1100. }
  1101. bool OBSBasic::LoadService()
  1102. {
  1103. const char *type;
  1104. char serviceJsonPath[512];
  1105. int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
  1106. SERVICE_PATH);
  1107. if (ret <= 0)
  1108. return false;
  1109. OBSDataAutoRelease data =
  1110. obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
  1111. if (!data)
  1112. return false;
  1113. obs_data_set_default_string(data, "type", "rtmp_common");
  1114. type = obs_data_get_string(data, "type");
  1115. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  1116. OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys");
  1117. service = obs_service_create(type, "default_service", settings,
  1118. hotkey_data);
  1119. obs_service_release(service);
  1120. if (!service)
  1121. return false;
  1122. /* Enforce Opus on FTL if needed */
  1123. if (strcmp(obs_service_get_protocol(service), "FTL") == 0 ||
  1124. strcmp(obs_service_get_protocol(service), "WHIP") == 0) {
  1125. const char *option = config_get_string(
  1126. basicConfig, "SimpleOutput", "StreamAudioEncoder");
  1127. if (strcmp(option, "opus") != 0)
  1128. config_set_string(basicConfig, "SimpleOutput",
  1129. "StreamAudioEncoder", "opus");
  1130. option = config_get_string(basicConfig, "AdvOut",
  1131. "AudioEncoder");
  1132. if (strcmp(obs_get_encoder_codec(option), "opus") != 0)
  1133. config_set_string(basicConfig, "AdvOut", "AudioEncoder",
  1134. "ffmpeg_opus");
  1135. }
  1136. return true;
  1137. }
  1138. bool OBSBasic::InitService()
  1139. {
  1140. ProfileScope("OBSBasic::InitService");
  1141. if (LoadService())
  1142. return true;
  1143. service = obs_service_create("rtmp_common", "default_service", nullptr,
  1144. nullptr);
  1145. if (!service)
  1146. return false;
  1147. obs_service_release(service);
  1148. return true;
  1149. }
  1150. static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5,
  1151. (1.0 / 0.6), 1.75, 2.0, 2.25,
  1152. 2.5, 2.75, 3.0, 0.0};
  1153. extern void CheckExistingCookieId();
  1154. #if OBS_RELEASE_CANDIDATE == 0 && OBS_BETA == 0
  1155. #define DEFAULT_CONTAINER "mkv"
  1156. #elif defined(__APPLE__)
  1157. #define DEFAULT_CONTAINER "fragmented_mov"
  1158. #else
  1159. #define DEFAULT_CONTAINER "fragmented_mp4"
  1160. #endif
  1161. bool OBSBasic::InitBasicConfigDefaults()
  1162. {
  1163. QList<QScreen *> screens = QGuiApplication::screens();
  1164. if (!screens.size()) {
  1165. OBSErrorBox(NULL, "There appears to be no monitors. Er, this "
  1166. "technically shouldn't be possible.");
  1167. return false;
  1168. }
  1169. QScreen *primaryScreen = QGuiApplication::primaryScreen();
  1170. uint32_t cx = primaryScreen->size().width();
  1171. uint32_t cy = primaryScreen->size().height();
  1172. cx *= devicePixelRatioF();
  1173. cy *= devicePixelRatioF();
  1174. bool oldResolutionDefaults = config_get_bool(
  1175. App()->GlobalConfig(), "General", "Pre19Defaults");
  1176. /* use 1920x1080 for new default base res if main monitor is above
  1177. * 1920x1080, but don't apply for people from older builds -- only to
  1178. * new users */
  1179. if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
  1180. cx = 1920;
  1181. cy = 1080;
  1182. }
  1183. bool changed = false;
  1184. /* ----------------------------------------------------- */
  1185. /* move over old FFmpeg track settings */
  1186. if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
  1187. !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {
  1188. int track = (int)config_get_int(basicConfig, "AdvOut",
  1189. "FFAudioTrack");
  1190. config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
  1191. 1LL << (track - 1));
  1192. config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
  1193. changed = true;
  1194. }
  1195. /* ----------------------------------------------------- */
  1196. /* move over mixer values in advanced if older config */
  1197. if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
  1198. !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {
  1199. uint64_t track =
  1200. config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
  1201. track = 1ULL << (track - 1);
  1202. config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
  1203. config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
  1204. changed = true;
  1205. }
  1206. /* ----------------------------------------------------- */
  1207. /* set twitch chat extensions to "both" if prev version */
  1208. /* is under 24.1 */
  1209. if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
  1210. !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
  1211. config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
  1212. changed = true;
  1213. }
  1214. /* ----------------------------------------------------- */
  1215. /* move bitrate enforcement setting to new value */
  1216. if (config_has_user_value(basicConfig, "SimpleOutput",
  1217. "EnforceBitrate") &&
  1218. !config_has_user_value(basicConfig, "Stream1",
  1219. "IgnoreRecommended") &&
  1220. !config_has_user_value(basicConfig, "Stream1", "MovedOldEnforce")) {
  1221. bool enforce = config_get_bool(basicConfig, "SimpleOutput",
  1222. "EnforceBitrate");
  1223. config_set_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1224. !enforce);
  1225. config_set_bool(basicConfig, "Stream1", "MovedOldEnforce",
  1226. true);
  1227. changed = true;
  1228. }
  1229. /* ----------------------------------------------------- */
  1230. /* enforce minimum retry delay of 1 second prior to 27.1 */
  1231. if (config_has_user_value(basicConfig, "Output", "RetryDelay")) {
  1232. int retryDelay =
  1233. config_get_uint(basicConfig, "Output", "RetryDelay");
  1234. if (retryDelay < 1) {
  1235. config_set_uint(basicConfig, "Output", "RetryDelay", 1);
  1236. changed = true;
  1237. }
  1238. }
  1239. /* ----------------------------------------------------- */
  1240. /* Migrate old container selection (if any) to new key. */
  1241. auto MigrateFormat = [&](const char *section) {
  1242. bool has_old_key = config_has_user_value(basicConfig, section,
  1243. "RecFormat");
  1244. bool has_new_key = config_has_user_value(basicConfig, section,
  1245. "RecFormat2");
  1246. if (!has_new_key && !has_old_key)
  1247. return;
  1248. string old_format = config_get_string(
  1249. basicConfig, section,
  1250. has_new_key ? "RecFormat2" : "RecFormat");
  1251. string new_format = old_format;
  1252. if (old_format == "ts")
  1253. new_format = "mpegts";
  1254. else if (old_format == "m3u8")
  1255. new_format = "hls";
  1256. else if (old_format == "fmp4")
  1257. new_format = "fragmented_mp4";
  1258. else if (old_format == "fmov")
  1259. new_format = "fragmented_mov";
  1260. if (new_format != old_format || !has_new_key) {
  1261. config_set_string(basicConfig, section, "RecFormat2",
  1262. new_format.c_str());
  1263. changed = true;
  1264. }
  1265. };
  1266. MigrateFormat("AdvOut");
  1267. MigrateFormat("SimpleOutput");
  1268. /* ----------------------------------------------------- */
  1269. if (changed)
  1270. config_save_safe(basicConfig, "tmp", nullptr);
  1271. /* ----------------------------------------------------- */
  1272. config_set_default_string(basicConfig, "Output", "Mode", "Simple");
  1273. config_set_default_bool(basicConfig, "Stream1", "IgnoreRecommended",
  1274. false);
  1275. config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
  1276. GetDefaultVideoSavePath().c_str());
  1277. config_set_default_string(basicConfig, "SimpleOutput", "RecFormat2",
  1278. DEFAULT_CONTAINER);
  1279. config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
  1280. config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
  1281. config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
  1282. false);
  1283. config_set_default_string(basicConfig, "SimpleOutput", "Preset",
  1284. "veryfast");
  1285. config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset2",
  1286. "p5");
  1287. config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
  1288. "Stream");
  1289. config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
  1290. config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
  1291. config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
  1292. config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
  1293. "Replay");
  1294. config_set_default_string(basicConfig, "SimpleOutput",
  1295. "StreamAudioEncoder", "aac");
  1296. config_set_default_string(basicConfig, "SimpleOutput",
  1297. "RecAudioEncoder", "aac");
  1298. config_set_default_uint(basicConfig, "SimpleOutput", "RecTracks",
  1299. (1 << 0));
  1300. config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
  1301. true);
  1302. config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
  1303. config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
  1304. config_set_default_uint(basicConfig, "AdvOut", "VodTrackIndex", 2);
  1305. config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");
  1306. config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");
  1307. config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
  1308. GetDefaultVideoSavePath().c_str());
  1309. config_set_default_string(basicConfig, "AdvOut", "RecFormat2",
  1310. DEFAULT_CONTAINER);
  1311. config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
  1312. config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
  1313. config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
  1314. config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
  1315. config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
  1316. config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
  1317. GetDefaultVideoSavePath().c_str());
  1318. config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
  1319. config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
  1320. config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
  1321. config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
  1322. config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
  1323. config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
  1324. config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);
  1325. config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
  1326. config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
  1327. config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
  1328. config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
  1329. config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
  1330. config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);
  1331. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileTime", 15);
  1332. config_set_default_uint(basicConfig, "AdvOut", "RecSplitFileSize",
  1333. 2048);
  1334. config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
  1335. config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
  1336. config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);
  1337. config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
  1338. config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
  1339. /* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
  1340. if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
  1341. !config_has_user_value(basicConfig, "Video", "BaseCY")) {
  1342. config_set_uint(basicConfig, "Video", "BaseCX", cx);
  1343. config_set_uint(basicConfig, "Video", "BaseCY", cy);
  1344. config_save_safe(basicConfig, "tmp", nullptr);
  1345. }
  1346. config_set_default_string(basicConfig, "Output", "FilenameFormatting",
  1347. "%CCYY-%MM-%DD %hh-%mm-%ss");
  1348. config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
  1349. config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
  1350. config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
  1351. config_set_default_bool(basicConfig, "Output", "Reconnect", true);
  1352. config_set_default_uint(basicConfig, "Output", "RetryDelay", 2);
  1353. config_set_default_uint(basicConfig, "Output", "MaxRetries", 25);
  1354. config_set_default_string(basicConfig, "Output", "BindIP", "default");
  1355. config_set_default_string(basicConfig, "Output", "IPFamily",
  1356. "IPv4+IPv6");
  1357. config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
  1358. false);
  1359. config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
  1360. false);
  1361. int i = 0;
  1362. uint32_t scale_cx = cx;
  1363. uint32_t scale_cy = cy;
  1364. /* use a default scaled resolution that has a pixel count no higher
  1365. * than 1280x720 */
  1366. while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
  1367. double scale = scaled_vals[i++];
  1368. scale_cx = uint32_t(double(cx) / scale);
  1369. scale_cy = uint32_t(double(cy) / scale);
  1370. }
  1371. config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1372. config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1373. /* don't allow OutputCX/OutputCY to be susceptible to defaults
  1374. * changing */
  1375. if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
  1376. !config_has_user_value(basicConfig, "Video", "OutputCY")) {
  1377. config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
  1378. config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
  1379. config_save_safe(basicConfig, "tmp", nullptr);
  1380. }
  1381. config_set_default_uint(basicConfig, "Video", "FPSType", 0);
  1382. config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
  1383. config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
  1384. config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
  1385. config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
  1386. config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
  1387. config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
  1388. config_set_default_string(basicConfig, "Video", "ColorSpace", "709");
  1389. config_set_default_string(basicConfig, "Video", "ColorRange",
  1390. "Partial");
  1391. config_set_default_uint(basicConfig, "Video", "SdrWhiteLevel", 300);
  1392. config_set_default_uint(basicConfig, "Video", "HdrNominalPeakLevel",
  1393. 1000);
  1394. config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
  1395. "default");
  1396. config_set_default_string(
  1397. basicConfig, "Audio", "MonitoringDeviceName",
  1398. Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
  1399. ".Default"));
  1400. config_set_default_uint(basicConfig, "Audio", "SampleRate", 48000);
  1401. config_set_default_string(basicConfig, "Audio", "ChannelSetup",
  1402. "Stereo");
  1403. config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
  1404. VOLUME_METER_DECAY_FAST);
  1405. config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
  1406. CheckExistingCookieId();
  1407. return true;
  1408. }
  1409. extern bool EncoderAvailable(const char *encoder);
  1410. extern bool update_nvenc_presets(ConfigFile &config);
  1411. void OBSBasic::InitBasicConfigDefaults2()
  1412. {
  1413. bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
  1414. "Pre23Defaults");
  1415. bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;
  1416. config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
  1417. useNV ? SIMPLE_ENCODER_NVENC
  1418. : SIMPLE_ENCODER_X264);
  1419. config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
  1420. useNV ? SIMPLE_ENCODER_NVENC
  1421. : SIMPLE_ENCODER_X264);
  1422. const char *aac_default = "ffmpeg_aac";
  1423. if (EncoderAvailable("CoreAudio_AAC"))
  1424. aac_default = "CoreAudio_AAC";
  1425. else if (EncoderAvailable("libfdk_aac"))
  1426. aac_default = "libfdk_aac";
  1427. config_set_default_string(basicConfig, "AdvOut", "AudioEncoder",
  1428. aac_default);
  1429. config_set_default_string(basicConfig, "AdvOut", "RecAudioEncoder",
  1430. aac_default);
  1431. if (update_nvenc_presets(basicConfig))
  1432. config_save_safe(basicConfig, "tmp", nullptr);
  1433. }
  1434. bool OBSBasic::InitBasicConfig()
  1435. {
  1436. ProfileScope("OBSBasic::InitBasicConfig");
  1437. char configPath[512];
  1438. int ret = GetProfilePath(configPath, sizeof(configPath), "");
  1439. if (ret <= 0) {
  1440. OBSErrorBox(nullptr, "Failed to get profile path");
  1441. return false;
  1442. }
  1443. if (os_mkdir(configPath) == MKDIR_ERROR) {
  1444. OBSErrorBox(nullptr, "Failed to create profile path");
  1445. return false;
  1446. }
  1447. ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
  1448. if (ret <= 0) {
  1449. OBSErrorBox(nullptr, "Failed to get basic.ini path");
  1450. return false;
  1451. }
  1452. int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
  1453. if (code != CONFIG_SUCCESS) {
  1454. OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
  1455. return false;
  1456. }
  1457. if (config_get_string(basicConfig, "General", "Name") == nullptr) {
  1458. const char *curName = config_get_string(App()->GlobalConfig(),
  1459. "Basic", "Profile");
  1460. config_set_string(basicConfig, "General", "Name", curName);
  1461. basicConfig.SaveSafe("tmp");
  1462. }
  1463. return InitBasicConfigDefaults();
  1464. }
  1465. void OBSBasic::InitOBSCallbacks()
  1466. {
  1467. ProfileScope("OBSBasic::InitOBSCallbacks");
  1468. signalHandlers.reserve(signalHandlers.size() + 7);
  1469. signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
  1470. OBSBasic::SourceCreated, this);
  1471. signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
  1472. OBSBasic::SourceRemoved, this);
  1473. signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
  1474. OBSBasic::SourceActivated, this);
  1475. signalHandlers.emplace_back(obs_get_signal_handler(),
  1476. "source_deactivate",
  1477. OBSBasic::SourceDeactivated, this);
  1478. signalHandlers.emplace_back(obs_get_signal_handler(),
  1479. "source_audio_activate",
  1480. OBSBasic::SourceAudioActivated, this);
  1481. signalHandlers.emplace_back(obs_get_signal_handler(),
  1482. "source_audio_deactivate",
  1483. OBSBasic::SourceAudioDeactivated, this);
  1484. signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
  1485. OBSBasic::SourceRenamed, this);
  1486. }
  1487. void OBSBasic::InitPrimitives()
  1488. {
  1489. ProfileScope("OBSBasic::InitPrimitives");
  1490. obs_enter_graphics();
  1491. gs_render_start(true);
  1492. gs_vertex2f(0.0f, 0.0f);
  1493. gs_vertex2f(0.0f, 1.0f);
  1494. gs_vertex2f(1.0f, 0.0f);
  1495. gs_vertex2f(1.0f, 1.0f);
  1496. box = gs_render_save();
  1497. gs_render_start(true);
  1498. gs_vertex2f(0.0f, 0.0f);
  1499. gs_vertex2f(0.0f, 1.0f);
  1500. boxLeft = gs_render_save();
  1501. gs_render_start(true);
  1502. gs_vertex2f(0.0f, 0.0f);
  1503. gs_vertex2f(1.0f, 0.0f);
  1504. boxTop = gs_render_save();
  1505. gs_render_start(true);
  1506. gs_vertex2f(1.0f, 0.0f);
  1507. gs_vertex2f(1.0f, 1.0f);
  1508. boxRight = gs_render_save();
  1509. gs_render_start(true);
  1510. gs_vertex2f(0.0f, 1.0f);
  1511. gs_vertex2f(1.0f, 1.0f);
  1512. boxBottom = gs_render_save();
  1513. gs_render_start(true);
  1514. for (int i = 0; i <= 360; i += (360 / 20)) {
  1515. float pos = RAD(float(i));
  1516. gs_vertex2f(cosf(pos), sinf(pos));
  1517. }
  1518. circle = gs_render_save();
  1519. InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin,
  1520. &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine);
  1521. obs_leave_graphics();
  1522. }
  1523. void OBSBasic::ReplayBufferClicked()
  1524. {
  1525. if (outputHandler->ReplayBufferActive())
  1526. StopReplayBuffer();
  1527. else
  1528. StartReplayBuffer();
  1529. };
  1530. void OBSBasic::AddVCamButton()
  1531. {
  1532. vcamButton = new ControlsSplitButton(
  1533. QTStr("Basic.Main.StartVirtualCam"), "vcamButton",
  1534. &OBSBasic::VCamButtonClicked);
  1535. vcamButton->addIcon(QTStr("Basic.Main.VirtualCamConfig"),
  1536. QStringLiteral("configIconSmall"),
  1537. &OBSBasic::VCamConfigButtonClicked);
  1538. vcamButton->insert(2);
  1539. }
  1540. void OBSBasic::ResetOutputs()
  1541. {
  1542. ProfileScope("OBSBasic::ResetOutputs");
  1543. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  1544. bool advOut = astrcmpi(mode, "Advanced") == 0;
  1545. if (!outputHandler || !outputHandler->Active()) {
  1546. outputHandler.reset();
  1547. outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
  1548. : CreateSimpleOutputHandler(this));
  1549. delete replayBufferButton;
  1550. if (outputHandler->replayBuffer) {
  1551. replayBufferButton = new ControlsSplitButton(
  1552. QTStr("Basic.Main.StartReplayBuffer"),
  1553. "replayBufferButton",
  1554. &OBSBasic::ReplayBufferClicked);
  1555. replayBufferButton->insert(2);
  1556. }
  1557. if (sysTrayReplayBuffer)
  1558. sysTrayReplayBuffer->setEnabled(
  1559. !!outputHandler->replayBuffer);
  1560. } else {
  1561. outputHandler->Update();
  1562. }
  1563. }
  1564. #define STARTUP_SEPARATOR \
  1565. "==== Startup complete ==============================================="
  1566. #define SHUTDOWN_SEPARATOR \
  1567. "==== Shutting down =================================================="
  1568. #define UNSUPPORTED_ERROR \
  1569. "Failed to initialize video:\n\nRequired graphics API functionality " \
  1570. "not found. Your GPU may not be supported."
  1571. #define UNKNOWN_ERROR \
  1572. "Failed to initialize video. Your GPU may not be supported, " \
  1573. "or your graphics drivers may need to be updated."
  1574. void OBSBasic::OBSInit()
  1575. {
  1576. ProfileScope("OBSBasic::OBSInit");
  1577. const char *sceneCollection = config_get_string(
  1578. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  1579. char savePath[1024];
  1580. char fileName[1024];
  1581. int ret;
  1582. if (!sceneCollection)
  1583. throw "Failed to get scene collection name";
  1584. ret = snprintf(fileName, sizeof(fileName),
  1585. "obs-studio/basic/scenes/%s.json", sceneCollection);
  1586. if (ret <= 0)
  1587. throw "Failed to create scene collection file name";
  1588. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  1589. if (ret <= 0)
  1590. throw "Failed to get scene collection json file path";
  1591. if (!InitBasicConfig())
  1592. throw "Failed to load basic.ini";
  1593. if (!ResetAudio())
  1594. throw "Failed to initialize audio";
  1595. ret = ResetVideo();
  1596. switch (ret) {
  1597. case OBS_VIDEO_MODULE_NOT_FOUND:
  1598. throw "Failed to initialize video: Graphics module not found";
  1599. case OBS_VIDEO_NOT_SUPPORTED:
  1600. throw UNSUPPORTED_ERROR;
  1601. case OBS_VIDEO_INVALID_PARAM:
  1602. throw "Failed to initialize video: Invalid parameters";
  1603. default:
  1604. if (ret != OBS_VIDEO_SUCCESS)
  1605. throw UNKNOWN_ERROR;
  1606. }
  1607. /* load audio monitoring */
  1608. if (obs_audio_monitoring_available()) {
  1609. const char *device_name = config_get_string(
  1610. basicConfig, "Audio", "MonitoringDeviceName");
  1611. const char *device_id = config_get_string(basicConfig, "Audio",
  1612. "MonitoringDeviceId");
  1613. obs_set_audio_monitoring_device(device_name, device_id);
  1614. blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
  1615. device_name, device_id);
  1616. }
  1617. InitOBSCallbacks();
  1618. InitHotkeys();
  1619. /* hack to prevent elgato from loading its own QtNetwork that it tries
  1620. * to ship with */
  1621. #if defined(_WIN32) && !defined(_DEBUG)
  1622. LoadLibraryW(L"Qt6Network");
  1623. #endif
  1624. struct obs_module_failure_info mfi;
  1625. /* Safe Mode disables third-party plugins so we don't need to add earch
  1626. * paths outside the OBS bundle/installation. */
  1627. if (safe_mode || disable_3p_plugins) {
  1628. SetSafeModuleNames();
  1629. } else {
  1630. AddExtraModulePaths();
  1631. }
  1632. blog(LOG_INFO, "---------------------------------");
  1633. obs_load_all_modules2(&mfi);
  1634. blog(LOG_INFO, "---------------------------------");
  1635. obs_log_loaded_modules();
  1636. blog(LOG_INFO, "---------------------------------");
  1637. obs_post_load_modules();
  1638. BPtr<char *> failed_modules = mfi.failed_modules;
  1639. #ifdef BROWSER_AVAILABLE
  1640. cef = obs_browser_init_panel();
  1641. cef_js_avail = cef && obs_browser_qcef_version() >= 3;
  1642. #endif
  1643. OBSDataAutoRelease obsData = obs_get_private_data();
  1644. vcamEnabled = obs_data_get_bool(obsData, "vcamEnabled");
  1645. if (vcamEnabled) {
  1646. AddVCamButton();
  1647. }
  1648. InitBasicConfigDefaults2();
  1649. CheckForSimpleModeX264Fallback();
  1650. blog(LOG_INFO, STARTUP_SEPARATOR);
  1651. if (!InitService())
  1652. throw "Failed to initialize service";
  1653. ResetOutputs();
  1654. CreateHotkeys();
  1655. InitPrimitives();
  1656. sceneDuplicationMode = config_get_bool(
  1657. App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
  1658. swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1659. "SwapScenesMode");
  1660. editPropertiesMode = config_get_bool(
  1661. App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
  1662. if (!opt_studio_mode) {
  1663. SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
  1664. "BasicWindow",
  1665. "PreviewProgramMode"));
  1666. } else {
  1667. SetPreviewProgramMode(true);
  1668. opt_studio_mode = false;
  1669. }
  1670. #define SET_VISIBILITY(name, control) \
  1671. do { \
  1672. if (config_has_user_value(App()->GlobalConfig(), \
  1673. "BasicWindow", name)) { \
  1674. bool visible = config_get_bool(App()->GlobalConfig(), \
  1675. "BasicWindow", name); \
  1676. ui->control->setChecked(visible); \
  1677. } \
  1678. } while (false)
  1679. SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
  1680. SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
  1681. #undef SET_VISIBILITY
  1682. bool sourceIconsVisible = config_get_bool(
  1683. GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
  1684. ui->toggleSourceIcons->setChecked(sourceIconsVisible);
  1685. bool contextVisible = config_get_bool(
  1686. App()->GlobalConfig(), "BasicWindow", "ShowContextToolbars");
  1687. ui->toggleContextBar->setChecked(contextVisible);
  1688. ui->contextContainer->setVisible(contextVisible);
  1689. if (contextVisible)
  1690. UpdateContextBar(true);
  1691. UpdateEditMenu();
  1692. {
  1693. ProfileScope("OBSBasic::Load");
  1694. disableSaving--;
  1695. Load(savePath);
  1696. disableSaving++;
  1697. }
  1698. loaded = true;
  1699. previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1700. "PreviewEnabled");
  1701. if (!previewEnabled && !IsPreviewProgramMode())
  1702. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1703. Qt::QueuedConnection,
  1704. Q_ARG(bool, previewEnabled));
  1705. else if (!previewEnabled && IsPreviewProgramMode())
  1706. QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
  1707. Qt::QueuedConnection,
  1708. Q_ARG(bool, true));
  1709. RefreshSceneCollections();
  1710. RefreshProfiles();
  1711. disableSaving--;
  1712. auto addDisplay = [this](OBSQTDisplay *window) {
  1713. obs_display_add_draw_callback(window->GetDisplay(),
  1714. OBSBasic::RenderMain, this);
  1715. struct obs_video_info ovi;
  1716. if (obs_get_video_info(&ovi))
  1717. ResizePreview(ovi.base_width, ovi.base_height);
  1718. };
  1719. connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);
  1720. /* Show the main window, unless the tray icon isn't available
  1721. * or neither the setting nor flag for starting minimized is set. */
  1722. bool sysTrayEnabled = config_get_bool(App()->GlobalConfig(),
  1723. "BasicWindow", "SysTrayEnabled");
  1724. bool sysTrayWhenStarted = config_get_bool(
  1725. App()->GlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  1726. bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() &&
  1727. sysTrayEnabled &&
  1728. (opt_minimize_tray || sysTrayWhenStarted);
  1729. #ifdef _WIN32
  1730. SetWin32DropStyle(this);
  1731. if (!hideWindowOnStart)
  1732. show();
  1733. #endif
  1734. bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1735. "AlwaysOnTop");
  1736. #ifdef ENABLE_WAYLAND
  1737. bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND;
  1738. #else
  1739. bool isWayland = false;
  1740. #endif
  1741. if (!isWayland && (alwaysOnTop || opt_always_on_top)) {
  1742. SetAlwaysOnTop(this, true);
  1743. ui->actionAlwaysOnTop->setChecked(true);
  1744. } else if (isWayland) {
  1745. if (opt_always_on_top)
  1746. blog(LOG_INFO,
  1747. "Always On Top not available on Wayland, ignoring.");
  1748. ui->actionAlwaysOnTop->setEnabled(false);
  1749. ui->actionAlwaysOnTop->setVisible(false);
  1750. }
  1751. #ifndef _WIN32
  1752. if (!hideWindowOnStart)
  1753. show();
  1754. #endif
  1755. /* setup stats dock */
  1756. OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
  1757. statsDock->setWidget(statsDlg);
  1758. /* ----------------------------- */
  1759. /* add custom browser docks */
  1760. #if defined(BROWSER_AVAILABLE) && defined(YOUTUBE_ENABLED)
  1761. YouTubeAppDock::CleanupYouTubeUrls();
  1762. #endif
  1763. #ifdef BROWSER_AVAILABLE
  1764. if (cef) {
  1765. QAction *action = new QAction(QTStr("Basic.MainMenu.Docks."
  1766. "CustomBrowserDocks"),
  1767. this);
  1768. ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(),
  1769. action);
  1770. connect(action, &QAction::triggered, this,
  1771. &OBSBasic::ManageExtraBrowserDocks);
  1772. ui->menuDocks->insertSeparator(
  1773. ui->scenesDock->toggleViewAction());
  1774. LoadExtraBrowserDocks();
  1775. }
  1776. #endif
  1777. const char *dockStateStr = config_get_string(
  1778. App()->GlobalConfig(), "BasicWindow", "DockState");
  1779. if (!dockStateStr) {
  1780. on_resetDocks_triggered(true);
  1781. } else {
  1782. QByteArray dockState =
  1783. QByteArray::fromBase64(QByteArray(dockStateStr));
  1784. if (!restoreState(dockState))
  1785. on_resetDocks_triggered(true);
  1786. }
  1787. bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
  1788. "Pre23Defaults");
  1789. if (pre23Defaults) {
  1790. bool resetDockLock23 = config_get_bool(
  1791. App()->GlobalConfig(), "General", "ResetDockLock23");
  1792. if (!resetDockLock23) {
  1793. config_set_bool(App()->GlobalConfig(), "General",
  1794. "ResetDockLock23", true);
  1795. config_remove_value(App()->GlobalConfig(),
  1796. "BasicWindow", "DocksLocked");
  1797. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1798. }
  1799. }
  1800. bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1801. "DocksLocked");
  1802. on_lockDocks_toggled(docksLocked);
  1803. ui->lockDocks->blockSignals(true);
  1804. ui->lockDocks->setChecked(docksLocked);
  1805. ui->lockDocks->blockSignals(false);
  1806. bool sideDocks = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1807. "SideDocks");
  1808. on_sideDocks_toggled(sideDocks);
  1809. ui->sideDocks->blockSignals(true);
  1810. ui->sideDocks->setChecked(sideDocks);
  1811. ui->sideDocks->blockSignals(false);
  1812. SystemTray(true);
  1813. TaskbarOverlayInit();
  1814. #ifdef __APPLE__
  1815. disableColorSpaceConversion(this);
  1816. #endif
  1817. bool has_last_version = config_has_user_value(App()->GlobalConfig(),
  1818. "General", "LastVersion");
  1819. bool first_run =
  1820. config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
  1821. if (!first_run) {
  1822. config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
  1823. true);
  1824. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1825. }
  1826. if (!first_run && !has_last_version && !Active())
  1827. QMetaObject::invokeMethod(this, "on_autoConfigure_triggered",
  1828. Qt::QueuedConnection);
  1829. #if (defined(_WIN32) || defined(__APPLE__)) && \
  1830. (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0)
  1831. /* Automatically set branch to "beta" the first time a pre-release build is run. */
  1832. if (!config_get_bool(App()->GlobalConfig(), "General",
  1833. "AutoBetaOptIn")) {
  1834. config_set_string(App()->GlobalConfig(), "General",
  1835. "UpdateBranch", "beta");
  1836. config_set_bool(App()->GlobalConfig(), "General",
  1837. "AutoBetaOptIn", true);
  1838. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  1839. }
  1840. #endif
  1841. TimedCheckForUpdates();
  1842. ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
  1843. "VerticalVolControl"));
  1844. if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
  1845. on_stats_triggered();
  1846. OBSBasicStats::InitializeValues();
  1847. /* ----------------------- */
  1848. /* Add multiview menu */
  1849. ui->viewMenu->addSeparator();
  1850. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  1851. &OBSBasic::OpenMultiviewProjector);
  1852. connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
  1853. &OBSBasic::UpdateMultiviewProjectorMenu);
  1854. ui->sources->UpdateIcons();
  1855. #if !defined(_WIN32)
  1856. delete ui->actionShowCrashLogs;
  1857. delete ui->actionUploadLastCrashLog;
  1858. delete ui->menuCrashLogs;
  1859. delete ui->actionRepair;
  1860. ui->actionShowCrashLogs = nullptr;
  1861. ui->actionUploadLastCrashLog = nullptr;
  1862. ui->menuCrashLogs = nullptr;
  1863. ui->actionRepair = nullptr;
  1864. #if !defined(__APPLE__)
  1865. delete ui->actionCheckForUpdates;
  1866. ui->actionCheckForUpdates = nullptr;
  1867. #endif
  1868. #endif
  1869. #ifdef __APPLE__
  1870. /* Remove OBS' Fullscreen Interface menu in favor of the one macOS adds by default */
  1871. delete ui->actionFullscreenInterface;
  1872. ui->actionFullscreenInterface = nullptr;
  1873. #else
  1874. /* Don't show menu to raise macOS-only permissions dialog */
  1875. delete ui->actionShowMacPermissions;
  1876. ui->actionShowMacPermissions = nullptr;
  1877. #endif
  1878. #if defined(_WIN32) || defined(__APPLE__)
  1879. if (App()->IsUpdaterDisabled()) {
  1880. ui->actionCheckForUpdates->setEnabled(false);
  1881. #if defined(_WIN32)
  1882. ui->actionRepair->setEnabled(false);
  1883. #endif
  1884. }
  1885. #endif
  1886. #ifndef WHATSNEW_ENABLED
  1887. delete ui->actionShowWhatsNew;
  1888. ui->actionShowWhatsNew = nullptr;
  1889. #endif
  1890. if (safe_mode) {
  1891. ui->actionRestartSafe->setText(
  1892. QTStr("Basic.MainMenu.Help.RestartNormal"));
  1893. }
  1894. UpdatePreviewProgramIndicators();
  1895. OnFirstLoad();
  1896. #ifdef YOUTUBE_ENABLED
  1897. /* setup YouTube app dock */
  1898. if (YouTubeAppDock::IsYTServiceSelected())
  1899. youtubeAppDock = new YouTubeAppDock();
  1900. #endif
  1901. if (!hideWindowOnStart)
  1902. activateWindow();
  1903. /* ------------------------------------------- */
  1904. /* display warning message for failed modules */
  1905. if (mfi.count) {
  1906. QString failed_plugins;
  1907. char **plugin = mfi.failed_modules;
  1908. while (*plugin) {
  1909. failed_plugins += *plugin;
  1910. failed_plugins += "\n";
  1911. plugin++;
  1912. }
  1913. QString failed_msg =
  1914. QTStr("PluginsFailedToLoad.Text").arg(failed_plugins);
  1915. OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"),
  1916. failed_msg);
  1917. }
  1918. }
  1919. void OBSBasic::OnFirstLoad()
  1920. {
  1921. if (api)
  1922. api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
  1923. #ifdef WHATSNEW_ENABLED
  1924. /* Attempt to load init screen if available */
  1925. if (cef) {
  1926. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  1927. connect(wnit, &WhatsNewInfoThread::Result, this,
  1928. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  1929. introCheckThread.reset(wnit);
  1930. introCheckThread->start();
  1931. }
  1932. #endif
  1933. Auth::Load();
  1934. bool showLogViewerOnStartup = config_get_bool(
  1935. App()->GlobalConfig(), "LogViewer", "ShowLogStartup");
  1936. if (showLogViewerOnStartup)
  1937. on_actionViewCurrentLog_triggered();
  1938. }
  1939. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1940. #define CUR_VER \
  1941. ((uint64_t)OBS_RELEASE_CANDIDATE_VER << 16ULL | OBS_RELEASE_CANDIDATE)
  1942. #define LAST_INFO_VERSION_STRING "InfoLastRCVersion"
  1943. #elif OBS_BETA > 0
  1944. #define CUR_VER ((uint64_t)OBS_BETA_VER << 16ULL | OBS_BETA)
  1945. #define LAST_INFO_VERSION_STRING "InfoLastBetaVersion"
  1946. #else
  1947. #define CUR_VER ((uint64_t)LIBOBS_API_VER << 16ULL)
  1948. #define LAST_INFO_VERSION_STRING "InfoLastVersion"
  1949. #endif
  1950. /* shows a "what's new" page on startup of new versions using CEF */
  1951. void OBSBasic::ReceivedIntroJson(const QString &text)
  1952. {
  1953. #ifdef WHATSNEW_ENABLED
  1954. if (closing)
  1955. return;
  1956. WhatsNewList items;
  1957. try {
  1958. nlohmann::json json = nlohmann::json::parse(text.toStdString());
  1959. items = json.get<WhatsNewList>();
  1960. } catch (nlohmann::json::exception &e) {
  1961. blog(LOG_WARNING, "Parsing whatsnew data failed: %s", e.what());
  1962. return;
  1963. }
  1964. std::string info_url;
  1965. int info_increment = -1;
  1966. /* check to see if there's an info page for this version */
  1967. for (const WhatsNewItem &item : items) {
  1968. if (item.os) {
  1969. WhatsNewPlatforms platforms = *item.os;
  1970. #ifdef _WIN32
  1971. if (!platforms.windows)
  1972. continue;
  1973. #elif defined(__APPLE__)
  1974. if (!platforms.macos)
  1975. continue;
  1976. #else
  1977. if (!platforms.linux)
  1978. continue;
  1979. #endif
  1980. }
  1981. int major = 0;
  1982. int minor = 0;
  1983. sscanf(item.version.c_str(), "%d.%d", &major, &minor);
  1984. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  1985. if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
  1986. minor == OBS_RELEASE_CANDIDATE_MINOR &&
  1987. item.RC == OBS_RELEASE_CANDIDATE) {
  1988. #elif OBS_BETA > 0
  1989. if (major == OBS_BETA_MAJOR && minor == OBS_BETA_MINOR &&
  1990. item.Beta == OBS_BETA) {
  1991. #else
  1992. if (major == LIBOBS_API_MAJOR_VER &&
  1993. minor == LIBOBS_API_MINOR_VER && item.RC == 0 &&
  1994. item.Beta == 0) {
  1995. #endif
  1996. info_url = item.url;
  1997. info_increment = item.increment;
  1998. }
  1999. }
  2000. /* this version was not found, or no info for this version */
  2001. if (info_increment == -1) {
  2002. return;
  2003. }
  2004. uint64_t lastVersion = config_get_uint(App()->GlobalConfig(), "General",
  2005. LAST_INFO_VERSION_STRING);
  2006. int current_version_increment = -1;
  2007. if ((lastVersion & ~0xFFFF0000ULL) < (CUR_VER & ~0xFFFF0000ULL)) {
  2008. config_set_int(App()->GlobalConfig(), "General",
  2009. "InfoIncrement", -1);
  2010. config_set_uint(App()->GlobalConfig(), "General",
  2011. LAST_INFO_VERSION_STRING, CUR_VER);
  2012. } else {
  2013. current_version_increment = config_get_int(
  2014. App()->GlobalConfig(), "General", "InfoIncrement");
  2015. }
  2016. if (info_increment <= current_version_increment) {
  2017. return;
  2018. }
  2019. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
  2020. info_increment);
  2021. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2022. cef->init_browser();
  2023. WhatsNewBrowserInitThread *wnbit =
  2024. new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
  2025. connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
  2026. &OBSBasic::ShowWhatsNew, Qt::QueuedConnection);
  2027. whatsNewInitThread.reset(wnbit);
  2028. whatsNewInitThread->start();
  2029. #else
  2030. UNUSED_PARAMETER(text);
  2031. #endif
  2032. }
  2033. #undef CUR_VER
  2034. #undef LAST_INFO_VERSION_STRING
  2035. void OBSBasic::ShowWhatsNew(const QString &url)
  2036. {
  2037. #ifdef BROWSER_AVAILABLE
  2038. if (closing)
  2039. return;
  2040. std::string info_url = QT_TO_UTF8(url);
  2041. QDialog *dlg = new QDialog(this);
  2042. dlg->setAttribute(Qt::WA_DeleteOnClose, true);
  2043. dlg->setWindowTitle("What's New");
  2044. dlg->resize(700, 600);
  2045. Qt::WindowFlags flags = dlg->windowFlags();
  2046. Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  2047. dlg->setWindowFlags(flags & (~helpFlag));
  2048. QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
  2049. if (!cefWidget) {
  2050. return;
  2051. }
  2052. connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
  2053. SLOT(setWindowTitle(const QString &)));
  2054. QPushButton *close = new QPushButton(QTStr("Close"));
  2055. connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
  2056. QHBoxLayout *bottomLayout = new QHBoxLayout();
  2057. bottomLayout->addStretch();
  2058. bottomLayout->addWidget(close);
  2059. bottomLayout->addStretch();
  2060. QVBoxLayout *topLayout = new QVBoxLayout(dlg);
  2061. topLayout->addWidget(cefWidget);
  2062. topLayout->addLayout(bottomLayout);
  2063. dlg->show();
  2064. #else
  2065. UNUSED_PARAMETER(url);
  2066. #endif
  2067. }
  2068. void OBSBasic::UpdateMultiviewProjectorMenu()
  2069. {
  2070. ui->multiviewProjectorMenu->clear();
  2071. AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this,
  2072. &OBSBasic::OpenMultiviewProjector);
  2073. }
  2074. void OBSBasic::InitHotkeys()
  2075. {
  2076. ProfileScope("OBSBasic::InitHotkeys");
  2077. struct obs_hotkeys_translations t = {};
  2078. t.insert = Str("Hotkeys.Insert");
  2079. t.del = Str("Hotkeys.Delete");
  2080. t.home = Str("Hotkeys.Home");
  2081. t.end = Str("Hotkeys.End");
  2082. t.page_up = Str("Hotkeys.PageUp");
  2083. t.page_down = Str("Hotkeys.PageDown");
  2084. t.num_lock = Str("Hotkeys.NumLock");
  2085. t.scroll_lock = Str("Hotkeys.ScrollLock");
  2086. t.caps_lock = Str("Hotkeys.CapsLock");
  2087. t.backspace = Str("Hotkeys.Backspace");
  2088. t.tab = Str("Hotkeys.Tab");
  2089. t.print = Str("Hotkeys.Print");
  2090. t.pause = Str("Hotkeys.Pause");
  2091. t.left = Str("Hotkeys.Left");
  2092. t.right = Str("Hotkeys.Right");
  2093. t.up = Str("Hotkeys.Up");
  2094. t.down = Str("Hotkeys.Down");
  2095. #ifdef _WIN32
  2096. t.meta = Str("Hotkeys.Windows");
  2097. #else
  2098. t.meta = Str("Hotkeys.Super");
  2099. #endif
  2100. t.menu = Str("Hotkeys.Menu");
  2101. t.space = Str("Hotkeys.Space");
  2102. t.numpad_num = Str("Hotkeys.NumpadNum");
  2103. t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
  2104. t.numpad_divide = Str("Hotkeys.NumpadDivide");
  2105. t.numpad_plus = Str("Hotkeys.NumpadAdd");
  2106. t.numpad_minus = Str("Hotkeys.NumpadSubtract");
  2107. t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
  2108. t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
  2109. t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
  2110. t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
  2111. t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
  2112. t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
  2113. t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
  2114. t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
  2115. t.mouse_num = Str("Hotkeys.MouseButton");
  2116. t.escape = Str("Hotkeys.Escape");
  2117. obs_hotkeys_set_translations(&t);
  2118. obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
  2119. Str("Push-to-mute"),
  2120. Str("Push-to-talk"));
  2121. obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
  2122. Str("SceneItemHide"));
  2123. obs_hotkey_enable_callback_rerouting(true);
  2124. obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
  2125. }
  2126. void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
  2127. {
  2128. obs_hotkey_trigger_routed_callback(id, pressed);
  2129. }
  2130. void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
  2131. {
  2132. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2133. QMetaObject::invokeMethod(&basic, "ProcessHotkey",
  2134. Q_ARG(obs_hotkey_id, id),
  2135. Q_ARG(bool, pressed));
  2136. }
  2137. void OBSBasic::CreateHotkeys()
  2138. {
  2139. ProfileScope("OBSBasic::CreateHotkeys");
  2140. auto LoadHotkeyData = [&](const char *name) -> OBSData {
  2141. const char *info =
  2142. config_get_string(basicConfig, "Hotkeys", name);
  2143. if (!info)
  2144. return {};
  2145. OBSDataAutoRelease data = obs_data_create_from_json(info);
  2146. if (!data)
  2147. return {};
  2148. return data.Get();
  2149. };
  2150. auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
  2151. OBSDataArrayAutoRelease array =
  2152. obs_data_get_array(LoadHotkeyData(name), "bindings");
  2153. obs_hotkey_load(id, array);
  2154. };
  2155. auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
  2156. const char *name1,
  2157. const char *oldName = NULL) {
  2158. if (oldName) {
  2159. const auto info = config_get_string(basicConfig,
  2160. "Hotkeys", oldName);
  2161. if (info) {
  2162. config_set_string(basicConfig, "Hotkeys", name0,
  2163. info);
  2164. config_set_string(basicConfig, "Hotkeys", name1,
  2165. info);
  2166. config_remove_value(basicConfig, "Hotkeys",
  2167. oldName);
  2168. config_save(basicConfig);
  2169. }
  2170. }
  2171. OBSDataArrayAutoRelease array0 =
  2172. obs_data_get_array(LoadHotkeyData(name0), "bindings");
  2173. OBSDataArrayAutoRelease array1 =
  2174. obs_data_get_array(LoadHotkeyData(name1), "bindings");
  2175. obs_hotkey_pair_load(id, array0, array1);
  2176. };
  2177. #define MAKE_CALLBACK(pred, method, log_action) \
  2178. [](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
  2179. OBSBasic &basic = *static_cast<OBSBasic *>(data); \
  2180. if ((pred) && pressed) { \
  2181. blog(LOG_INFO, log_action " due to hotkey"); \
  2182. method(); \
  2183. return true; \
  2184. } \
  2185. return false; \
  2186. }
  2187. streamingHotkeys = obs_hotkey_pair_register_frontend(
  2188. "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
  2189. "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
  2190. MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
  2191. basic.ui->streamButton->isEnabled(),
  2192. basic.StartStreaming, "Starting stream"),
  2193. MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
  2194. basic.ui->streamButton->isEnabled(),
  2195. basic.StopStreaming, "Stopping stream"),
  2196. this, this);
  2197. LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
  2198. "OBSBasic.StopStreaming");
  2199. auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2200. OBSBasic &basic = *static_cast<OBSBasic *>(data);
  2201. if (basic.outputHandler->StreamingActive() && pressed) {
  2202. basic.ForceStopStreaming();
  2203. }
  2204. };
  2205. forceStreamingStopHotkey = obs_hotkey_register_frontend(
  2206. "OBSBasic.ForceStopStreaming",
  2207. Str("Basic.Main.ForceStopStreaming"), cb, this);
  2208. LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
  2209. recordingHotkeys = obs_hotkey_pair_register_frontend(
  2210. "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
  2211. "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
  2212. MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
  2213. !basic.ui->recordButton->isChecked(),
  2214. basic.StartRecording, "Starting recording"),
  2215. MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
  2216. basic.ui->recordButton->isChecked(),
  2217. basic.StopRecording, "Stopping recording"),
  2218. this, this);
  2219. LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
  2220. "OBSBasic.StopRecording");
  2221. pauseHotkeys = obs_hotkey_pair_register_frontend(
  2222. "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
  2223. "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
  2224. MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
  2225. basic.PauseRecording, "Pausing recording"),
  2226. MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
  2227. basic.UnpauseRecording, "Unpausing recording"),
  2228. this, this);
  2229. LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
  2230. "OBSBasic.UnpauseRecording");
  2231. splitFileHotkey = obs_hotkey_register_frontend(
  2232. "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"),
  2233. [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2234. if (pressed)
  2235. obs_frontend_recording_split_file();
  2236. },
  2237. this);
  2238. LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile");
  2239. replayBufHotkeys = obs_hotkey_pair_register_frontend(
  2240. "OBSBasic.StartReplayBuffer",
  2241. Str("Basic.Main.StartReplayBuffer"),
  2242. "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
  2243. MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
  2244. basic.StartReplayBuffer,
  2245. "Starting replay buffer"),
  2246. MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
  2247. basic.StopReplayBuffer, "Stopping replay buffer"),
  2248. this, this);
  2249. LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
  2250. "OBSBasic.StopReplayBuffer");
  2251. if (vcamEnabled) {
  2252. vcamHotkeys = obs_hotkey_pair_register_frontend(
  2253. "OBSBasic.StartVirtualCam",
  2254. Str("Basic.Main.StartVirtualCam"),
  2255. "OBSBasic.StopVirtualCam",
  2256. Str("Basic.Main.StopVirtualCam"),
  2257. MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(),
  2258. basic.StartVirtualCam,
  2259. "Starting virtual camera"),
  2260. MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(),
  2261. basic.StopVirtualCam,
  2262. "Stopping virtual camera"),
  2263. this, this);
  2264. LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam",
  2265. "OBSBasic.StopVirtualCam");
  2266. }
  2267. togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
  2268. "OBSBasic.EnablePreview",
  2269. Str("Basic.Main.PreviewConextMenu.Enable"),
  2270. "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
  2271. MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
  2272. "Enabling preview"),
  2273. MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
  2274. "Disabling preview"),
  2275. this, this);
  2276. LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
  2277. "OBSBasic.DisablePreview");
  2278. togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend(
  2279. "OBSBasic.EnablePreviewProgram",
  2280. Str("Basic.EnablePreviewProgramMode"),
  2281. "OBSBasic.DisablePreviewProgram",
  2282. Str("Basic.DisablePreviewProgramMode"),
  2283. MAKE_CALLBACK(!basic.IsPreviewProgramMode(),
  2284. basic.EnablePreviewProgram,
  2285. "Enabling preview program"),
  2286. MAKE_CALLBACK(basic.IsPreviewProgramMode(),
  2287. basic.DisablePreviewProgram,
  2288. "Disabling preview program"),
  2289. this, this);
  2290. LoadHotkeyPair(togglePreviewProgramHotkeys,
  2291. "OBSBasic.EnablePreviewProgram",
  2292. "OBSBasic.DisablePreviewProgram",
  2293. "OBSBasic.TogglePreviewProgram");
  2294. contextBarHotkeys = obs_hotkey_pair_register_frontend(
  2295. "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"),
  2296. "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"),
  2297. MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(),
  2298. basic.ShowContextBar, "Showing Context Bar"),
  2299. MAKE_CALLBACK(basic.ui->contextContainer->isVisible(),
  2300. basic.HideContextBar, "Hiding Context Bar"),
  2301. this, this);
  2302. LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar",
  2303. "OBSBasic.HideContextBar");
  2304. #undef MAKE_CALLBACK
  2305. auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2306. bool pressed) {
  2307. if (pressed)
  2308. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2309. "TransitionClicked",
  2310. Qt::QueuedConnection);
  2311. };
  2312. transitionHotkey = obs_hotkey_register_frontend(
  2313. "OBSBasic.Transition", Str("Transition"), transition, this);
  2314. LoadHotkey(transitionHotkey, "OBSBasic.Transition");
  2315. auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2316. bool pressed) {
  2317. if (pressed)
  2318. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2319. "ResetStatsHotkey",
  2320. Qt::QueuedConnection);
  2321. };
  2322. statsHotkey = obs_hotkey_register_frontend(
  2323. "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
  2324. resetStats, this);
  2325. LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
  2326. auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2327. bool pressed) {
  2328. if (pressed)
  2329. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2330. "Screenshot",
  2331. Qt::QueuedConnection);
  2332. };
  2333. screenshotHotkey = obs_hotkey_register_frontend(
  2334. "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this);
  2335. LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot");
  2336. auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *,
  2337. bool pressed) {
  2338. if (pressed)
  2339. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  2340. "ScreenshotSelectedSource",
  2341. Qt::QueuedConnection);
  2342. };
  2343. sourceScreenshotHotkey = obs_hotkey_register_frontend(
  2344. "OBSBasic.SelectedSourceScreenshot",
  2345. Str("Screenshot.SourceHotkey"), screenshotSource, this);
  2346. LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot");
  2347. }
  2348. void OBSBasic::ClearHotkeys()
  2349. {
  2350. obs_hotkey_pair_unregister(streamingHotkeys);
  2351. obs_hotkey_pair_unregister(recordingHotkeys);
  2352. obs_hotkey_pair_unregister(pauseHotkeys);
  2353. obs_hotkey_unregister(splitFileHotkey);
  2354. obs_hotkey_pair_unregister(replayBufHotkeys);
  2355. obs_hotkey_pair_unregister(vcamHotkeys);
  2356. obs_hotkey_pair_unregister(togglePreviewHotkeys);
  2357. obs_hotkey_pair_unregister(contextBarHotkeys);
  2358. obs_hotkey_pair_unregister(togglePreviewProgramHotkeys);
  2359. obs_hotkey_unregister(forceStreamingStopHotkey);
  2360. obs_hotkey_unregister(transitionHotkey);
  2361. obs_hotkey_unregister(statsHotkey);
  2362. obs_hotkey_unregister(screenshotHotkey);
  2363. obs_hotkey_unregister(sourceScreenshotHotkey);
  2364. }
  2365. OBSBasic::~OBSBasic()
  2366. {
  2367. /* clear out UI event queue */
  2368. QApplication::sendPostedEvents(nullptr);
  2369. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  2370. if (updateCheckThread && updateCheckThread->isRunning())
  2371. updateCheckThread->wait();
  2372. if (patronJsonThread && patronJsonThread->isRunning())
  2373. patronJsonThread->wait();
  2374. delete screenshotData;
  2375. delete previewProjector;
  2376. delete studioProgramProjector;
  2377. delete previewProjectorSource;
  2378. delete previewProjectorMain;
  2379. delete sourceProjector;
  2380. delete sceneProjectorMenu;
  2381. delete scaleFilteringMenu;
  2382. delete blendingModeMenu;
  2383. delete colorMenu;
  2384. delete colorWidgetAction;
  2385. delete colorSelect;
  2386. delete deinterlaceMenu;
  2387. delete perSceneTransitionMenu;
  2388. delete shortcutFilter;
  2389. delete trayMenu;
  2390. delete programOptions;
  2391. delete program;
  2392. /* XXX: any obs data must be released before calling obs_shutdown.
  2393. * currently, we can't automate this with C++ RAII because of the
  2394. * delicate nature of obs_shutdown needing to be freed before the UI
  2395. * can be freed, and we have no control over the destruction order of
  2396. * the Qt UI stuff, so we have to manually clear any references to
  2397. * libobs. */
  2398. delete cpuUsageTimer;
  2399. os_cpu_usage_info_destroy(cpuUsageInfo);
  2400. obs_hotkey_set_callback_routing_func(nullptr, nullptr);
  2401. ClearHotkeys();
  2402. service = nullptr;
  2403. outputHandler.reset();
  2404. delete interaction;
  2405. delete properties;
  2406. delete filters;
  2407. delete transformWindow;
  2408. delete advAudioWindow;
  2409. delete about;
  2410. delete remux;
  2411. obs_display_remove_draw_callback(ui->preview->GetDisplay(),
  2412. OBSBasic::RenderMain, this);
  2413. obs_enter_graphics();
  2414. gs_vertexbuffer_destroy(box);
  2415. gs_vertexbuffer_destroy(boxLeft);
  2416. gs_vertexbuffer_destroy(boxTop);
  2417. gs_vertexbuffer_destroy(boxRight);
  2418. gs_vertexbuffer_destroy(boxBottom);
  2419. gs_vertexbuffer_destroy(circle);
  2420. gs_vertexbuffer_destroy(actionSafeMargin);
  2421. gs_vertexbuffer_destroy(graphicsSafeMargin);
  2422. gs_vertexbuffer_destroy(fourByThreeSafeMargin);
  2423. gs_vertexbuffer_destroy(leftLine);
  2424. gs_vertexbuffer_destroy(topLine);
  2425. gs_vertexbuffer_destroy(rightLine);
  2426. obs_leave_graphics();
  2427. /* When shutting down, sometimes source references can get in to the
  2428. * event queue, and if we don't forcibly process those events they
  2429. * won't get processed until after obs_shutdown has been called. I
  2430. * really wish there were a more elegant way to deal with this via C++,
  2431. * but Qt doesn't use C++ in a normal way, so you can't really rely on
  2432. * normal C++ behavior for your data to be freed in the order that you
  2433. * expect or want it to. */
  2434. QApplication::sendPostedEvents(nullptr);
  2435. config_set_int(App()->GlobalConfig(), "General", "LastVersion",
  2436. LIBOBS_API_VER);
  2437. #if defined(OBS_RELEASE_CANDIDATE) && OBS_RELEASE_CANDIDATE > 0
  2438. config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
  2439. OBS_RELEASE_CANDIDATE_VER);
  2440. #elif OBS_BETA > 0
  2441. config_set_int(App()->GlobalConfig(), "General", "LastBetaVersion",
  2442. OBS_BETA_VER);
  2443. #endif
  2444. config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
  2445. previewEnabled);
  2446. config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
  2447. ui->actionAlwaysOnTop->isChecked());
  2448. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2449. "SceneDuplicationMode", sceneDuplicationMode);
  2450. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
  2451. swapScenesMode);
  2452. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2453. "EditPropertiesMode", editPropertiesMode);
  2454. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  2455. "PreviewProgramMode", IsPreviewProgramMode());
  2456. config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
  2457. ui->lockDocks->isChecked());
  2458. config_set_bool(App()->GlobalConfig(), "BasicWindow", "SideDocks",
  2459. ui->sideDocks->isChecked());
  2460. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  2461. #ifdef BROWSER_AVAILABLE
  2462. DestroyPanelCookieManager();
  2463. delete cef;
  2464. cef = nullptr;
  2465. #endif
  2466. }
  2467. void OBSBasic::SaveProjectNow()
  2468. {
  2469. if (disableSaving)
  2470. return;
  2471. projectChanged = true;
  2472. SaveProjectDeferred();
  2473. }
  2474. void OBSBasic::SaveProject()
  2475. {
  2476. if (disableSaving)
  2477. return;
  2478. projectChanged = true;
  2479. QMetaObject::invokeMethod(this, "SaveProjectDeferred",
  2480. Qt::QueuedConnection);
  2481. }
  2482. void OBSBasic::SaveProjectDeferred()
  2483. {
  2484. if (disableSaving)
  2485. return;
  2486. if (!projectChanged)
  2487. return;
  2488. projectChanged = false;
  2489. const char *sceneCollection = config_get_string(
  2490. App()->GlobalConfig(), "Basic", "SceneCollectionFile");
  2491. char savePath[1024];
  2492. char fileName[1024];
  2493. int ret;
  2494. if (!sceneCollection)
  2495. return;
  2496. ret = snprintf(fileName, sizeof(fileName),
  2497. "obs-studio/basic/scenes/%s.json", sceneCollection);
  2498. if (ret <= 0)
  2499. return;
  2500. ret = GetConfigPath(savePath, sizeof(savePath), fileName);
  2501. if (ret <= 0)
  2502. return;
  2503. Save(savePath);
  2504. }
  2505. OBSSource OBSBasic::GetProgramSource()
  2506. {
  2507. return OBSGetStrongRef(programScene);
  2508. }
  2509. OBSScene OBSBasic::GetCurrentScene()
  2510. {
  2511. return currentScene.load();
  2512. }
  2513. OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
  2514. {
  2515. return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
  2516. }
  2517. OBSSceneItem OBSBasic::GetCurrentSceneItem()
  2518. {
  2519. return ui->sources->Get(GetTopSelectedSourceItem());
  2520. }
  2521. void OBSBasic::UpdatePreviewScalingMenu()
  2522. {
  2523. bool fixedScaling = ui->preview->IsFixedScaling();
  2524. float scalingAmount = ui->preview->GetScalingAmount();
  2525. if (!fixedScaling) {
  2526. ui->actionScaleWindow->setChecked(true);
  2527. ui->actionScaleCanvas->setChecked(false);
  2528. ui->actionScaleOutput->setChecked(false);
  2529. return;
  2530. }
  2531. obs_video_info ovi;
  2532. obs_get_video_info(&ovi);
  2533. ui->actionScaleWindow->setChecked(false);
  2534. ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
  2535. ui->actionScaleOutput->setChecked(scalingAmount ==
  2536. float(ovi.output_width) /
  2537. float(ovi.base_width));
  2538. }
  2539. void OBSBasic::CreateInteractionWindow(obs_source_t *source)
  2540. {
  2541. bool closed = true;
  2542. if (interaction)
  2543. closed = interaction->close();
  2544. if (!closed)
  2545. return;
  2546. interaction = new OBSBasicInteraction(this, source);
  2547. interaction->Init();
  2548. interaction->setAttribute(Qt::WA_DeleteOnClose, true);
  2549. }
  2550. void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
  2551. {
  2552. bool closed = true;
  2553. if (properties)
  2554. closed = properties->close();
  2555. if (!closed)
  2556. return;
  2557. properties = new OBSBasicProperties(this, source);
  2558. properties->Init();
  2559. properties->setAttribute(Qt::WA_DeleteOnClose, true);
  2560. }
  2561. void OBSBasic::CreateFiltersWindow(obs_source_t *source)
  2562. {
  2563. bool closed = true;
  2564. if (filters)
  2565. closed = filters->close();
  2566. if (!closed)
  2567. return;
  2568. filters = new OBSBasicFilters(this, source);
  2569. filters->Init();
  2570. filters->setAttribute(Qt::WA_DeleteOnClose, true);
  2571. }
  2572. /* Qt callbacks for invokeMethod */
  2573. void OBSBasic::AddScene(OBSSource source)
  2574. {
  2575. const char *name = obs_source_get_name(source);
  2576. obs_scene_t *scene = obs_scene_from_source(source);
  2577. QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
  2578. SetOBSRef(item, OBSScene(scene));
  2579. ui->scenes->insertItem(ui->scenes->currentRow() + 1, item);
  2580. obs_hotkey_register_source(
  2581. source, "OBSBasic.SelectScene",
  2582. Str("Basic.Hotkeys.SelectScene"),
  2583. [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
  2584. OBSBasic *main = reinterpret_cast<OBSBasic *>(
  2585. App()->GetMainWindow());
  2586. auto potential_source =
  2587. static_cast<obs_source_t *>(data);
  2588. OBSSourceAutoRelease source =
  2589. obs_source_get_ref(potential_source);
  2590. if (source && pressed)
  2591. main->SetCurrentScene(source.Get());
  2592. },
  2593. static_cast<obs_source_t *>(source));
  2594. signal_handler_t *handler = obs_source_get_signal_handler(source);
  2595. SignalContainer<OBSScene> container;
  2596. container.ref = scene;
  2597. container.handlers.assign({
  2598. std::make_shared<OBSSignal>(handler, "item_add",
  2599. OBSBasic::SceneItemAdded, this),
  2600. std::make_shared<OBSSignal>(handler, "reorder",
  2601. OBSBasic::SceneReordered, this),
  2602. std::make_shared<OBSSignal>(handler, "refresh",
  2603. OBSBasic::SceneRefreshed, this),
  2604. });
  2605. item->setData(static_cast<int>(QtDataRole::OBSSignals),
  2606. QVariant::fromValue(container));
  2607. /* if the scene already has items (a duplicated scene) add them */
  2608. auto addSceneItem = [this](obs_sceneitem_t *item) {
  2609. AddSceneItem(item);
  2610. };
  2611. using addSceneItem_t = decltype(addSceneItem);
  2612. obs_scene_enum_items(
  2613. scene,
  2614. [](obs_scene_t *, obs_sceneitem_t *item, void *param) {
  2615. addSceneItem_t *func;
  2616. func = reinterpret_cast<addSceneItem_t *>(param);
  2617. (*func)(item);
  2618. return true;
  2619. },
  2620. &addSceneItem);
  2621. SaveProject();
  2622. if (!disableSaving) {
  2623. obs_source_t *source = obs_scene_get_source(scene);
  2624. blog(LOG_INFO, "User added scene '%s'",
  2625. obs_source_get_name(source));
  2626. OBSProjector::UpdateMultiviewProjectors();
  2627. }
  2628. if (api)
  2629. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2630. }
  2631. void OBSBasic::RemoveScene(OBSSource source)
  2632. {
  2633. obs_scene_t *scene = obs_scene_from_source(source);
  2634. QListWidgetItem *sel = nullptr;
  2635. int count = ui->scenes->count();
  2636. for (int i = 0; i < count; i++) {
  2637. auto item = ui->scenes->item(i);
  2638. auto cur_scene = GetOBSRef<OBSScene>(item);
  2639. if (cur_scene != scene)
  2640. continue;
  2641. sel = item;
  2642. break;
  2643. }
  2644. if (sel != nullptr) {
  2645. if (sel == ui->scenes->currentItem())
  2646. ui->sources->Clear();
  2647. delete sel;
  2648. }
  2649. SaveProject();
  2650. if (!disableSaving) {
  2651. blog(LOG_INFO, "User Removed scene '%s'",
  2652. obs_source_get_name(source));
  2653. OBSProjector::UpdateMultiviewProjectors();
  2654. }
  2655. if (api)
  2656. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  2657. }
  2658. static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item,
  2659. void *param)
  2660. {
  2661. obs_sceneitem_t *selectedItem =
  2662. reinterpret_cast<obs_sceneitem_t *>(param);
  2663. if (obs_sceneitem_is_group(item))
  2664. obs_sceneitem_group_enum_items(item, select_one, param);
  2665. obs_sceneitem_select(item, (selectedItem == item));
  2666. return true;
  2667. }
  2668. void OBSBasic::AddSceneItem(OBSSceneItem item)
  2669. {
  2670. obs_scene_t *scene = obs_sceneitem_get_scene(item);
  2671. if (GetCurrentScene() == scene)
  2672. ui->sources->Add(item);
  2673. SaveProject();
  2674. if (!disableSaving) {
  2675. obs_source_t *sceneSource = obs_scene_get_source(scene);
  2676. obs_source_t *itemSource = obs_sceneitem_get_source(item);
  2677. blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
  2678. obs_source_get_name(itemSource),
  2679. obs_source_get_id(itemSource),
  2680. obs_source_get_name(sceneSource));
  2681. obs_scene_enum_items(scene, select_one,
  2682. (obs_sceneitem_t *)item);
  2683. }
  2684. }
  2685. static void RenameListValues(QListWidget *listWidget, const QString &newName,
  2686. const QString &prevName)
  2687. {
  2688. QList<QListWidgetItem *> items =
  2689. listWidget->findItems(prevName, Qt::MatchExactly);
  2690. for (int i = 0; i < items.count(); i++)
  2691. items[i]->setText(newName);
  2692. }
  2693. void OBSBasic::RenameSources(OBSSource source, QString newName,
  2694. QString prevName)
  2695. {
  2696. RenameListValues(ui->scenes, newName, prevName);
  2697. for (size_t i = 0; i < volumes.size(); i++) {
  2698. if (volumes[i]->GetName().compare(prevName) == 0)
  2699. volumes[i]->SetName(newName);
  2700. }
  2701. for (size_t i = 0; i < projectors.size(); i++) {
  2702. if (projectors[i]->GetSource() == source)
  2703. projectors[i]->RenameProjector(prevName, newName);
  2704. }
  2705. if (vcamConfig.type == VCamOutputType::SourceOutput &&
  2706. prevName == QString::fromStdString(vcamConfig.source))
  2707. vcamConfig.source = newName.toStdString();
  2708. if (vcamConfig.type == VCamOutputType::SceneOutput &&
  2709. prevName == QString::fromStdString(vcamConfig.scene))
  2710. vcamConfig.scene = newName.toStdString();
  2711. SaveProject();
  2712. obs_scene_t *scene = obs_scene_from_source(source);
  2713. if (scene)
  2714. OBSProjector::UpdateMultiviewProjectors();
  2715. UpdateContextBar();
  2716. UpdatePreviewProgramIndicators();
  2717. }
  2718. void OBSBasic::ClearContextBar()
  2719. {
  2720. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2721. if (la) {
  2722. delete la->widget();
  2723. ui->emptySpace->layout()->removeItem(la);
  2724. }
  2725. }
  2726. void OBSBasic::UpdateContextBarVisibility()
  2727. {
  2728. int width = ui->centralwidget->size().width();
  2729. ContextBarSize contextBarSizeNew;
  2730. if (width >= 740) {
  2731. contextBarSizeNew = ContextBarSize_Normal;
  2732. } else if (width >= 600) {
  2733. contextBarSizeNew = ContextBarSize_Reduced;
  2734. } else {
  2735. contextBarSizeNew = ContextBarSize_Minimized;
  2736. }
  2737. if (contextBarSize == contextBarSizeNew)
  2738. return;
  2739. contextBarSize = contextBarSizeNew;
  2740. UpdateContextBarDeferred();
  2741. }
  2742. static bool is_network_media_source(obs_source_t *source, const char *id)
  2743. {
  2744. if (strcmp(id, "ffmpeg_source") != 0)
  2745. return false;
  2746. OBSDataAutoRelease s = obs_source_get_settings(source);
  2747. bool is_local_file = obs_data_get_bool(s, "is_local_file");
  2748. return !is_local_file;
  2749. }
  2750. void OBSBasic::UpdateContextBarDeferred(bool force)
  2751. {
  2752. QMetaObject::invokeMethod(this, "UpdateContextBar",
  2753. Qt::QueuedConnection, Q_ARG(bool, force));
  2754. }
  2755. void OBSBasic::SourceToolBarActionsSetEnabled()
  2756. {
  2757. bool enable = false;
  2758. bool disableProps = false;
  2759. OBSSceneItem item = GetCurrentSceneItem();
  2760. if (item) {
  2761. OBSSource source = obs_sceneitem_get_source(item);
  2762. disableProps = !obs_source_configurable(source);
  2763. enable = true;
  2764. }
  2765. if (disableProps)
  2766. ui->actionSourceProperties->setEnabled(false);
  2767. else
  2768. ui->actionSourceProperties->setEnabled(enable);
  2769. ui->actionRemoveSource->setEnabled(enable);
  2770. ui->actionSourceUp->setEnabled(enable);
  2771. ui->actionSourceDown->setEnabled(enable);
  2772. RefreshToolBarStyling(ui->sourcesToolbar);
  2773. }
  2774. void OBSBasic::UpdateTransformShortcuts()
  2775. {
  2776. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  2777. uint32_t flags = obs_source_get_output_flags(source);
  2778. bool audioOnly = (flags & OBS_SOURCE_VIDEO) == 0;
  2779. ui->actionEditTransform->setEnabled(!audioOnly);
  2780. ui->actionCopyTransform->setEnabled(!audioOnly);
  2781. ui->actionPasteTransform->setEnabled(audioOnly ? false
  2782. : hasCopiedTransform);
  2783. ui->actionResetTransform->setEnabled(!audioOnly);
  2784. }
  2785. void OBSBasic::UpdateContextBar(bool force)
  2786. {
  2787. SourceToolBarActionsSetEnabled();
  2788. UpdateTransformShortcuts();
  2789. if (!ui->contextContainer->isVisible() && !force)
  2790. return;
  2791. OBSSceneItem item = GetCurrentSceneItem();
  2792. if (item) {
  2793. obs_source_t *source = obs_sceneitem_get_source(item);
  2794. bool updateNeeded = true;
  2795. QLayoutItem *la = ui->emptySpace->layout()->itemAt(0);
  2796. if (la) {
  2797. if (SourceToolbar *toolbar =
  2798. dynamic_cast<SourceToolbar *>(
  2799. la->widget())) {
  2800. if (toolbar->GetSource() == source)
  2801. updateNeeded = false;
  2802. } else if (MediaControls *toolbar =
  2803. dynamic_cast<MediaControls *>(
  2804. la->widget())) {
  2805. if (toolbar->GetSource() == source)
  2806. updateNeeded = false;
  2807. }
  2808. }
  2809. const char *id = obs_source_get_unversioned_id(source);
  2810. uint32_t flags = obs_source_get_output_flags(source);
  2811. ui->sourceInteractButton->setVisible(flags &
  2812. OBS_SOURCE_INTERACTION);
  2813. if (contextBarSize >= ContextBarSize_Reduced &&
  2814. (updateNeeded || force)) {
  2815. ClearContextBar();
  2816. if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) {
  2817. if (!is_network_media_source(source, id)) {
  2818. MediaControls *mediaControls =
  2819. new MediaControls(
  2820. ui->emptySpace);
  2821. mediaControls->SetSource(source);
  2822. ui->emptySpace->layout()->addWidget(
  2823. mediaControls);
  2824. }
  2825. } else if (strcmp(id, "browser_source") == 0) {
  2826. BrowserToolbar *c = new BrowserToolbar(
  2827. ui->emptySpace, source);
  2828. ui->emptySpace->layout()->addWidget(c);
  2829. } else if (strcmp(id, "wasapi_input_capture") == 0 ||
  2830. strcmp(id, "wasapi_output_capture") == 0 ||
  2831. strcmp(id, "coreaudio_input_capture") == 0 ||
  2832. strcmp(id, "coreaudio_output_capture") ==
  2833. 0 ||
  2834. strcmp(id, "pulse_input_capture") == 0 ||
  2835. strcmp(id, "pulse_output_capture") == 0 ||
  2836. strcmp(id, "alsa_input_capture") == 0) {
  2837. AudioCaptureToolbar *c =
  2838. new AudioCaptureToolbar(ui->emptySpace,
  2839. source);
  2840. c->Init();
  2841. ui->emptySpace->layout()->addWidget(c);
  2842. } else if (strcmp(id,
  2843. "wasapi_process_output_capture") ==
  2844. 0) {
  2845. ApplicationAudioCaptureToolbar *c =
  2846. new ApplicationAudioCaptureToolbar(
  2847. ui->emptySpace, source);
  2848. c->Init();
  2849. ui->emptySpace->layout()->addWidget(c);
  2850. } else if (strcmp(id, "window_capture") == 0 ||
  2851. strcmp(id, "xcomposite_input") == 0) {
  2852. WindowCaptureToolbar *c =
  2853. new WindowCaptureToolbar(ui->emptySpace,
  2854. source);
  2855. c->Init();
  2856. ui->emptySpace->layout()->addWidget(c);
  2857. } else if (strcmp(id, "monitor_capture") == 0 ||
  2858. strcmp(id, "display_capture") == 0 ||
  2859. strcmp(id, "xshm_input") == 0) {
  2860. DisplayCaptureToolbar *c =
  2861. new DisplayCaptureToolbar(
  2862. ui->emptySpace, source);
  2863. c->Init();
  2864. ui->emptySpace->layout()->addWidget(c);
  2865. } else if (strcmp(id, "dshow_input") == 0) {
  2866. DeviceCaptureToolbar *c =
  2867. new DeviceCaptureToolbar(ui->emptySpace,
  2868. source);
  2869. ui->emptySpace->layout()->addWidget(c);
  2870. } else if (strcmp(id, "game_capture") == 0) {
  2871. GameCaptureToolbar *c = new GameCaptureToolbar(
  2872. ui->emptySpace, source);
  2873. ui->emptySpace->layout()->addWidget(c);
  2874. } else if (strcmp(id, "image_source") == 0) {
  2875. ImageSourceToolbar *c = new ImageSourceToolbar(
  2876. ui->emptySpace, source);
  2877. ui->emptySpace->layout()->addWidget(c);
  2878. } else if (strcmp(id, "color_source") == 0) {
  2879. ColorSourceToolbar *c = new ColorSourceToolbar(
  2880. ui->emptySpace, source);
  2881. ui->emptySpace->layout()->addWidget(c);
  2882. } else if (strcmp(id, "text_ft2_source") == 0 ||
  2883. strcmp(id, "text_gdiplus") == 0) {
  2884. TextSourceToolbar *c = new TextSourceToolbar(
  2885. ui->emptySpace, source);
  2886. ui->emptySpace->layout()->addWidget(c);
  2887. }
  2888. } else if (contextBarSize == ContextBarSize_Minimized) {
  2889. ClearContextBar();
  2890. }
  2891. QIcon icon;
  2892. if (strcmp(id, "scene") == 0)
  2893. icon = GetSceneIcon();
  2894. else if (strcmp(id, "group") == 0)
  2895. icon = GetGroupIcon();
  2896. else
  2897. icon = GetSourceIcon(id);
  2898. QPixmap pixmap = icon.pixmap(QSize(16, 16));
  2899. ui->contextSourceIcon->setPixmap(pixmap);
  2900. ui->contextSourceIconSpacer->hide();
  2901. ui->contextSourceIcon->show();
  2902. const char *name = obs_source_get_name(source);
  2903. ui->contextSourceLabel->setText(name);
  2904. ui->sourceFiltersButton->setEnabled(true);
  2905. ui->sourcePropertiesButton->setEnabled(
  2906. obs_source_configurable(source));
  2907. } else {
  2908. ClearContextBar();
  2909. ui->contextSourceIcon->hide();
  2910. ui->contextSourceIconSpacer->show();
  2911. ui->contextSourceLabel->setText(
  2912. QTStr("ContextBar.NoSelectedSource"));
  2913. ui->sourceFiltersButton->setEnabled(false);
  2914. ui->sourcePropertiesButton->setEnabled(false);
  2915. ui->sourceInteractButton->setVisible(false);
  2916. }
  2917. if (contextBarSize == ContextBarSize_Normal) {
  2918. ui->sourcePropertiesButton->setText(QTStr("Properties"));
  2919. ui->sourceFiltersButton->setText(QTStr("Filters"));
  2920. ui->sourceInteractButton->setText(QTStr("Interact"));
  2921. } else {
  2922. ui->sourcePropertiesButton->setText("");
  2923. ui->sourceFiltersButton->setText("");
  2924. ui->sourceInteractButton->setText("");
  2925. }
  2926. }
  2927. static inline bool SourceMixerHidden(obs_source_t *source)
  2928. {
  2929. OBSDataAutoRelease priv_settings =
  2930. obs_source_get_private_settings(source);
  2931. bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
  2932. return hidden;
  2933. }
  2934. static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
  2935. {
  2936. OBSDataAutoRelease priv_settings =
  2937. obs_source_get_private_settings(source);
  2938. obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
  2939. }
  2940. void OBSBasic::GetAudioSourceFilters()
  2941. {
  2942. QAction *action = reinterpret_cast<QAction *>(sender());
  2943. VolControl *vol = action->property("volControl").value<VolControl *>();
  2944. obs_source_t *source = vol->GetSource();
  2945. CreateFiltersWindow(source);
  2946. }
  2947. void OBSBasic::GetAudioSourceProperties()
  2948. {
  2949. QAction *action = reinterpret_cast<QAction *>(sender());
  2950. VolControl *vol = action->property("volControl").value<VolControl *>();
  2951. obs_source_t *source = vol->GetSource();
  2952. CreatePropertiesWindow(source);
  2953. }
  2954. void OBSBasic::HideAudioControl()
  2955. {
  2956. QAction *action = reinterpret_cast<QAction *>(sender());
  2957. VolControl *vol = action->property("volControl").value<VolControl *>();
  2958. obs_source_t *source = vol->GetSource();
  2959. if (!SourceMixerHidden(source)) {
  2960. SetSourceMixerHidden(source, true);
  2961. /* Due to a bug with QT 6.2.4, the version that's in the Ubuntu
  2962. * 22.04 ppa, hiding the audio mixer causes a crash, so defer to
  2963. * the next event loop to hide it. Doesn't seem to be a problem
  2964. * with newer versions of QT. */
  2965. QMetaObject::invokeMethod(this, "DeactivateAudioSource",
  2966. Qt::QueuedConnection,
  2967. Q_ARG(OBSSource, OBSSource(source)));
  2968. }
  2969. }
  2970. void OBSBasic::UnhideAllAudioControls()
  2971. {
  2972. auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
  2973. {
  2974. if (!obs_source_active(source))
  2975. return true;
  2976. if (!SourceMixerHidden(source))
  2977. return true;
  2978. SetSourceMixerHidden(source, false);
  2979. ActivateAudioSource(source);
  2980. return true;
  2981. };
  2982. using UnhideAudioMixer_t = decltype(UnhideAudioMixer);
  2983. auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
  2984. {
  2985. return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source);
  2986. };
  2987. obs_enum_sources(PreEnum, &UnhideAudioMixer);
  2988. }
  2989. void OBSBasic::ToggleHideMixer()
  2990. {
  2991. OBSSceneItem item = GetCurrentSceneItem();
  2992. OBSSource source = obs_sceneitem_get_source(item);
  2993. if (!SourceMixerHidden(source)) {
  2994. SetSourceMixerHidden(source, true);
  2995. DeactivateAudioSource(source);
  2996. } else {
  2997. SetSourceMixerHidden(source, false);
  2998. ActivateAudioSource(source);
  2999. }
  3000. }
  3001. void OBSBasic::MixerRenameSource()
  3002. {
  3003. QAction *action = reinterpret_cast<QAction *>(sender());
  3004. VolControl *vol = action->property("volControl").value<VolControl *>();
  3005. OBSSource source = vol->GetSource();
  3006. const char *prevName = obs_source_get_name(source);
  3007. for (;;) {
  3008. string name;
  3009. bool accepted = NameDialog::AskForName(
  3010. this, QTStr("Basic.Main.MixerRename.Title"),
  3011. QTStr("Basic.Main.MixerRename.Text"), name,
  3012. QT_UTF8(prevName));
  3013. if (!accepted)
  3014. return;
  3015. if (name.empty()) {
  3016. OBSMessageBox::warning(this,
  3017. QTStr("NoNameEntered.Title"),
  3018. QTStr("NoNameEntered.Text"));
  3019. continue;
  3020. }
  3021. OBSSourceAutoRelease sourceTest =
  3022. obs_get_source_by_name(name.c_str());
  3023. if (sourceTest) {
  3024. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3025. QTStr("NameExists.Text"));
  3026. continue;
  3027. }
  3028. obs_source_set_name(source, name.c_str());
  3029. break;
  3030. }
  3031. }
  3032. static inline bool SourceVolumeLocked(obs_source_t *source)
  3033. {
  3034. OBSDataAutoRelease priv_settings =
  3035. obs_source_get_private_settings(source);
  3036. bool lock = obs_data_get_bool(priv_settings, "volume_locked");
  3037. return lock;
  3038. }
  3039. void OBSBasic::LockVolumeControl(bool lock)
  3040. {
  3041. QAction *action = reinterpret_cast<QAction *>(sender());
  3042. VolControl *vol = action->property("volControl").value<VolControl *>();
  3043. obs_source_t *source = vol->GetSource();
  3044. OBSDataAutoRelease priv_settings =
  3045. obs_source_get_private_settings(source);
  3046. obs_data_set_bool(priv_settings, "volume_locked", lock);
  3047. vol->EnableSlider(!lock);
  3048. }
  3049. void OBSBasic::VolControlContextMenu()
  3050. {
  3051. VolControl *vol = reinterpret_cast<VolControl *>(sender());
  3052. /* ------------------- */
  3053. QAction lockAction(QTStr("LockVolume"), this);
  3054. lockAction.setCheckable(true);
  3055. lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));
  3056. QAction hideAction(QTStr("Hide"), this);
  3057. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3058. QAction mixerRenameAction(QTStr("Rename"), this);
  3059. QAction copyFiltersAction(QTStr("Copy.Filters"), this);
  3060. QAction pasteFiltersAction(QTStr("Paste.Filters"), this);
  3061. QAction filtersAction(QTStr("Filters"), this);
  3062. QAction propertiesAction(QTStr("Properties"), this);
  3063. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3064. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3065. toggleControlLayoutAction.setCheckable(true);
  3066. toggleControlLayoutAction.setChecked(config_get_bool(
  3067. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3068. /* ------------------- */
  3069. connect(&hideAction, &QAction::triggered, this,
  3070. &OBSBasic::HideAudioControl, Qt::DirectConnection);
  3071. connect(&unhideAllAction, &QAction::triggered, this,
  3072. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3073. connect(&lockAction, &QAction::toggled, this,
  3074. &OBSBasic::LockVolumeControl, Qt::DirectConnection);
  3075. connect(&mixerRenameAction, &QAction::triggered, this,
  3076. &OBSBasic::MixerRenameSource, Qt::DirectConnection);
  3077. connect(&copyFiltersAction, &QAction::triggered, this,
  3078. &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
  3079. connect(&pasteFiltersAction, &QAction::triggered, this,
  3080. &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);
  3081. connect(&filtersAction, &QAction::triggered, this,
  3082. &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
  3083. connect(&propertiesAction, &QAction::triggered, this,
  3084. &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
  3085. connect(&advPropAction, &QAction::triggered, this,
  3086. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3087. Qt::DirectConnection);
  3088. /* ------------------- */
  3089. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3090. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3091. /* ------------------- */
  3092. hideAction.setProperty("volControl",
  3093. QVariant::fromValue<VolControl *>(vol));
  3094. lockAction.setProperty("volControl",
  3095. QVariant::fromValue<VolControl *>(vol));
  3096. mixerRenameAction.setProperty("volControl",
  3097. QVariant::fromValue<VolControl *>(vol));
  3098. copyFiltersAction.setProperty("volControl",
  3099. QVariant::fromValue<VolControl *>(vol));
  3100. pasteFiltersAction.setProperty("volControl",
  3101. QVariant::fromValue<VolControl *>(vol));
  3102. filtersAction.setProperty("volControl",
  3103. QVariant::fromValue<VolControl *>(vol));
  3104. propertiesAction.setProperty("volControl",
  3105. QVariant::fromValue<VolControl *>(vol));
  3106. /* ------------------- */
  3107. copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) >
  3108. 0);
  3109. OBSSourceAutoRelease source =
  3110. obs_weak_source_get_source(copyFiltersSource);
  3111. if (source) {
  3112. pasteFiltersAction.setEnabled(true);
  3113. } else {
  3114. pasteFiltersAction.setEnabled(false);
  3115. }
  3116. QMenu popup;
  3117. vol->SetContextMenu(&popup);
  3118. popup.addAction(&lockAction);
  3119. popup.addSeparator();
  3120. popup.addAction(&unhideAllAction);
  3121. popup.addAction(&hideAction);
  3122. popup.addAction(&mixerRenameAction);
  3123. popup.addSeparator();
  3124. popup.addAction(&copyFiltersAction);
  3125. popup.addAction(&pasteFiltersAction);
  3126. popup.addSeparator();
  3127. popup.addAction(&toggleControlLayoutAction);
  3128. popup.addSeparator();
  3129. popup.addAction(&filtersAction);
  3130. popup.addAction(&propertiesAction);
  3131. popup.addAction(&advPropAction);
  3132. // toggleControlLayoutAction deletes and re-creates the volume controls
  3133. // meaning that "vol" would be pointing to freed memory.
  3134. if (popup.exec(QCursor::pos()) != &toggleControlLayoutAction)
  3135. vol->SetContextMenu(nullptr);
  3136. }
  3137. void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
  3138. {
  3139. StackedMixerAreaContextMenuRequested();
  3140. }
  3141. void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
  3142. {
  3143. StackedMixerAreaContextMenuRequested();
  3144. }
  3145. void OBSBasic::StackedMixerAreaContextMenuRequested()
  3146. {
  3147. QAction unhideAllAction(QTStr("UnhideAll"), this);
  3148. QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
  3149. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  3150. toggleControlLayoutAction.setCheckable(true);
  3151. toggleControlLayoutAction.setChecked(config_get_bool(
  3152. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  3153. /* ------------------- */
  3154. connect(&unhideAllAction, &QAction::triggered, this,
  3155. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  3156. connect(&advPropAction, &QAction::triggered, this,
  3157. &OBSBasic::on_actionAdvAudioProperties_triggered,
  3158. Qt::DirectConnection);
  3159. /* ------------------- */
  3160. connect(&toggleControlLayoutAction, &QAction::changed, this,
  3161. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  3162. /* ------------------- */
  3163. QMenu popup;
  3164. popup.addAction(&unhideAllAction);
  3165. popup.addSeparator();
  3166. popup.addAction(&toggleControlLayoutAction);
  3167. popup.addSeparator();
  3168. popup.addAction(&advPropAction);
  3169. popup.exec(QCursor::pos());
  3170. }
  3171. void OBSBasic::ToggleMixerLayout(bool vertical)
  3172. {
  3173. if (vertical) {
  3174. ui->stackedMixerArea->setMinimumSize(180, 220);
  3175. ui->stackedMixerArea->setCurrentIndex(1);
  3176. } else {
  3177. ui->stackedMixerArea->setMinimumSize(220, 0);
  3178. ui->stackedMixerArea->setCurrentIndex(0);
  3179. }
  3180. }
  3181. void OBSBasic::ToggleVolControlLayout()
  3182. {
  3183. bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
  3184. "VerticalVolControl");
  3185. config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
  3186. vertical);
  3187. ToggleMixerLayout(vertical);
  3188. // We need to store it so we can delete current and then add
  3189. // at the right order
  3190. vector<OBSSource> sources;
  3191. for (size_t i = 0; i != volumes.size(); i++)
  3192. sources.emplace_back(volumes[i]->GetSource());
  3193. ClearVolumeControls();
  3194. for (const auto &source : sources)
  3195. ActivateAudioSource(source);
  3196. }
  3197. void OBSBasic::ActivateAudioSource(OBSSource source)
  3198. {
  3199. if (SourceMixerHidden(source))
  3200. return;
  3201. if (!obs_source_active(source))
  3202. return;
  3203. if (!obs_source_audio_active(source))
  3204. return;
  3205. bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
  3206. "VerticalVolControl");
  3207. VolControl *vol = new VolControl(source, true, vertical);
  3208. vol->EnableSlider(!SourceVolumeLocked(source));
  3209. double meterDecayRate =
  3210. config_get_double(basicConfig, "Audio", "MeterDecayRate");
  3211. vol->SetMeterDecayRate(meterDecayRate);
  3212. uint32_t peakMeterTypeIdx =
  3213. config_get_uint(basicConfig, "Audio", "PeakMeterType");
  3214. enum obs_peak_meter_type peakMeterType;
  3215. switch (peakMeterTypeIdx) {
  3216. case 0:
  3217. peakMeterType = SAMPLE_PEAK_METER;
  3218. break;
  3219. case 1:
  3220. peakMeterType = TRUE_PEAK_METER;
  3221. break;
  3222. default:
  3223. peakMeterType = SAMPLE_PEAK_METER;
  3224. break;
  3225. }
  3226. vol->setPeakMeterType(peakMeterType);
  3227. vol->setContextMenuPolicy(Qt::CustomContextMenu);
  3228. connect(vol, &QWidget::customContextMenuRequested, this,
  3229. &OBSBasic::VolControlContextMenu);
  3230. connect(vol, &VolControl::ConfigClicked, this,
  3231. &OBSBasic::VolControlContextMenu);
  3232. InsertQObjectByName(volumes, vol);
  3233. for (auto volume : volumes) {
  3234. if (vertical)
  3235. ui->vVolControlLayout->addWidget(volume);
  3236. else
  3237. ui->hVolControlLayout->addWidget(volume);
  3238. }
  3239. }
  3240. void OBSBasic::DeactivateAudioSource(OBSSource source)
  3241. {
  3242. for (size_t i = 0; i < volumes.size(); i++) {
  3243. if (volumes[i]->GetSource() == source) {
  3244. delete volumes[i];
  3245. volumes.erase(volumes.begin() + i);
  3246. break;
  3247. }
  3248. }
  3249. }
  3250. bool OBSBasic::QueryRemoveSource(obs_source_t *source)
  3251. {
  3252. if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
  3253. !obs_source_is_group(source)) {
  3254. int count = ui->scenes->count();
  3255. if (count == 1) {
  3256. OBSMessageBox::information(this,
  3257. QTStr("FinalScene.Title"),
  3258. QTStr("FinalScene.Text"));
  3259. return false;
  3260. }
  3261. }
  3262. const char *name = obs_source_get_name(source);
  3263. QString text = QTStr("ConfirmRemove.Text").arg(QT_UTF8(name));
  3264. QMessageBox remove_source(this);
  3265. remove_source.setText(text);
  3266. QPushButton *Yes =
  3267. remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
  3268. remove_source.setDefaultButton(Yes);
  3269. remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
  3270. remove_source.setIcon(QMessageBox::Question);
  3271. remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
  3272. remove_source.exec();
  3273. return Yes == remove_source.clickedButton();
  3274. }
  3275. #define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
  3276. void OBSBasic::TimedCheckForUpdates()
  3277. {
  3278. if (App()->IsUpdaterDisabled())
  3279. return;
  3280. if (!config_get_bool(App()->GlobalConfig(), "General",
  3281. "EnableAutoUpdates"))
  3282. return;
  3283. #if defined(ENABLE_SPARKLE_UPDATER)
  3284. CheckForUpdates(false);
  3285. #elif _WIN32
  3286. long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
  3287. "LastUpdateCheck");
  3288. uint32_t lastVersion =
  3289. config_get_int(App()->GlobalConfig(), "General", "LastVersion");
  3290. if (lastVersion < LIBOBS_API_VER) {
  3291. lastUpdate = 0;
  3292. config_set_int(App()->GlobalConfig(), "General",
  3293. "LastUpdateCheck", 0);
  3294. }
  3295. long long t = (long long)time(nullptr);
  3296. long long secs = t - lastUpdate;
  3297. if (secs > UPDATE_CHECK_INTERVAL)
  3298. CheckForUpdates(false);
  3299. #endif
  3300. }
  3301. void OBSBasic::CheckForUpdates(bool manualUpdate)
  3302. {
  3303. #if _WIN32
  3304. ui->actionCheckForUpdates->setEnabled(false);
  3305. ui->actionRepair->setEnabled(false);
  3306. if (updateCheckThread && updateCheckThread->isRunning())
  3307. return;
  3308. updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
  3309. updateCheckThread->start();
  3310. #elif defined(ENABLE_SPARKLE_UPDATER)
  3311. ui->actionCheckForUpdates->setEnabled(false);
  3312. if (updateCheckThread && updateCheckThread->isRunning())
  3313. return;
  3314. MacUpdateThread *mut = new MacUpdateThread(manualUpdate);
  3315. connect(mut, &MacUpdateThread::Result, this,
  3316. &OBSBasic::MacBranchesFetched, Qt::QueuedConnection);
  3317. updateCheckThread.reset(mut);
  3318. updateCheckThread->start();
  3319. #else
  3320. UNUSED_PARAMETER(manualUpdate);
  3321. #endif
  3322. }
  3323. void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate)
  3324. {
  3325. #ifdef ENABLE_SPARKLE_UPDATER
  3326. static OBSSparkle *updater;
  3327. if (!updater) {
  3328. updater = new OBSSparkle(QT_TO_UTF8(branch),
  3329. ui->actionCheckForUpdates);
  3330. return;
  3331. }
  3332. updater->setBranch(QT_TO_UTF8(branch));
  3333. updater->checkForUpdates(manualUpdate);
  3334. #else
  3335. UNUSED_PARAMETER(branch);
  3336. UNUSED_PARAMETER(manualUpdate);
  3337. #endif
  3338. }
  3339. void OBSBasic::updateCheckFinished()
  3340. {
  3341. ui->actionCheckForUpdates->setEnabled(true);
  3342. ui->actionRepair->setEnabled(true);
  3343. }
  3344. void OBSBasic::DuplicateSelectedScene()
  3345. {
  3346. OBSScene curScene = GetCurrentScene();
  3347. if (!curScene)
  3348. return;
  3349. OBSSource curSceneSource = obs_scene_get_source(curScene);
  3350. QString format{obs_source_get_name(curSceneSource)};
  3351. format += " %1";
  3352. int i = 2;
  3353. QString placeHolderText = format.arg(i);
  3354. OBSSourceAutoRelease source = nullptr;
  3355. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  3356. placeHolderText = format.arg(++i);
  3357. }
  3358. for (;;) {
  3359. string name;
  3360. bool accepted = NameDialog::AskForName(
  3361. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  3362. QTStr("Basic.Main.AddSceneDlg.Text"), name,
  3363. placeHolderText);
  3364. if (!accepted)
  3365. return;
  3366. if (name.empty()) {
  3367. OBSMessageBox::warning(this,
  3368. QTStr("NoNameEntered.Title"),
  3369. QTStr("NoNameEntered.Text"));
  3370. continue;
  3371. }
  3372. obs_source_t *source = obs_get_source_by_name(name.c_str());
  3373. if (source) {
  3374. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  3375. QTStr("NameExists.Text"));
  3376. obs_source_release(source);
  3377. continue;
  3378. }
  3379. OBSSceneAutoRelease scene = obs_scene_duplicate(
  3380. curScene, name.c_str(), OBS_SCENE_DUP_REFS);
  3381. source = obs_scene_get_source(scene);
  3382. SetCurrentScene(source, true);
  3383. auto undo = [](const std::string &data) {
  3384. OBSSourceAutoRelease source =
  3385. obs_get_source_by_name(data.c_str());
  3386. obs_source_remove(source);
  3387. };
  3388. auto redo = [this, name](const std::string &data) {
  3389. OBSSourceAutoRelease source =
  3390. obs_get_source_by_name(data.c_str());
  3391. obs_scene_t *scene = obs_scene_from_source(source);
  3392. scene = obs_scene_duplicate(scene, name.c_str(),
  3393. OBS_SCENE_DUP_REFS);
  3394. source = obs_scene_get_source(scene);
  3395. SetCurrentScene(source.Get(), true);
  3396. };
  3397. undo_s.add_action(
  3398. QTStr("Undo.Scene.Duplicate")
  3399. .arg(obs_source_get_name(source)),
  3400. undo, redo, obs_source_get_name(source),
  3401. obs_source_get_name(obs_scene_get_source(curScene)));
  3402. break;
  3403. }
  3404. }
  3405. static bool save_undo_source_enum(obs_scene_t * /* scene */,
  3406. obs_sceneitem_t *item, void *p)
  3407. {
  3408. obs_source_t *source = obs_sceneitem_get_source(item);
  3409. if (obs_obj_is_private(source) && !obs_source_removed(source))
  3410. return true;
  3411. obs_data_array_t *array = (obs_data_array_t *)p;
  3412. /* check if the source is already stored in the array */
  3413. const char *name = obs_source_get_name(source);
  3414. const size_t count = obs_data_array_count(array);
  3415. for (size_t i = 0; i < count; i++) {
  3416. OBSDataAutoRelease sourceData = obs_data_array_item(array, i);
  3417. if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0)
  3418. return true;
  3419. }
  3420. if (obs_source_is_group(source))
  3421. obs_scene_enum_items(obs_group_from_source(source),
  3422. save_undo_source_enum, p);
  3423. OBSDataAutoRelease source_data = obs_save_source(source);
  3424. obs_data_array_push_back(array, source_data);
  3425. return true;
  3426. }
  3427. static inline void RemoveSceneAndReleaseNested(obs_source_t *source)
  3428. {
  3429. obs_source_remove(source);
  3430. auto cb = [](void *, obs_source_t *source) {
  3431. if (strcmp(obs_source_get_id(source), "scene") == 0)
  3432. obs_scene_prune_sources(obs_scene_from_source(source));
  3433. return true;
  3434. };
  3435. obs_enum_scenes(cb, NULL);
  3436. }
  3437. void OBSBasic::RemoveSelectedScene()
  3438. {
  3439. OBSScene scene = GetCurrentScene();
  3440. obs_source_t *source = obs_scene_get_source(scene);
  3441. if (!source || !QueryRemoveSource(source)) {
  3442. return;
  3443. }
  3444. /* ------------------------------ */
  3445. /* save all sources in scene */
  3446. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3447. obs_data_array_create();
  3448. obs_scene_enum_items(scene, save_undo_source_enum,
  3449. sources_in_deleted_scene);
  3450. OBSDataAutoRelease scene_data = obs_save_source(source);
  3451. obs_data_array_push_back(sources_in_deleted_scene, scene_data);
  3452. /* ----------------------------------------------- */
  3453. /* save all scenes and groups the scene is used in */
  3454. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3455. obs_data_array_create();
  3456. struct other_scenes_cb_data {
  3457. obs_source_t *oldScene;
  3458. obs_data_array_t *scene_used_in_other_scenes;
  3459. } other_scenes_cb_data;
  3460. other_scenes_cb_data.oldScene = source;
  3461. other_scenes_cb_data.scene_used_in_other_scenes =
  3462. scene_used_in_other_scenes;
  3463. auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) {
  3464. struct other_scenes_cb_data *data =
  3465. (struct other_scenes_cb_data *)data_ptr;
  3466. if (strcmp(obs_source_get_name(scene),
  3467. obs_source_get_name(data->oldScene)) == 0)
  3468. return true;
  3469. obs_sceneitem_t *item = obs_scene_find_source(
  3470. obs_group_or_scene_from_source(scene),
  3471. obs_source_get_name(data->oldScene));
  3472. if (item) {
  3473. OBSDataAutoRelease scene_data =
  3474. obs_save_source(obs_scene_get_source(
  3475. obs_sceneitem_get_scene(item)));
  3476. obs_data_array_push_back(
  3477. data->scene_used_in_other_scenes, scene_data);
  3478. }
  3479. return true;
  3480. };
  3481. obs_enum_scenes(other_scenes_cb, &other_scenes_cb_data);
  3482. /* --------------------------- */
  3483. /* undo/redo */
  3484. auto undo = [this](const std::string &json) {
  3485. OBSDataAutoRelease base =
  3486. obs_data_create_from_json(json.c_str());
  3487. OBSDataArrayAutoRelease sources_in_deleted_scene =
  3488. obs_data_get_array(base, "sources_in_deleted_scene");
  3489. OBSDataArrayAutoRelease scene_used_in_other_scenes =
  3490. obs_data_get_array(base, "scene_used_in_other_scenes");
  3491. int savedIndex = (int)obs_data_get_int(base, "index");
  3492. std::vector<OBSSource> sources;
  3493. /* create missing sources */
  3494. size_t count = obs_data_array_count(sources_in_deleted_scene);
  3495. sources.reserve(count);
  3496. for (size_t i = 0; i < count; i++) {
  3497. OBSDataAutoRelease data = obs_data_array_item(
  3498. sources_in_deleted_scene, i);
  3499. const char *name = obs_data_get_string(data, "name");
  3500. OBSSourceAutoRelease source =
  3501. obs_get_source_by_name(name);
  3502. if (!source) {
  3503. source = obs_load_source(data);
  3504. sources.push_back(source.Get());
  3505. }
  3506. }
  3507. /* actually load sources now */
  3508. for (obs_source_t *source : sources)
  3509. obs_source_load2(source);
  3510. /* Add scene to scenes and groups it was nested in */
  3511. for (size_t i = 0;
  3512. i < obs_data_array_count(scene_used_in_other_scenes);
  3513. i++) {
  3514. OBSDataAutoRelease data = obs_data_array_item(
  3515. scene_used_in_other_scenes, i);
  3516. const char *name = obs_data_get_string(data, "name");
  3517. OBSSourceAutoRelease source =
  3518. obs_get_source_by_name(name);
  3519. OBSDataAutoRelease settings =
  3520. obs_data_get_obj(data, "settings");
  3521. OBSDataArrayAutoRelease items =
  3522. obs_data_get_array(settings, "items");
  3523. /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */
  3524. std::vector<OBSSource> existing_sources;
  3525. auto cb = [](obs_scene_t *, obs_sceneitem_t *item,
  3526. void *data) {
  3527. std::vector<OBSSource> *existing =
  3528. (std::vector<OBSSource> *)data;
  3529. OBSSource source =
  3530. obs_sceneitem_get_source(item);
  3531. obs_sceneitem_remove(item);
  3532. existing->push_back(source);
  3533. return true;
  3534. };
  3535. obs_scene_enum_items(
  3536. obs_group_or_scene_from_source(source), cb,
  3537. (void *)&existing_sources);
  3538. /* Re-add sources to the scene */
  3539. obs_sceneitems_add(
  3540. obs_group_or_scene_from_source(source), items);
  3541. }
  3542. obs_source_t *scene_source = sources.back();
  3543. OBSScene scene = obs_scene_from_source(scene_source);
  3544. SetCurrentScene(scene, true);
  3545. /* set original index in list box */
  3546. ui->scenes->blockSignals(true);
  3547. int curIndex = ui->scenes->currentRow();
  3548. QListWidgetItem *item = ui->scenes->takeItem(curIndex);
  3549. ui->scenes->insertItem(savedIndex, item);
  3550. ui->scenes->setCurrentRow(savedIndex);
  3551. currentScene = scene.Get();
  3552. ui->scenes->blockSignals(false);
  3553. };
  3554. auto redo = [](const std::string &name) {
  3555. OBSSourceAutoRelease source =
  3556. obs_get_source_by_name(name.c_str());
  3557. RemoveSceneAndReleaseNested(source);
  3558. };
  3559. OBSDataAutoRelease data = obs_data_create();
  3560. obs_data_set_array(data, "sources_in_deleted_scene",
  3561. sources_in_deleted_scene);
  3562. obs_data_set_array(data, "scene_used_in_other_scenes",
  3563. scene_used_in_other_scenes);
  3564. obs_data_set_int(data, "index", ui->scenes->currentRow());
  3565. const char *scene_name = obs_source_get_name(source);
  3566. undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo,
  3567. obs_data_get_json(data), scene_name);
  3568. /* --------------------------- */
  3569. /* remove */
  3570. RemoveSceneAndReleaseNested(source);
  3571. if (api)
  3572. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  3573. }
  3574. void OBSBasic::ReorderSources(OBSScene scene)
  3575. {
  3576. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3577. return;
  3578. ui->sources->ReorderItems();
  3579. SaveProject();
  3580. }
  3581. void OBSBasic::RefreshSources(OBSScene scene)
  3582. {
  3583. if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
  3584. return;
  3585. ui->sources->RefreshItems();
  3586. SaveProject();
  3587. }
  3588. /* OBS Callbacks */
  3589. void OBSBasic::SceneReordered(void *data, calldata_t *params)
  3590. {
  3591. OBSBasic *window = static_cast<OBSBasic *>(data);
  3592. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3593. QMetaObject::invokeMethod(window, "ReorderSources",
  3594. Q_ARG(OBSScene, OBSScene(scene)));
  3595. }
  3596. void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
  3597. {
  3598. OBSBasic *window = static_cast<OBSBasic *>(data);
  3599. obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
  3600. QMetaObject::invokeMethod(window, "RefreshSources",
  3601. Q_ARG(OBSScene, OBSScene(scene)));
  3602. }
  3603. void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
  3604. {
  3605. OBSBasic *window = static_cast<OBSBasic *>(data);
  3606. obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
  3607. QMetaObject::invokeMethod(window, "AddSceneItem",
  3608. Q_ARG(OBSSceneItem, OBSSceneItem(item)));
  3609. }
  3610. void OBSBasic::SourceCreated(void *data, calldata_t *params)
  3611. {
  3612. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3613. if (obs_scene_from_source(source) != NULL)
  3614. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3615. "AddScene", WaitConnection(),
  3616. Q_ARG(OBSSource, OBSSource(source)));
  3617. }
  3618. void OBSBasic::SourceRemoved(void *data, calldata_t *params)
  3619. {
  3620. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3621. if (obs_scene_from_source(source) != NULL)
  3622. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3623. "RemoveScene",
  3624. Q_ARG(OBSSource, OBSSource(source)));
  3625. }
  3626. void OBSBasic::SourceActivated(void *data, calldata_t *params)
  3627. {
  3628. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3629. uint32_t flags = obs_source_get_output_flags(source);
  3630. if (flags & OBS_SOURCE_AUDIO)
  3631. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3632. "ActivateAudioSource",
  3633. Q_ARG(OBSSource, OBSSource(source)));
  3634. }
  3635. void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
  3636. {
  3637. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3638. uint32_t flags = obs_source_get_output_flags(source);
  3639. if (flags & OBS_SOURCE_AUDIO)
  3640. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3641. "DeactivateAudioSource",
  3642. Q_ARG(OBSSource, OBSSource(source)));
  3643. }
  3644. void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
  3645. {
  3646. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3647. if (obs_source_active(source))
  3648. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3649. "ActivateAudioSource",
  3650. Q_ARG(OBSSource, OBSSource(source)));
  3651. }
  3652. void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
  3653. {
  3654. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3655. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3656. "DeactivateAudioSource",
  3657. Q_ARG(OBSSource, OBSSource(source)));
  3658. }
  3659. void OBSBasic::SourceRenamed(void *data, calldata_t *params)
  3660. {
  3661. obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
  3662. const char *newName = calldata_string(params, "new_name");
  3663. const char *prevName = calldata_string(params, "prev_name");
  3664. QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
  3665. "RenameSources", Q_ARG(OBSSource, source),
  3666. Q_ARG(QString, QT_UTF8(newName)),
  3667. Q_ARG(QString, QT_UTF8(prevName)));
  3668. blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
  3669. }
  3670. void OBSBasic::DrawBackdrop(float cx, float cy)
  3671. {
  3672. if (!box)
  3673. return;
  3674. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");
  3675. gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
  3676. gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
  3677. gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
  3678. vec4 colorVal;
  3679. vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
  3680. gs_effect_set_vec4(color, &colorVal);
  3681. gs_technique_begin(tech);
  3682. gs_technique_begin_pass(tech, 0);
  3683. gs_matrix_push();
  3684. gs_matrix_identity();
  3685. gs_matrix_scale3f(float(cx), float(cy), 1.0f);
  3686. gs_load_vertexbuffer(box);
  3687. gs_draw(GS_TRISTRIP, 0, 0);
  3688. gs_matrix_pop();
  3689. gs_technique_end_pass(tech);
  3690. gs_technique_end(tech);
  3691. gs_load_vertexbuffer(nullptr);
  3692. GS_DEBUG_MARKER_END();
  3693. }
  3694. void OBSBasic::RenderMain(void *data, uint32_t, uint32_t)
  3695. {
  3696. GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");
  3697. OBSBasic *window = static_cast<OBSBasic *>(data);
  3698. obs_video_info ovi;
  3699. obs_get_video_info(&ovi);
  3700. window->previewCX = int(window->previewScale * float(ovi.base_width));
  3701. window->previewCY = int(window->previewScale * float(ovi.base_height));
  3702. gs_viewport_push();
  3703. gs_projection_push();
  3704. obs_display_t *display = window->ui->preview->GetDisplay();
  3705. uint32_t width, height;
  3706. obs_display_size(display, &width, &height);
  3707. float right = float(width) - window->previewX;
  3708. float bottom = float(height) - window->previewY;
  3709. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3710. 100.0f);
  3711. window->ui->preview->DrawOverflow();
  3712. /* --------------------------------------- */
  3713. gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
  3714. -100.0f, 100.0f);
  3715. gs_set_viewport(window->previewX, window->previewY, window->previewCX,
  3716. window->previewCY);
  3717. if (window->IsPreviewProgramMode()) {
  3718. window->DrawBackdrop(float(ovi.base_width),
  3719. float(ovi.base_height));
  3720. OBSScene scene = window->GetCurrentScene();
  3721. obs_source_t *source = obs_scene_get_source(scene);
  3722. if (source)
  3723. obs_source_video_render(source);
  3724. } else {
  3725. obs_render_main_texture_src_color_only();
  3726. }
  3727. gs_load_vertexbuffer(nullptr);
  3728. /* --------------------------------------- */
  3729. gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
  3730. 100.0f);
  3731. gs_reset_viewport();
  3732. uint32_t targetCX = window->previewCX;
  3733. uint32_t targetCY = window->previewCY;
  3734. if (window->drawSafeAreas) {
  3735. RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY);
  3736. RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY);
  3737. RenderSafeAreas(window->fourByThreeSafeMargin, targetCX,
  3738. targetCY);
  3739. RenderSafeAreas(window->leftLine, targetCX, targetCY);
  3740. RenderSafeAreas(window->topLine, targetCX, targetCY);
  3741. RenderSafeAreas(window->rightLine, targetCX, targetCY);
  3742. }
  3743. window->ui->preview->DrawSceneEditing();
  3744. if (window->drawSpacingHelpers)
  3745. window->ui->preview->DrawSpacingHelpers();
  3746. /* --------------------------------------- */
  3747. gs_projection_pop();
  3748. gs_viewport_pop();
  3749. GS_DEBUG_MARKER_END();
  3750. }
  3751. /* Main class functions */
  3752. obs_service_t *OBSBasic::GetService()
  3753. {
  3754. if (!service) {
  3755. service =
  3756. obs_service_create("rtmp_common", NULL, NULL, nullptr);
  3757. obs_service_release(service);
  3758. }
  3759. return service;
  3760. }
  3761. void OBSBasic::SetService(obs_service_t *newService)
  3762. {
  3763. if (newService) {
  3764. service = newService;
  3765. }
  3766. }
  3767. int OBSBasic::GetTransitionDuration()
  3768. {
  3769. return ui->transitionDuration->value();
  3770. }
  3771. bool OBSBasic::Active() const
  3772. {
  3773. if (!outputHandler)
  3774. return false;
  3775. return outputHandler->Active();
  3776. }
  3777. #ifdef _WIN32
  3778. #define IS_WIN32 1
  3779. #else
  3780. #define IS_WIN32 0
  3781. #endif
  3782. static inline int AttemptToResetVideo(struct obs_video_info *ovi)
  3783. {
  3784. return obs_reset_video(ovi);
  3785. }
  3786. static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
  3787. {
  3788. const char *scaleTypeStr =
  3789. config_get_string(basicConfig, "Video", "ScaleType");
  3790. if (astrcmpi(scaleTypeStr, "bilinear") == 0)
  3791. return OBS_SCALE_BILINEAR;
  3792. else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
  3793. return OBS_SCALE_LANCZOS;
  3794. else if (astrcmpi(scaleTypeStr, "area") == 0)
  3795. return OBS_SCALE_AREA;
  3796. else
  3797. return OBS_SCALE_BICUBIC;
  3798. }
  3799. static inline enum video_format GetVideoFormatFromName(const char *name)
  3800. {
  3801. if (astrcmpi(name, "I420") == 0)
  3802. return VIDEO_FORMAT_I420;
  3803. else if (astrcmpi(name, "NV12") == 0)
  3804. return VIDEO_FORMAT_NV12;
  3805. else if (astrcmpi(name, "I444") == 0)
  3806. return VIDEO_FORMAT_I444;
  3807. else if (astrcmpi(name, "I010") == 0)
  3808. return VIDEO_FORMAT_I010;
  3809. else if (astrcmpi(name, "P010") == 0)
  3810. return VIDEO_FORMAT_P010;
  3811. else if (astrcmpi(name, "P216") == 0)
  3812. return VIDEO_FORMAT_P216;
  3813. else if (astrcmpi(name, "P416") == 0)
  3814. return VIDEO_FORMAT_P416;
  3815. #if 0 //currently unsupported
  3816. else if (astrcmpi(name, "YVYU") == 0)
  3817. return VIDEO_FORMAT_YVYU;
  3818. else if (astrcmpi(name, "YUY2") == 0)
  3819. return VIDEO_FORMAT_YUY2;
  3820. else if (astrcmpi(name, "UYVY") == 0)
  3821. return VIDEO_FORMAT_UYVY;
  3822. #endif
  3823. else
  3824. return VIDEO_FORMAT_BGRA;
  3825. }
  3826. static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name)
  3827. {
  3828. enum video_colorspace colorspace = VIDEO_CS_SRGB;
  3829. if (strcmp(name, "601") == 0)
  3830. colorspace = VIDEO_CS_601;
  3831. else if (strcmp(name, "709") == 0)
  3832. colorspace = VIDEO_CS_709;
  3833. else if (strcmp(name, "2100PQ") == 0)
  3834. colorspace = VIDEO_CS_2100_PQ;
  3835. else if (strcmp(name, "2100HLG") == 0)
  3836. colorspace = VIDEO_CS_2100_HLG;
  3837. return colorspace;
  3838. }
  3839. void OBSBasic::ResetUI()
  3840. {
  3841. bool studioPortraitLayout = config_get_bool(
  3842. GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
  3843. if (studioPortraitLayout)
  3844. ui->previewLayout->setDirection(QBoxLayout::BottomToTop);
  3845. else
  3846. ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
  3847. UpdatePreviewProgramIndicators();
  3848. }
  3849. int OBSBasic::ResetVideo()
  3850. {
  3851. if (outputHandler && outputHandler->Active())
  3852. return OBS_VIDEO_CURRENTLY_ACTIVE;
  3853. ProfileScope("OBSBasic::ResetVideo");
  3854. struct obs_video_info ovi;
  3855. int ret;
  3856. GetConfigFPS(ovi.fps_num, ovi.fps_den);
  3857. const char *colorFormat =
  3858. config_get_string(basicConfig, "Video", "ColorFormat");
  3859. const char *colorSpace =
  3860. config_get_string(basicConfig, "Video", "ColorSpace");
  3861. const char *colorRange =
  3862. config_get_string(basicConfig, "Video", "ColorRange");
  3863. ovi.graphics_module = App()->GetRenderModule();
  3864. ovi.base_width =
  3865. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
  3866. ovi.base_height =
  3867. (uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
  3868. ovi.output_width =
  3869. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
  3870. ovi.output_height =
  3871. (uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
  3872. ovi.output_format = GetVideoFormatFromName(colorFormat);
  3873. ovi.colorspace = GetVideoColorSpaceFromName(colorSpace);
  3874. ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
  3875. : VIDEO_RANGE_PARTIAL;
  3876. ovi.adapter =
  3877. config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
  3878. ovi.gpu_conversion = true;
  3879. ovi.scale_type = GetScaleType(basicConfig);
  3880. if (ovi.base_width < 8 || ovi.base_height < 8) {
  3881. ovi.base_width = 1920;
  3882. ovi.base_height = 1080;
  3883. config_set_uint(basicConfig, "Video", "BaseCX", 1920);
  3884. config_set_uint(basicConfig, "Video", "BaseCY", 1080);
  3885. }
  3886. if (ovi.output_width < 8 || ovi.output_height < 8) {
  3887. ovi.output_width = ovi.base_width;
  3888. ovi.output_height = ovi.base_height;
  3889. config_set_uint(basicConfig, "Video", "OutputCX",
  3890. ovi.base_width);
  3891. config_set_uint(basicConfig, "Video", "OutputCY",
  3892. ovi.base_height);
  3893. }
  3894. ret = AttemptToResetVideo(&ovi);
  3895. if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
  3896. if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
  3897. blog(LOG_WARNING, "Tried to reset when "
  3898. "already active");
  3899. return ret;
  3900. }
  3901. /* Try OpenGL if DirectX fails on windows */
  3902. if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
  3903. blog(LOG_WARNING,
  3904. "Failed to initialize obs video (%d) "
  3905. "with graphics_module='%s', retrying "
  3906. "with graphics_module='%s'",
  3907. ret, ovi.graphics_module, DL_OPENGL);
  3908. ovi.graphics_module = DL_OPENGL;
  3909. ret = AttemptToResetVideo(&ovi);
  3910. }
  3911. } else if (ret == OBS_VIDEO_SUCCESS) {
  3912. ResizePreview(ovi.base_width, ovi.base_height);
  3913. if (program)
  3914. ResizeProgram(ovi.base_width, ovi.base_height);
  3915. }
  3916. if (ret == OBS_VIDEO_SUCCESS) {
  3917. const float sdr_white_level = (float)config_get_uint(
  3918. basicConfig, "Video", "SdrWhiteLevel");
  3919. const float hdr_nominal_peak_level = (float)config_get_uint(
  3920. basicConfig, "Video", "HdrNominalPeakLevel");
  3921. obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level);
  3922. OBSBasicStats::InitializeValues();
  3923. OBSProjector::UpdateMultiviewProjectors();
  3924. }
  3925. return ret;
  3926. }
  3927. bool OBSBasic::ResetAudio()
  3928. {
  3929. ProfileScope("OBSBasic::ResetAudio");
  3930. struct obs_audio_info2 ai = {};
  3931. ai.samples_per_sec =
  3932. config_get_uint(basicConfig, "Audio", "SampleRate");
  3933. const char *channelSetupStr =
  3934. config_get_string(basicConfig, "Audio", "ChannelSetup");
  3935. if (strcmp(channelSetupStr, "Mono") == 0)
  3936. ai.speakers = SPEAKERS_MONO;
  3937. else if (strcmp(channelSetupStr, "2.1") == 0)
  3938. ai.speakers = SPEAKERS_2POINT1;
  3939. else if (strcmp(channelSetupStr, "4.0") == 0)
  3940. ai.speakers = SPEAKERS_4POINT0;
  3941. else if (strcmp(channelSetupStr, "4.1") == 0)
  3942. ai.speakers = SPEAKERS_4POINT1;
  3943. else if (strcmp(channelSetupStr, "5.1") == 0)
  3944. ai.speakers = SPEAKERS_5POINT1;
  3945. else if (strcmp(channelSetupStr, "7.1") == 0)
  3946. ai.speakers = SPEAKERS_7POINT1;
  3947. else
  3948. ai.speakers = SPEAKERS_STEREO;
  3949. bool lowLatencyAudioBuffering = config_get_bool(
  3950. GetGlobalConfig(), "Audio", "LowLatencyAudioBuffering");
  3951. if (lowLatencyAudioBuffering) {
  3952. ai.max_buffering_ms = 20;
  3953. ai.fixed_buffering = true;
  3954. }
  3955. return obs_reset_audio2(&ai);
  3956. }
  3957. extern char *get_new_source_name(const char *name, const char *format);
  3958. void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
  3959. const char *deviceDesc, int channel)
  3960. {
  3961. bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
  3962. OBSSourceAutoRelease source;
  3963. OBSDataAutoRelease settings;
  3964. source = obs_get_output_source(channel);
  3965. if (source) {
  3966. if (disable) {
  3967. obs_set_output_source(channel, nullptr);
  3968. } else {
  3969. settings = obs_source_get_settings(source);
  3970. const char *oldId =
  3971. obs_data_get_string(settings, "device_id");
  3972. if (strcmp(oldId, deviceId) != 0) {
  3973. obs_data_set_string(settings, "device_id",
  3974. deviceId);
  3975. obs_source_update(source, settings);
  3976. }
  3977. }
  3978. } else if (!disable) {
  3979. BPtr<char> name = get_new_source_name(deviceDesc, "%s (%d)");
  3980. settings = obs_data_create();
  3981. obs_data_set_string(settings, "device_id", deviceId);
  3982. source = obs_source_create(sourceId, name, settings, nullptr);
  3983. obs_set_output_source(channel, source);
  3984. }
  3985. }
  3986. void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
  3987. {
  3988. QSize targetSize;
  3989. bool isFixedScaling;
  3990. obs_video_info ovi;
  3991. /* resize preview panel to fix to the top section of the window */
  3992. targetSize = GetPixelSize(ui->preview);
  3993. isFixedScaling = ui->preview->IsFixedScaling();
  3994. obs_get_video_info(&ovi);
  3995. if (isFixedScaling) {
  3996. ui->preview->ClampScrollingOffsets();
  3997. previewScale = ui->preview->GetScalingAmount();
  3998. GetCenterPosFromFixedScale(
  3999. int(cx), int(cy),
  4000. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4001. targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
  4002. previewY, previewScale);
  4003. previewX += ui->preview->GetScrollX();
  4004. previewY += ui->preview->GetScrollY();
  4005. } else {
  4006. GetScaleAndCenterPos(int(cx), int(cy),
  4007. targetSize.width() - PREVIEW_EDGE_SIZE * 2,
  4008. targetSize.height() -
  4009. PREVIEW_EDGE_SIZE * 2,
  4010. previewX, previewY, previewScale);
  4011. }
  4012. previewX += float(PREVIEW_EDGE_SIZE);
  4013. previewY += float(PREVIEW_EDGE_SIZE);
  4014. }
  4015. void OBSBasic::CloseDialogs()
  4016. {
  4017. QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
  4018. if (!childDialogs.isEmpty()) {
  4019. for (int i = 0; i < childDialogs.size(); ++i) {
  4020. childDialogs.at(i)->close();
  4021. }
  4022. }
  4023. if (!stats.isNull())
  4024. stats->close(); //call close to save Stats geometry
  4025. if (!remux.isNull())
  4026. remux->close();
  4027. }
  4028. void OBSBasic::EnumDialogs()
  4029. {
  4030. visDialogs.clear();
  4031. modalDialogs.clear();
  4032. visMsgBoxes.clear();
  4033. /* fill list of Visible dialogs and Modal dialogs */
  4034. QList<QDialog *> dialogs = findChildren<QDialog *>();
  4035. for (QDialog *dialog : dialogs) {
  4036. if (dialog->isVisible())
  4037. visDialogs.append(dialog);
  4038. if (dialog->isModal())
  4039. modalDialogs.append(dialog);
  4040. }
  4041. /* fill list of Visible message boxes */
  4042. QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
  4043. for (QMessageBox *msgbox : msgBoxes) {
  4044. if (msgbox->isVisible())
  4045. visMsgBoxes.append(msgbox);
  4046. }
  4047. }
  4048. void OBSBasic::ClearProjectors()
  4049. {
  4050. for (size_t i = 0; i < projectors.size(); i++) {
  4051. if (projectors[i])
  4052. delete projectors[i];
  4053. }
  4054. projectors.clear();
  4055. }
  4056. void OBSBasic::ClearSceneData()
  4057. {
  4058. disableSaving++;
  4059. setCursor(Qt::WaitCursor);
  4060. CloseDialogs();
  4061. ClearVolumeControls();
  4062. ClearListItems(ui->scenes);
  4063. ui->sources->Clear();
  4064. ClearQuickTransitions();
  4065. ui->transitions->clear();
  4066. ClearProjectors();
  4067. for (int i = 0; i < MAX_CHANNELS; i++)
  4068. obs_set_output_source(i, nullptr);
  4069. /* Reset VCam to default to clear its private scene and any references
  4070. * it holds. It will be reconfigured during loading. */
  4071. if (vcamEnabled) {
  4072. vcamConfig.type = VCamOutputType::ProgramView;
  4073. outputHandler->UpdateVirtualCamOutputSource();
  4074. }
  4075. safeModeModuleData = nullptr;
  4076. lastScene = nullptr;
  4077. swapScene = nullptr;
  4078. programScene = nullptr;
  4079. prevFTBSource = nullptr;
  4080. clipboard.clear();
  4081. copyFiltersSource = nullptr;
  4082. copyFilter = nullptr;
  4083. auto cb = [](void *, obs_source_t *source) {
  4084. obs_source_remove(source);
  4085. return true;
  4086. };
  4087. obs_enum_scenes(cb, nullptr);
  4088. obs_enum_sources(cb, nullptr);
  4089. if (api)
  4090. api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  4091. undo_s.clear();
  4092. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  4093. * that deleteLater events are processed at this point */
  4094. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  4095. do {
  4096. QApplication::sendPostedEvents(nullptr);
  4097. } while (obs_wait_for_destroy_queue());
  4098. /* Pump Qt events one final time to give remaining signals time to be
  4099. * processed (since this happens after the destroy thread finishes and
  4100. * the audio/video threads have processed their tasks). */
  4101. QApplication::sendPostedEvents(nullptr);
  4102. unsetCursor();
  4103. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  4104. * reference, they will still be in the hash table, enumerate them and
  4105. * store the names for logging purposes. */
  4106. auto cb2 = [](void *param, obs_source_t *source) {
  4107. auto orphans = static_cast<vector<string> *>(param);
  4108. orphans->push_back(obs_source_get_name(source));
  4109. return true;
  4110. };
  4111. vector<string> orphan_sources;
  4112. obs_enum_sources(cb2, &orphan_sources);
  4113. if (!orphan_sources.empty()) {
  4114. /* Avoid logging list twice in case it gets called after
  4115. * setting the flag the first time. */
  4116. if (!clearingFailed) {
  4117. /* This ugly mess exists to join a vector of strings
  4118. * with a user-defined delimiter. */
  4119. string orphan_names = std::accumulate(
  4120. orphan_sources.begin(), orphan_sources.end(),
  4121. string(""), [](string a, string b) {
  4122. return std::move(a) + "\n- " + b;
  4123. });
  4124. blog(LOG_ERROR,
  4125. "Not all sources were cleared when clearing scene data:\n%s\n",
  4126. orphan_names.c_str());
  4127. }
  4128. /* We do not decrement disableSaving here to avoid OBS
  4129. * overwriting user data with garbage. */
  4130. clearingFailed = true;
  4131. } else {
  4132. disableSaving--;
  4133. blog(LOG_INFO, "All scene data cleared");
  4134. blog(LOG_INFO,
  4135. "------------------------------------------------");
  4136. }
  4137. }
  4138. void OBSBasic::closeEvent(QCloseEvent *event)
  4139. {
  4140. /* Do not close window if inside of a temporary event loop because we
  4141. * could be inside of an Auth::LoadUI call. Keep trying once per
  4142. * second until we've exit any known sub-loops. */
  4143. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4144. QTimer::singleShot(1000, this, &OBSBasic::close);
  4145. event->ignore();
  4146. return;
  4147. }
  4148. #ifdef YOUTUBE_ENABLED
  4149. /* Also don't close the window if the youtube stream check is active */
  4150. if (youtubeStreamCheckThread) {
  4151. QTimer::singleShot(1000, this, &OBSBasic::close);
  4152. event->ignore();
  4153. return;
  4154. }
  4155. #endif
  4156. if (isVisible())
  4157. config_set_string(App()->GlobalConfig(), "BasicWindow",
  4158. "geometry",
  4159. saveGeometry().toBase64().constData());
  4160. bool confirmOnExit =
  4161. config_get_bool(GetGlobalConfig(), "General", "ConfirmOnExit");
  4162. if (confirmOnExit && outputHandler && outputHandler->Active() &&
  4163. !clearingFailed) {
  4164. SetShowing(true);
  4165. QMessageBox::StandardButton button = OBSMessageBox::question(
  4166. this, QTStr("ConfirmExit.Title"),
  4167. QTStr("ConfirmExit.Text"));
  4168. if (button == QMessageBox::No) {
  4169. event->ignore();
  4170. restart = false;
  4171. return;
  4172. }
  4173. }
  4174. if (remux && !remux->close()) {
  4175. event->ignore();
  4176. restart = false;
  4177. return;
  4178. }
  4179. QWidget::closeEvent(event);
  4180. if (!event->isAccepted())
  4181. return;
  4182. blog(LOG_INFO, SHUTDOWN_SEPARATOR);
  4183. closing = true;
  4184. if (outputHandler->VirtualCamActive())
  4185. outputHandler->StopVirtualCam();
  4186. if (introCheckThread)
  4187. introCheckThread->wait();
  4188. if (whatsNewInitThread)
  4189. whatsNewInitThread->wait();
  4190. if (updateCheckThread)
  4191. updateCheckThread->wait();
  4192. if (logUploadThread)
  4193. logUploadThread->wait();
  4194. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  4195. devicePropertiesThread->wait();
  4196. devicePropertiesThread.reset();
  4197. }
  4198. QApplication::sendPostedEvents(nullptr);
  4199. signalHandlers.clear();
  4200. Auth::Save();
  4201. SaveProjectNow();
  4202. auth.reset();
  4203. delete extraBrowsers;
  4204. ui->preview->DestroyDisplay();
  4205. if (program)
  4206. program->DestroyDisplay();
  4207. config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
  4208. saveState().toBase64().constData());
  4209. #ifdef BROWSER_AVAILABLE
  4210. if (cef)
  4211. SaveExtraBrowserDocks();
  4212. ClearExtraBrowserDocks();
  4213. #endif
  4214. if (api)
  4215. api->on_event(OBS_FRONTEND_EVENT_SCRIPTING_SHUTDOWN);
  4216. disableSaving++;
  4217. /* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
  4218. * sources, etc) so that all references are released before shutdown */
  4219. ClearSceneData();
  4220. if (api)
  4221. api->on_event(OBS_FRONTEND_EVENT_EXIT);
  4222. // Destroys the frontend API so plugins can't continue calling it
  4223. obs_frontend_set_callbacks_internal(nullptr);
  4224. api = nullptr;
  4225. QMetaObject::invokeMethod(App(), "quit", Qt::QueuedConnection);
  4226. }
  4227. bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *)
  4228. {
  4229. #ifdef _WIN32
  4230. const MSG &msg = *static_cast<MSG *>(message);
  4231. switch (msg.message) {
  4232. case WM_MOVE:
  4233. for (OBSQTDisplay *const display :
  4234. findChildren<OBSQTDisplay *>()) {
  4235. display->OnMove();
  4236. }
  4237. break;
  4238. case WM_DISPLAYCHANGE:
  4239. for (OBSQTDisplay *const display :
  4240. findChildren<OBSQTDisplay *>()) {
  4241. display->OnDisplayChange();
  4242. }
  4243. }
  4244. #else
  4245. UNUSED_PARAMETER(message);
  4246. #endif
  4247. return false;
  4248. }
  4249. void OBSBasic::changeEvent(QEvent *event)
  4250. {
  4251. if (event->type() == QEvent::WindowStateChange) {
  4252. QWindowStateChangeEvent *stateEvent =
  4253. (QWindowStateChangeEvent *)event;
  4254. if (isMinimized()) {
  4255. if (trayIcon && trayIcon->isVisible() &&
  4256. sysTrayMinimizeToTray()) {
  4257. ToggleShowHide();
  4258. return;
  4259. }
  4260. if (previewEnabled)
  4261. EnablePreviewDisplay(false);
  4262. } else if (stateEvent->oldState() & Qt::WindowMinimized &&
  4263. isVisible()) {
  4264. if (previewEnabled)
  4265. EnablePreviewDisplay(true);
  4266. }
  4267. }
  4268. }
  4269. void OBSBasic::on_actionShow_Recordings_triggered()
  4270. {
  4271. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4272. const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
  4273. const char *adv_path =
  4274. strcmp(type, "Standard")
  4275. ? config_get_string(basicConfig, "AdvOut", "FFFilePath")
  4276. : config_get_string(basicConfig, "AdvOut",
  4277. "RecFilePath");
  4278. const char *path = strcmp(mode, "Advanced")
  4279. ? config_get_string(basicConfig,
  4280. "SimpleOutput",
  4281. "FilePath")
  4282. : adv_path;
  4283. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  4284. }
  4285. void OBSBasic::on_actionRemux_triggered()
  4286. {
  4287. if (!remux.isNull()) {
  4288. remux->show();
  4289. remux->raise();
  4290. return;
  4291. }
  4292. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  4293. const char *path = strcmp(mode, "Advanced")
  4294. ? config_get_string(basicConfig,
  4295. "SimpleOutput",
  4296. "FilePath")
  4297. : config_get_string(basicConfig, "AdvOut",
  4298. "RecFilePath");
  4299. OBSRemux *remuxDlg;
  4300. remuxDlg = new OBSRemux(path, this);
  4301. remuxDlg->show();
  4302. remux = remuxDlg;
  4303. }
  4304. void OBSBasic::on_action_Settings_triggered()
  4305. {
  4306. static bool settings_already_executing = false;
  4307. /* Do not load settings window if inside of a temporary event loop
  4308. * because we could be inside of an Auth::LoadUI call. Keep trying
  4309. * once per second until we've exit any known sub-loops. */
  4310. if (os_atomic_load_long(&insideEventLoop) != 0) {
  4311. QTimer::singleShot(1000, this,
  4312. &OBSBasic::on_action_Settings_triggered);
  4313. return;
  4314. }
  4315. if (settings_already_executing) {
  4316. return;
  4317. }
  4318. settings_already_executing = true;
  4319. {
  4320. OBSBasicSettings settings(this);
  4321. settings.exec();
  4322. }
  4323. settings_already_executing = false;
  4324. if (restart) {
  4325. QMessageBox::StandardButton button = OBSMessageBox::question(
  4326. this, QTStr("Restart"), QTStr("NeedsRestart"));
  4327. if (button == QMessageBox::Yes)
  4328. close();
  4329. else
  4330. restart = false;
  4331. }
  4332. }
  4333. void OBSBasic::on_actionShowMacPermissions_triggered()
  4334. {
  4335. #ifdef __APPLE__
  4336. OBSPermissions check(this, CheckPermission(kScreenCapture),
  4337. CheckPermission(kVideoDeviceAccess),
  4338. CheckPermission(kAudioDeviceAccess),
  4339. CheckPermission(kAccessibility));
  4340. check.exec();
  4341. #endif
  4342. }
  4343. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  4344. {
  4345. if (obs_missing_files_count(files) > 0) {
  4346. /* When loading the missing files dialog on launch, the
  4347. * window hasn't fully initialized by this point on macOS,
  4348. * so put this at the end of the current task queue. Fixes
  4349. * a bug where the window is behind OBS on startup. */
  4350. QTimer::singleShot(0, [this, files] {
  4351. missDialog = new OBSMissingFiles(files, this);
  4352. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  4353. missDialog->show();
  4354. missDialog->raise();
  4355. });
  4356. } else {
  4357. obs_missing_files_destroy(files);
  4358. /* Only raise dialog if triggered manually */
  4359. if (!disableSaving)
  4360. OBSMessageBox::information(
  4361. this, QTStr("MissingFiles.NoMissing.Title"),
  4362. QTStr("MissingFiles.NoMissing.Text"));
  4363. }
  4364. }
  4365. void OBSBasic::on_actionShowMissingFiles_triggered()
  4366. {
  4367. obs_missing_files_t *files = obs_missing_files_create();
  4368. auto cb_sources = [](void *data, obs_source_t *source) {
  4369. AddMissingFiles(data, source);
  4370. return true;
  4371. };
  4372. obs_enum_all_sources(cb_sources, files);
  4373. ShowMissingFilesDialog(files);
  4374. }
  4375. void OBSBasic::on_actionAdvAudioProperties_triggered()
  4376. {
  4377. if (advAudioWindow != nullptr) {
  4378. advAudioWindow->raise();
  4379. return;
  4380. }
  4381. bool iconsVisible = config_get_bool(App()->GlobalConfig(),
  4382. "BasicWindow", "ShowSourceIcons");
  4383. advAudioWindow = new OBSBasicAdvAudio(this);
  4384. advAudioWindow->show();
  4385. advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  4386. advAudioWindow->SetIconsVisible(iconsVisible);
  4387. }
  4388. void OBSBasic::on_actionMixerToolbarAdvAudio_triggered()
  4389. {
  4390. on_actionAdvAudioProperties_triggered();
  4391. }
  4392. void OBSBasic::on_actionMixerToolbarMenu_triggered()
  4393. {
  4394. QAction unhideAllAction(QTStr("UnhideAll"), this);
  4395. connect(&unhideAllAction, &QAction::triggered, this,
  4396. &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
  4397. QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
  4398. toggleControlLayoutAction.setCheckable(true);
  4399. toggleControlLayoutAction.setChecked(config_get_bool(
  4400. GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
  4401. connect(&toggleControlLayoutAction, &QAction::changed, this,
  4402. &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
  4403. QMenu popup;
  4404. popup.addAction(&unhideAllAction);
  4405. popup.addSeparator();
  4406. popup.addAction(&toggleControlLayoutAction);
  4407. popup.exec(QCursor::pos());
  4408. }
  4409. void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
  4410. QListWidgetItem *)
  4411. {
  4412. OBSSource source;
  4413. if (current) {
  4414. OBSScene scene = GetOBSRef<OBSScene>(current);
  4415. source = obs_scene_get_source(scene);
  4416. currentScene = scene;
  4417. } else {
  4418. currentScene = NULL;
  4419. }
  4420. SetCurrentScene(source);
  4421. if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput)
  4422. outputHandler->UpdateVirtualCamOutputSource();
  4423. if (api)
  4424. api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  4425. UpdateContextBar();
  4426. }
  4427. void OBSBasic::EditSceneName()
  4428. {
  4429. ui->scenesDock->removeAction(renameScene);
  4430. QListWidgetItem *item = ui->scenes->currentItem();
  4431. Qt::ItemFlags flags = item->flags();
  4432. item->setFlags(flags | Qt::ItemIsEditable);
  4433. ui->scenes->editItem(item);
  4434. item->setFlags(flags);
  4435. }
  4436. QList<QString> OBSBasic::GetProjectorMenuMonitorsFormatted()
  4437. {
  4438. QList<QString> projectorsFormatted;
  4439. QList<QScreen *> screens = QGuiApplication::screens();
  4440. for (int i = 0; i < screens.size(); i++) {
  4441. QScreen *screen = screens[i];
  4442. QRect screenGeometry = screen->geometry();
  4443. qreal ratio = screen->devicePixelRatio();
  4444. QString name = "";
  4445. #if defined(_WIN32) && QT_VERSION < QT_VERSION_CHECK(6, 4, 0)
  4446. QTextStream fullname(&name);
  4447. fullname << GetMonitorName(screen->name());
  4448. fullname << " (";
  4449. fullname << (i + 1);
  4450. fullname << ")";
  4451. #elif defined(__APPLE__) || defined(_WIN32)
  4452. name = screen->name();
  4453. #else
  4454. name = screen->model().simplified();
  4455. if (name.length() > 1 && name.endsWith("-"))
  4456. name.chop(1);
  4457. #endif
  4458. name = name.simplified();
  4459. if (name.length() == 0) {
  4460. name = QString("%1 %2")
  4461. .arg(QTStr("Display"))
  4462. .arg(QString::number(i + 1));
  4463. }
  4464. QString str =
  4465. QString("%1: %2x%3 @ %4,%5")
  4466. .arg(name,
  4467. QString::number(screenGeometry.width() *
  4468. ratio),
  4469. QString::number(screenGeometry.height() *
  4470. ratio),
  4471. QString::number(screenGeometry.x()),
  4472. QString::number(screenGeometry.y()));
  4473. projectorsFormatted.push_back(str);
  4474. }
  4475. return projectorsFormatted;
  4476. }
  4477. void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
  4478. {
  4479. QListWidgetItem *item = ui->scenes->itemAt(pos);
  4480. QMenu popup(this);
  4481. QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
  4482. popup.addAction(QTStr("Add"), this,
  4483. &OBSBasic::on_actionAddScene_triggered);
  4484. if (item) {
  4485. QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this);
  4486. copyFilters->setEnabled(false);
  4487. connect(copyFilters, &QAction::triggered, this,
  4488. &OBSBasic::SceneCopyFilters);
  4489. QAction *pasteFilters =
  4490. new QAction(QTStr("Paste.Filters"), this);
  4491. pasteFilters->setEnabled(
  4492. !obs_weak_source_expired(copyFiltersSource));
  4493. connect(pasteFilters, &QAction::triggered, this,
  4494. &OBSBasic::ScenePasteFilters);
  4495. popup.addSeparator();
  4496. popup.addAction(QTStr("Duplicate"), this,
  4497. &OBSBasic::DuplicateSelectedScene);
  4498. popup.addAction(copyFilters);
  4499. popup.addAction(pasteFilters);
  4500. popup.addSeparator();
  4501. popup.addAction(renameScene);
  4502. popup.addAction(ui->actionRemoveScene);
  4503. popup.addSeparator();
  4504. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
  4505. &OBSBasic::on_actionSceneUp_triggered);
  4506. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
  4507. this, &OBSBasic::on_actionSceneDown_triggered);
  4508. order.addSeparator();
  4509. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
  4510. this, &OBSBasic::MoveSceneToTop);
  4511. order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
  4512. this, &OBSBasic::MoveSceneToBottom);
  4513. popup.addMenu(&order);
  4514. popup.addSeparator();
  4515. delete sceneProjectorMenu;
  4516. sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
  4517. AddProjectorMenuMonitors(sceneProjectorMenu, this,
  4518. &OBSBasic::OpenSceneProjector);
  4519. popup.addMenu(sceneProjectorMenu);
  4520. QAction *sceneWindow = popup.addAction(
  4521. QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow);
  4522. popup.addAction(sceneWindow);
  4523. popup.addAction(QTStr("Screenshot.Scene"), this,
  4524. &OBSBasic::ScreenshotScene);
  4525. popup.addSeparator();
  4526. popup.addAction(QTStr("Filters"), this,
  4527. &OBSBasic::OpenSceneFilters);
  4528. popup.addSeparator();
  4529. delete perSceneTransitionMenu;
  4530. perSceneTransitionMenu = CreatePerSceneTransitionMenu();
  4531. popup.addMenu(perSceneTransitionMenu);
  4532. /* ---------------------- */
  4533. QAction *multiviewAction =
  4534. popup.addAction(QTStr("ShowInMultiview"));
  4535. OBSSource source = GetCurrentSceneSource();
  4536. OBSDataAutoRelease data =
  4537. obs_source_get_private_settings(source);
  4538. obs_data_set_default_bool(data, "show_in_multiview", true);
  4539. bool show = obs_data_get_bool(data, "show_in_multiview");
  4540. multiviewAction->setCheckable(true);
  4541. multiviewAction->setChecked(show);
  4542. auto showInMultiview = [](OBSData data) {
  4543. bool show =
  4544. obs_data_get_bool(data, "show_in_multiview");
  4545. obs_data_set_bool(data, "show_in_multiview", !show);
  4546. OBSProjector::UpdateMultiviewProjectors();
  4547. };
  4548. connect(multiviewAction, &QAction::triggered,
  4549. std::bind(showInMultiview, data.Get()));
  4550. copyFilters->setEnabled(obs_source_filter_count(source) > 0);
  4551. }
  4552. popup.addSeparator();
  4553. bool grid = ui->scenes->GetGridMode();
  4554. QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
  4555. : QTStr("Basic.Main.GridMode"),
  4556. this);
  4557. connect(gridAction, &QAction::triggered, this,
  4558. &OBSBasic::GridActionClicked);
  4559. popup.addAction(gridAction);
  4560. popup.exec(QCursor::pos());
  4561. }
  4562. void OBSBasic::on_actionSceneListMode_triggered()
  4563. {
  4564. ui->scenes->SetGridMode(false);
  4565. }
  4566. void OBSBasic::on_actionSceneGridMode_triggered()
  4567. {
  4568. ui->scenes->SetGridMode(true);
  4569. }
  4570. void OBSBasic::GridActionClicked()
  4571. {
  4572. bool gridMode = !ui->scenes->GetGridMode();
  4573. ui->scenes->SetGridMode(gridMode);
  4574. if (gridMode)
  4575. ui->actionSceneGridMode->setChecked(true);
  4576. else
  4577. ui->actionSceneListMode->setChecked(true);
  4578. config_set_bool(App()->GlobalConfig(), "BasicWindow", "gridMode",
  4579. gridMode);
  4580. }
  4581. void OBSBasic::on_actionAddScene_triggered()
  4582. {
  4583. string name;
  4584. QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
  4585. int i = 2;
  4586. QString placeHolderText = format.arg(i);
  4587. OBSSourceAutoRelease source = nullptr;
  4588. while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
  4589. placeHolderText = format.arg(++i);
  4590. }
  4591. bool accepted = NameDialog::AskForName(
  4592. this, QTStr("Basic.Main.AddSceneDlg.Title"),
  4593. QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
  4594. if (accepted) {
  4595. if (name.empty()) {
  4596. OBSMessageBox::warning(this,
  4597. QTStr("NoNameEntered.Title"),
  4598. QTStr("NoNameEntered.Text"));
  4599. on_actionAddScene_triggered();
  4600. return;
  4601. }
  4602. OBSSourceAutoRelease source =
  4603. obs_get_source_by_name(name.c_str());
  4604. if (source) {
  4605. OBSMessageBox::warning(this, QTStr("NameExists.Title"),
  4606. QTStr("NameExists.Text"));
  4607. on_actionAddScene_triggered();
  4608. return;
  4609. }
  4610. auto undo_fn = [](const std::string &data) {
  4611. obs_source_t *t = obs_get_source_by_name(data.c_str());
  4612. if (t) {
  4613. obs_source_remove(t);
  4614. obs_source_release(t);
  4615. }
  4616. };
  4617. auto redo_fn = [this](const std::string &data) {
  4618. OBSSceneAutoRelease scene =
  4619. obs_scene_create(data.c_str());
  4620. obs_source_t *source = obs_scene_get_source(scene);
  4621. SetCurrentScene(source, true);
  4622. };
  4623. undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())),
  4624. undo_fn, redo_fn, name, name);
  4625. OBSSceneAutoRelease scene = obs_scene_create(name.c_str());
  4626. obs_source_t *scene_source = obs_scene_get_source(scene);
  4627. SetCurrentScene(scene_source);
  4628. }
  4629. }
  4630. void OBSBasic::on_actionRemoveScene_triggered()
  4631. {
  4632. RemoveSelectedScene();
  4633. }
  4634. void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
  4635. {
  4636. int idx = ui->scenes->currentRow();
  4637. if (idx == -1 || idx == invalidIdx)
  4638. return;
  4639. ui->scenes->blockSignals(true);
  4640. QListWidgetItem *item = ui->scenes->takeItem(idx);
  4641. if (!relative)
  4642. idx = 0;
  4643. ui->scenes->insertItem(idx + offset, item);
  4644. ui->scenes->setCurrentRow(idx + offset);
  4645. item->setSelected(true);
  4646. currentScene = GetOBSRef<OBSScene>(item).Get();
  4647. ui->scenes->blockSignals(false);
  4648. OBSProjector::UpdateMultiviewProjectors();
  4649. }
  4650. void OBSBasic::on_actionSceneUp_triggered()
  4651. {
  4652. ChangeSceneIndex(true, -1, 0);
  4653. }
  4654. void OBSBasic::on_actionSceneDown_triggered()
  4655. {
  4656. ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
  4657. }
  4658. void OBSBasic::MoveSceneToTop()
  4659. {
  4660. ChangeSceneIndex(false, 0, 0);
  4661. }
  4662. void OBSBasic::MoveSceneToBottom()
  4663. {
  4664. ChangeSceneIndex(false, ui->scenes->count() - 1,
  4665. ui->scenes->count() - 1);
  4666. }
  4667. void OBSBasic::EditSceneItemName()
  4668. {
  4669. int idx = GetTopSelectedSourceItem();
  4670. ui->sources->Edit(idx);
  4671. }
  4672. void OBSBasic::SetDeinterlacingMode()
  4673. {
  4674. QAction *action = reinterpret_cast<QAction *>(sender());
  4675. obs_deinterlace_mode mode =
  4676. (obs_deinterlace_mode)action->property("mode").toInt();
  4677. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4678. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4679. obs_source_set_deinterlace_mode(source, mode);
  4680. }
  4681. void OBSBasic::SetDeinterlacingOrder()
  4682. {
  4683. QAction *action = reinterpret_cast<QAction *>(sender());
  4684. obs_deinterlace_field_order order =
  4685. (obs_deinterlace_field_order)action->property("order").toInt();
  4686. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4687. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4688. obs_source_set_deinterlace_field_order(source, order);
  4689. }
  4690. QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
  4691. {
  4692. obs_deinterlace_mode deinterlaceMode =
  4693. obs_source_get_deinterlace_mode(source);
  4694. obs_deinterlace_field_order deinterlaceOrder =
  4695. obs_source_get_deinterlace_field_order(source);
  4696. QAction *action;
  4697. #define ADD_MODE(name, mode) \
  4698. action = menu->addAction(QTStr("" name), this, \
  4699. &OBSBasic::SetDeinterlacingMode); \
  4700. action->setProperty("mode", (int)mode); \
  4701. action->setCheckable(true); \
  4702. action->setChecked(deinterlaceMode == mode);
  4703. ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
  4704. ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
  4705. ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
  4706. ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
  4707. ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
  4708. ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
  4709. ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
  4710. ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
  4711. ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
  4712. #undef ADD_MODE
  4713. menu->addSeparator();
  4714. #define ADD_ORDER(name, order) \
  4715. action = menu->addAction(QTStr("Deinterlacing." name), this, \
  4716. &OBSBasic::SetDeinterlacingOrder); \
  4717. action->setProperty("order", (int)order); \
  4718. action->setCheckable(true); \
  4719. action->setChecked(deinterlaceOrder == order);
  4720. ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
  4721. ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
  4722. #undef ADD_ORDER
  4723. return menu;
  4724. }
  4725. void OBSBasic::SetScaleFilter()
  4726. {
  4727. QAction *action = reinterpret_cast<QAction *>(sender());
  4728. obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
  4729. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4730. obs_sceneitem_set_scale_filter(sceneItem, mode);
  4731. }
  4732. QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
  4733. {
  4734. obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
  4735. QAction *action;
  4736. #define ADD_MODE(name, mode) \
  4737. action = menu->addAction(QTStr("" name), this, \
  4738. &OBSBasic::SetScaleFilter); \
  4739. action->setProperty("mode", (int)mode); \
  4740. action->setCheckable(true); \
  4741. action->setChecked(scaleFilter == mode);
  4742. ADD_MODE("Disable", OBS_SCALE_DISABLE);
  4743. ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
  4744. ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
  4745. ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
  4746. ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
  4747. ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
  4748. #undef ADD_MODE
  4749. return menu;
  4750. }
  4751. void OBSBasic::SetBlendingMethod()
  4752. {
  4753. QAction *action = reinterpret_cast<QAction *>(sender());
  4754. obs_blending_method method =
  4755. (obs_blending_method)action->property("method").toInt();
  4756. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4757. obs_sceneitem_set_blending_method(sceneItem, method);
  4758. }
  4759. QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item)
  4760. {
  4761. obs_blending_method blendingMethod =
  4762. obs_sceneitem_get_blending_method(item);
  4763. QAction *action;
  4764. #define ADD_MODE(name, method) \
  4765. action = menu->addAction(QTStr("" name), this, \
  4766. &OBSBasic::SetBlendingMethod); \
  4767. action->setProperty("method", (int)method); \
  4768. action->setCheckable(true); \
  4769. action->setChecked(blendingMethod == method);
  4770. ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT);
  4771. ADD_MODE("BlendingMethod.SrgbOff", OBS_BLEND_METHOD_SRGB_OFF);
  4772. #undef ADD_MODE
  4773. return menu;
  4774. }
  4775. void OBSBasic::SetBlendingMode()
  4776. {
  4777. QAction *action = reinterpret_cast<QAction *>(sender());
  4778. obs_blending_type mode =
  4779. (obs_blending_type)action->property("mode").toInt();
  4780. OBSSceneItem sceneItem = GetCurrentSceneItem();
  4781. obs_sceneitem_set_blending_mode(sceneItem, mode);
  4782. }
  4783. QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item)
  4784. {
  4785. obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item);
  4786. QAction *action;
  4787. #define ADD_MODE(name, mode) \
  4788. action = menu->addAction(QTStr("" name), this, \
  4789. &OBSBasic::SetBlendingMode); \
  4790. action->setProperty("mode", (int)mode); \
  4791. action->setCheckable(true); \
  4792. action->setChecked(blendingMode == mode);
  4793. ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL);
  4794. ADD_MODE("BlendingMode.Additive", OBS_BLEND_ADDITIVE);
  4795. ADD_MODE("BlendingMode.Subtract", OBS_BLEND_SUBTRACT);
  4796. ADD_MODE("BlendingMode.Screen", OBS_BLEND_SCREEN);
  4797. ADD_MODE("BlendingMode.Multiply", OBS_BLEND_MULTIPLY);
  4798. ADD_MODE("BlendingMode.Lighten", OBS_BLEND_LIGHTEN);
  4799. ADD_MODE("BlendingMode.Darken", OBS_BLEND_DARKEN);
  4800. #undef ADD_MODE
  4801. return menu;
  4802. }
  4803. QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
  4804. QWidgetAction *widgetAction,
  4805. ColorSelect *select,
  4806. obs_sceneitem_t *item)
  4807. {
  4808. QAction *action;
  4809. menu->setStyleSheet(QString(
  4810. "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
  4811. "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
  4812. "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
  4813. "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
  4814. "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
  4815. "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
  4816. "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
  4817. "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));
  4818. obs_data_t *privData = obs_sceneitem_get_private_settings(item);
  4819. obs_data_release(privData);
  4820. obs_data_set_default_int(privData, "color-preset", 0);
  4821. int preset = obs_data_get_int(privData, "color-preset");
  4822. action = menu->addAction(QTStr("Clear"), this, &OBSBasic::ColorChange);
  4823. action->setCheckable(true);
  4824. action->setProperty("bgColor", 0);
  4825. action->setChecked(preset == 0);
  4826. action = menu->addAction(QTStr("CustomColor"), this,
  4827. &OBSBasic::ColorChange);
  4828. action->setCheckable(true);
  4829. action->setProperty("bgColor", 1);
  4830. action->setChecked(preset == 1);
  4831. menu->addSeparator();
  4832. widgetAction->setDefaultWidget(select);
  4833. for (int i = 1; i < 9; i++) {
  4834. stringstream button;
  4835. button << "preset" << i;
  4836. QPushButton *colorButton =
  4837. select->findChild<QPushButton *>(button.str().c_str());
  4838. if (preset == i + 1)
  4839. colorButton->setStyleSheet("border: 2px solid black");
  4840. colorButton->setProperty("bgColor", i);
  4841. select->connect(colorButton, &QPushButton::released, this,
  4842. &OBSBasic::ColorChange);
  4843. }
  4844. menu->addAction(widgetAction);
  4845. return menu;
  4846. }
  4847. ColorSelect::ColorSelect(QWidget *parent)
  4848. : QWidget(parent),
  4849. ui(new Ui::ColorSelect)
  4850. {
  4851. ui->setupUi(this);
  4852. }
  4853. void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
  4854. {
  4855. QMenu popup(this);
  4856. delete previewProjectorSource;
  4857. delete sourceProjector;
  4858. delete scaleFilteringMenu;
  4859. delete blendingMethodMenu;
  4860. delete blendingModeMenu;
  4861. delete colorMenu;
  4862. delete colorWidgetAction;
  4863. delete colorSelect;
  4864. delete deinterlaceMenu;
  4865. if (preview) {
  4866. QAction *action = popup.addAction(
  4867. QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
  4868. &OBSBasic::TogglePreview);
  4869. action->setCheckable(true);
  4870. action->setChecked(
  4871. obs_display_enabled(ui->preview->GetDisplay()));
  4872. if (IsPreviewProgramMode())
  4873. action->setEnabled(false);
  4874. popup.addAction(ui->actionLockPreview);
  4875. popup.addMenu(ui->scalingMenu);
  4876. previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
  4877. AddProjectorMenuMonitors(previewProjectorSource, this,
  4878. &OBSBasic::OpenPreviewProjector);
  4879. popup.addMenu(previewProjectorSource);
  4880. QAction *previewWindow =
  4881. popup.addAction(QTStr("PreviewWindow"), this,
  4882. &OBSBasic::OpenPreviewWindow);
  4883. popup.addAction(previewWindow);
  4884. popup.addAction(QTStr("Screenshot.Preview"), this,
  4885. &OBSBasic::ScreenshotScene);
  4886. popup.addSeparator();
  4887. }
  4888. QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
  4889. if (addSourceMenu)
  4890. popup.addMenu(addSourceMenu);
  4891. if (ui->sources->MultipleBaseSelected()) {
  4892. popup.addSeparator();
  4893. popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
  4894. &SourceTree::GroupSelectedItems);
  4895. } else if (ui->sources->GroupsSelected()) {
  4896. popup.addSeparator();
  4897. popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
  4898. &SourceTree::UngroupSelectedGroups);
  4899. }
  4900. popup.addSeparator();
  4901. popup.addAction(ui->actionCopySource);
  4902. popup.addAction(ui->actionPasteRef);
  4903. popup.addAction(ui->actionPasteDup);
  4904. popup.addSeparator();
  4905. popup.addSeparator();
  4906. popup.addAction(ui->actionCopyFilters);
  4907. popup.addAction(ui->actionPasteFilters);
  4908. popup.addSeparator();
  4909. if (idx != -1) {
  4910. if (addSourceMenu)
  4911. popup.addSeparator();
  4912. OBSSceneItem sceneItem = ui->sources->Get(idx);
  4913. obs_source_t *source = obs_sceneitem_get_source(sceneItem);
  4914. uint32_t flags = obs_source_get_output_flags(source);
  4915. bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
  4916. OBS_SOURCE_ASYNC_VIDEO;
  4917. bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
  4918. bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO;
  4919. colorMenu = new QMenu(QTStr("ChangeBG"));
  4920. colorWidgetAction = new QWidgetAction(colorMenu);
  4921. colorSelect = new ColorSelect(colorMenu);
  4922. popup.addMenu(AddBackgroundColorMenu(
  4923. colorMenu, colorWidgetAction, colorSelect, sceneItem));
  4924. popup.addAction(renameSource);
  4925. popup.addAction(ui->actionRemoveSource);
  4926. popup.addSeparator();
  4927. popup.addMenu(ui->orderMenu);
  4928. if (hasVideo)
  4929. popup.addMenu(ui->transformMenu);
  4930. popup.addSeparator();
  4931. if (hasAudio) {
  4932. QAction *actionHideMixer =
  4933. popup.addAction(QTStr("HideMixer"), this,
  4934. &OBSBasic::ToggleHideMixer);
  4935. actionHideMixer->setCheckable(true);
  4936. actionHideMixer->setChecked(SourceMixerHidden(source));
  4937. popup.addSeparator();
  4938. }
  4939. if (hasVideo) {
  4940. QAction *resizeOutput = popup.addAction(
  4941. QTStr("ResizeOutputSizeOfSource"), this,
  4942. &OBSBasic::ResizeOutputSizeOfSource);
  4943. int width = obs_source_get_width(source);
  4944. int height = obs_source_get_height(source);
  4945. resizeOutput->setEnabled(!obs_video_active());
  4946. if (width < 8 || height < 8)
  4947. resizeOutput->setEnabled(false);
  4948. scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
  4949. popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu,
  4950. sceneItem));
  4951. blendingModeMenu = new QMenu(QTStr("BlendingMode"));
  4952. popup.addMenu(AddBlendingModeMenu(blendingModeMenu,
  4953. sceneItem));
  4954. blendingMethodMenu = new QMenu(QTStr("BlendingMethod"));
  4955. popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu,
  4956. sceneItem));
  4957. if (isAsyncVideo) {
  4958. deinterlaceMenu =
  4959. new QMenu(QTStr("Deinterlacing"));
  4960. popup.addMenu(AddDeinterlacingMenu(
  4961. deinterlaceMenu, source));
  4962. }
  4963. popup.addSeparator();
  4964. popup.addMenu(CreateVisibilityTransitionMenu(true));
  4965. popup.addMenu(CreateVisibilityTransitionMenu(false));
  4966. popup.addSeparator();
  4967. sourceProjector = new QMenu(QTStr("SourceProjector"));
  4968. AddProjectorMenuMonitors(
  4969. sourceProjector, this,
  4970. &OBSBasic::OpenSourceProjector);
  4971. popup.addMenu(sourceProjector);
  4972. popup.addAction(QTStr("SourceWindow"), this,
  4973. &OBSBasic::OpenSourceWindow);
  4974. popup.addAction(QTStr("Screenshot.Source"), this,
  4975. &OBSBasic::ScreenshotSelectedSource);
  4976. }
  4977. popup.addSeparator();
  4978. if (flags & OBS_SOURCE_INTERACTION)
  4979. popup.addAction(QTStr("Interact"), this,
  4980. &OBSBasic::on_actionInteract_triggered);
  4981. popup.addAction(QTStr("Filters"), this,
  4982. [&]() { OpenFilters(); });
  4983. QAction *action = popup.addAction(
  4984. QTStr("Properties"), this,
  4985. &OBSBasic::on_actionSourceProperties_triggered);
  4986. action->setEnabled(obs_source_configurable(source));
  4987. }
  4988. popup.exec(QCursor::pos());
  4989. }
  4990. void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
  4991. {
  4992. if (ui->scenes->count()) {
  4993. QModelIndex idx = ui->sources->indexAt(pos);
  4994. CreateSourcePopupMenu(idx.row(), false);
  4995. }
  4996. }
  4997. void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
  4998. {
  4999. if (!witem)
  5000. return;
  5001. if (IsPreviewProgramMode()) {
  5002. bool doubleClickSwitch =
  5003. config_get_bool(App()->GlobalConfig(), "BasicWindow",
  5004. "TransitionOnDoubleClick");
  5005. if (doubleClickSwitch)
  5006. TransitionClicked();
  5007. }
  5008. }
  5009. static inline bool should_show_properties(obs_source_t *source, const char *id)
  5010. {
  5011. if (!source)
  5012. return false;
  5013. if (strcmp(id, "group") == 0)
  5014. return false;
  5015. if (!obs_source_configurable(source))
  5016. return false;
  5017. uint32_t caps = obs_source_get_output_flags(source);
  5018. if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0)
  5019. return false;
  5020. return true;
  5021. }
  5022. void OBSBasic::AddSource(const char *id)
  5023. {
  5024. if (id && *id) {
  5025. OBSBasicSourceSelect sourceSelect(this, id, undo_s);
  5026. sourceSelect.exec();
  5027. if (should_show_properties(sourceSelect.newSource, id)) {
  5028. CreatePropertiesWindow(sourceSelect.newSource);
  5029. }
  5030. }
  5031. }
  5032. QMenu *OBSBasic::CreateAddSourcePopupMenu()
  5033. {
  5034. const char *unversioned_type;
  5035. const char *type;
  5036. bool foundValues = false;
  5037. bool foundDeprecated = false;
  5038. size_t idx = 0;
  5039. QMenu *popup = new QMenu(QTStr("Add"), this);
  5040. QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
  5041. auto getActionAfter = [](QMenu *menu, const QString &name) {
  5042. QList<QAction *> actions = menu->actions();
  5043. for (QAction *menuAction : actions) {
  5044. if (menuAction->text().compare(
  5045. name, Qt::CaseInsensitive) >= 0)
  5046. return menuAction;
  5047. }
  5048. return (QAction *)nullptr;
  5049. };
  5050. auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
  5051. const char *name) {
  5052. QString qname = QT_UTF8(name);
  5053. QAction *popupItem = new QAction(qname, this);
  5054. connect(popupItem, &QAction::triggered,
  5055. [this, type]() { AddSource(type); });
  5056. QIcon icon;
  5057. if (strcmp(type, "scene") == 0)
  5058. icon = GetSceneIcon();
  5059. else
  5060. icon = GetSourceIcon(type);
  5061. popupItem->setIcon(icon);
  5062. QAction *after = getActionAfter(popup, qname);
  5063. popup->insertAction(after, popupItem);
  5064. };
  5065. while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
  5066. const char *name = obs_source_get_display_name(type);
  5067. uint32_t caps = obs_get_source_output_flags(type);
  5068. if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
  5069. continue;
  5070. if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
  5071. addSource(popup, unversioned_type, name);
  5072. } else {
  5073. addSource(deprecated, unversioned_type, name);
  5074. foundDeprecated = true;
  5075. }
  5076. foundValues = true;
  5077. }
  5078. addSource(popup, "scene", Str("Basic.Scene"));
  5079. popup->addSeparator();
  5080. QAction *addGroup = new QAction(QTStr("Group"), this);
  5081. addGroup->setIcon(GetGroupIcon());
  5082. connect(addGroup, &QAction::triggered,
  5083. [this]() { AddSource("group"); });
  5084. popup->addAction(addGroup);
  5085. if (!foundDeprecated) {
  5086. delete deprecated;
  5087. deprecated = nullptr;
  5088. }
  5089. if (!foundValues) {
  5090. delete popup;
  5091. popup = nullptr;
  5092. } else if (foundDeprecated) {
  5093. popup->addSeparator();
  5094. popup->addMenu(deprecated);
  5095. }
  5096. return popup;
  5097. }
  5098. void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
  5099. {
  5100. if (!GetCurrentScene()) {
  5101. // Tell the user he needs a scene first (help beginners).
  5102. OBSMessageBox::information(
  5103. this, QTStr("Basic.Main.AddSourceHelp.Title"),
  5104. QTStr("Basic.Main.AddSourceHelp.Text"));
  5105. return;
  5106. }
  5107. QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
  5108. if (popup)
  5109. popup->exec(pos);
  5110. }
  5111. void OBSBasic::on_actionAddSource_triggered()
  5112. {
  5113. AddSourcePopupMenu(QCursor::pos());
  5114. }
  5115. static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
  5116. {
  5117. vector<OBSSceneItem> &items =
  5118. *reinterpret_cast<vector<OBSSceneItem> *>(param);
  5119. if (obs_sceneitem_selected(item)) {
  5120. items.emplace_back(item);
  5121. } else if (obs_sceneitem_is_group(item)) {
  5122. obs_sceneitem_group_enum_items(item, remove_items, &items);
  5123. }
  5124. return true;
  5125. };
  5126. OBSData OBSBasic::BackupScene(obs_scene_t *scene,
  5127. std::vector<obs_source_t *> *sources)
  5128. {
  5129. OBSDataArrayAutoRelease undo_array = obs_data_array_create();
  5130. if (!sources) {
  5131. obs_scene_enum_items(scene, save_undo_source_enum, undo_array);
  5132. } else {
  5133. for (obs_source_t *source : *sources) {
  5134. obs_data_t *source_data = obs_save_source(source);
  5135. obs_data_array_push_back(undo_array, source_data);
  5136. obs_data_release(source_data);
  5137. }
  5138. }
  5139. OBSDataAutoRelease scene_data =
  5140. obs_save_source(obs_scene_get_source(scene));
  5141. obs_data_array_push_back(undo_array, scene_data);
  5142. OBSDataAutoRelease data = obs_data_create();
  5143. obs_data_set_array(data, "array", undo_array);
  5144. obs_data_get_json(data);
  5145. return data.Get();
  5146. }
  5147. static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p)
  5148. {
  5149. auto sources = static_cast<std::vector<OBSSource> *>(p);
  5150. sources->push_back(obs_sceneitem_get_source(item));
  5151. return true;
  5152. }
  5153. void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name,
  5154. OBSData undo_data, OBSData redo_data)
  5155. {
  5156. auto undo_redo = [this](const std::string &json) {
  5157. OBSDataAutoRelease base =
  5158. obs_data_create_from_json(json.c_str());
  5159. OBSDataArrayAutoRelease array =
  5160. obs_data_get_array(base, "array");
  5161. std::vector<OBSSource> sources;
  5162. std::vector<OBSSource> old_sources;
  5163. /* create missing sources */
  5164. const size_t count = obs_data_array_count(array);
  5165. sources.reserve(count);
  5166. for (size_t i = 0; i < count; i++) {
  5167. OBSDataAutoRelease data = obs_data_array_item(array, i);
  5168. const char *name = obs_data_get_string(data, "name");
  5169. OBSSourceAutoRelease source =
  5170. obs_get_source_by_name(name);
  5171. if (!source)
  5172. source = obs_load_source(data);
  5173. sources.push_back(source.Get());
  5174. /* update scene/group settings to restore their
  5175. * contents to their saved settings */
  5176. obs_scene_t *scene =
  5177. obs_group_or_scene_from_source(source);
  5178. if (scene) {
  5179. obs_scene_enum_items(scene, add_source_enum,
  5180. &old_sources);
  5181. OBSDataAutoRelease scene_settings =
  5182. obs_data_get_obj(data, "settings");
  5183. obs_source_update(source, scene_settings);
  5184. }
  5185. }
  5186. /* actually load sources now */
  5187. for (obs_source_t *source : sources)
  5188. obs_source_load2(source);
  5189. ui->sources->RefreshItems();
  5190. };
  5191. const char *undo_json = obs_data_get_last_json(undo_data);
  5192. const char *redo_json = obs_data_get_last_json(redo_data);
  5193. undo_s.add_action(action_name, undo_redo, undo_redo, undo_json,
  5194. redo_json);
  5195. }
  5196. void OBSBasic::on_actionRemoveSource_triggered()
  5197. {
  5198. vector<OBSSceneItem> items;
  5199. OBSScene scene = GetCurrentScene();
  5200. obs_source_t *scene_source = obs_scene_get_source(scene);
  5201. obs_scene_enum_items(scene, remove_items, &items);
  5202. if (!items.size())
  5203. return;
  5204. /* ------------------------------------- */
  5205. /* confirm action with user */
  5206. bool confirmed = false;
  5207. if (items.size() > 1) {
  5208. QString text = QTStr("ConfirmRemove.TextMultiple")
  5209. .arg(QString::number(items.size()));
  5210. QMessageBox remove_items(this);
  5211. remove_items.setText(text);
  5212. QPushButton *Yes = remove_items.addButton(QTStr("Yes"),
  5213. QMessageBox::YesRole);
  5214. remove_items.setDefaultButton(Yes);
  5215. remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
  5216. remove_items.setIcon(QMessageBox::Question);
  5217. remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
  5218. remove_items.exec();
  5219. confirmed = Yes == remove_items.clickedButton();
  5220. } else {
  5221. OBSSceneItem &item = items[0];
  5222. obs_source_t *source = obs_sceneitem_get_source(item);
  5223. if (source && QueryRemoveSource(source))
  5224. confirmed = true;
  5225. }
  5226. if (!confirmed)
  5227. return;
  5228. /* ----------------------------------------------- */
  5229. /* save undo data */
  5230. OBSData undo_data = BackupScene(scene_source);
  5231. /* ----------------------------------------------- */
  5232. /* remove items */
  5233. for (auto &item : items)
  5234. obs_sceneitem_remove(item);
  5235. /* ----------------------------------------------- */
  5236. /* save redo data */
  5237. OBSData redo_data = BackupScene(scene_source);
  5238. /* ----------------------------------------------- */
  5239. /* add undo/redo action */
  5240. QString action_name;
  5241. if (items.size() > 1) {
  5242. action_name = QTStr("Undo.Sources.Multi")
  5243. .arg(QString::number(items.size()));
  5244. } else {
  5245. QString str = QTStr("Undo.Delete");
  5246. action_name = str.arg(obs_source_get_name(
  5247. obs_sceneitem_get_source(items[0])));
  5248. }
  5249. CreateSceneUndoRedoAction(action_name, undo_data, redo_data);
  5250. }
  5251. void OBSBasic::on_actionInteract_triggered()
  5252. {
  5253. OBSSceneItem item = GetCurrentSceneItem();
  5254. OBSSource source = obs_sceneitem_get_source(item);
  5255. if (source)
  5256. CreateInteractionWindow(source);
  5257. }
  5258. void OBSBasic::on_actionSourceProperties_triggered()
  5259. {
  5260. OBSSceneItem item = GetCurrentSceneItem();
  5261. OBSSource source = obs_sceneitem_get_source(item);
  5262. if (source)
  5263. CreatePropertiesWindow(source);
  5264. }
  5265. void OBSBasic::MoveSceneItem(enum obs_order_movement movement,
  5266. const QString &action_name)
  5267. {
  5268. OBSSceneItem item = GetCurrentSceneItem();
  5269. obs_source_t *source = obs_sceneitem_get_source(item);
  5270. if (!source)
  5271. return;
  5272. OBSScene scene = GetCurrentScene();
  5273. std::vector<obs_source_t *> sources;
  5274. if (scene != obs_sceneitem_get_scene(item))
  5275. sources.push_back(
  5276. obs_scene_get_source(obs_sceneitem_get_scene(item)));
  5277. OBSData undo_data = BackupScene(scene, &sources);
  5278. obs_sceneitem_set_order(item, movement);
  5279. const char *source_name = obs_source_get_name(source);
  5280. const char *scene_name =
  5281. obs_source_get_name(obs_scene_get_source(scene));
  5282. OBSData redo_data = BackupScene(scene, &sources);
  5283. CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name),
  5284. undo_data, redo_data);
  5285. }
  5286. void OBSBasic::on_actionSourceUp_triggered()
  5287. {
  5288. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5289. }
  5290. void OBSBasic::on_actionSourceDown_triggered()
  5291. {
  5292. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5293. }
  5294. void OBSBasic::on_actionMoveUp_triggered()
  5295. {
  5296. MoveSceneItem(OBS_ORDER_MOVE_UP, QTStr("Undo.MoveUp"));
  5297. }
  5298. void OBSBasic::on_actionMoveDown_triggered()
  5299. {
  5300. MoveSceneItem(OBS_ORDER_MOVE_DOWN, QTStr("Undo.MoveDown"));
  5301. }
  5302. void OBSBasic::on_actionMoveToTop_triggered()
  5303. {
  5304. MoveSceneItem(OBS_ORDER_MOVE_TOP, QTStr("Undo.MoveToTop"));
  5305. }
  5306. void OBSBasic::on_actionMoveToBottom_triggered()
  5307. {
  5308. MoveSceneItem(OBS_ORDER_MOVE_BOTTOM, QTStr("Undo.MoveToBottom"));
  5309. }
  5310. static BPtr<char> ReadLogFile(const char *subdir, const char *log)
  5311. {
  5312. char logDir[512];
  5313. if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
  5314. return nullptr;
  5315. string path = logDir;
  5316. path += "/";
  5317. path += log;
  5318. BPtr<char> file = os_quick_read_utf8_file(path.c_str());
  5319. if (!file)
  5320. blog(LOG_WARNING, "Failed to read log file %s", path.c_str());
  5321. return file;
  5322. }
  5323. void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash)
  5324. {
  5325. BPtr<char> fileString{ReadLogFile(subdir, file)};
  5326. if (!fileString)
  5327. return;
  5328. if (!*fileString)
  5329. return;
  5330. ui->menuLogFiles->setEnabled(false);
  5331. #if defined(_WIN32)
  5332. ui->menuCrashLogs->setEnabled(false);
  5333. #endif
  5334. stringstream ss;
  5335. ss << "OBS " << App()->GetVersionString(false)
  5336. << " log file uploaded at " << CurrentDateTimeString() << "\n\n"
  5337. << fileString;
  5338. if (logUploadThread) {
  5339. logUploadThread->wait();
  5340. }
  5341. RemoteTextThread *thread = new RemoteTextThread(
  5342. "https://obsproject.com/logs/upload", "text/plain", ss.str());
  5343. logUploadThread.reset(thread);
  5344. if (crash) {
  5345. connect(thread, &RemoteTextThread::Result, this,
  5346. &OBSBasic::crashUploadFinished);
  5347. } else {
  5348. connect(thread, &RemoteTextThread::Result, this,
  5349. &OBSBasic::logUploadFinished);
  5350. }
  5351. logUploadThread->start();
  5352. }
  5353. void OBSBasic::on_actionShowLogs_triggered()
  5354. {
  5355. char logDir[512];
  5356. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
  5357. return;
  5358. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5359. QDesktopServices::openUrl(url);
  5360. }
  5361. void OBSBasic::on_actionUploadCurrentLog_triggered()
  5362. {
  5363. UploadLog("obs-studio/logs", App()->GetCurrentLog(), false);
  5364. }
  5365. void OBSBasic::on_actionUploadLastLog_triggered()
  5366. {
  5367. UploadLog("obs-studio/logs", App()->GetLastLog(), false);
  5368. }
  5369. void OBSBasic::on_actionViewCurrentLog_triggered()
  5370. {
  5371. if (!logView)
  5372. logView = new OBSLogViewer();
  5373. logView->show();
  5374. logView->setWindowState(
  5375. (logView->windowState() & ~Qt::WindowMinimized) |
  5376. Qt::WindowActive);
  5377. logView->activateWindow();
  5378. logView->raise();
  5379. }
  5380. void OBSBasic::on_actionShowCrashLogs_triggered()
  5381. {
  5382. char logDir[512];
  5383. if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
  5384. return;
  5385. QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
  5386. QDesktopServices::openUrl(url);
  5387. }
  5388. void OBSBasic::on_actionUploadLastCrashLog_triggered()
  5389. {
  5390. UploadLog("obs-studio/crashes", App()->GetLastCrashLog(), true);
  5391. }
  5392. void OBSBasic::on_actionCheckForUpdates_triggered()
  5393. {
  5394. CheckForUpdates(true);
  5395. }
  5396. void OBSBasic::on_actionRepair_triggered()
  5397. {
  5398. #if defined(_WIN32)
  5399. ui->actionCheckForUpdates->setEnabled(false);
  5400. ui->actionRepair->setEnabled(false);
  5401. if (updateCheckThread && updateCheckThread->isRunning())
  5402. return;
  5403. updateCheckThread.reset(new AutoUpdateThread(false, true));
  5404. updateCheckThread->start();
  5405. #endif
  5406. }
  5407. void OBSBasic::on_actionRestartSafe_triggered()
  5408. {
  5409. QMessageBox::StandardButton button = OBSMessageBox::question(
  5410. this, QTStr("Restart"),
  5411. safe_mode ? QTStr("SafeMode.RestartNormal")
  5412. : QTStr("SafeMode.Restart"));
  5413. if (button == QMessageBox::Yes) {
  5414. restart = safe_mode;
  5415. restart_safe = !safe_mode;
  5416. close();
  5417. }
  5418. }
  5419. void OBSBasic::logUploadFinished(const QString &text, const QString &error)
  5420. {
  5421. ui->menuLogFiles->setEnabled(true);
  5422. #if defined(_WIN32)
  5423. ui->menuCrashLogs->setEnabled(true);
  5424. #endif
  5425. if (text.isEmpty()) {
  5426. OBSMessageBox::critical(
  5427. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5428. error);
  5429. return;
  5430. }
  5431. openLogDialog(text, false);
  5432. }
  5433. void OBSBasic::crashUploadFinished(const QString &text, const QString &error)
  5434. {
  5435. ui->menuLogFiles->setEnabled(true);
  5436. #if defined(_WIN32)
  5437. ui->menuCrashLogs->setEnabled(true);
  5438. #endif
  5439. if (text.isEmpty()) {
  5440. OBSMessageBox::critical(
  5441. this, QTStr("LogReturnDialog.ErrorUploadingLog"),
  5442. error);
  5443. return;
  5444. }
  5445. openLogDialog(text, true);
  5446. }
  5447. void OBSBasic::openLogDialog(const QString &text, const bool crash)
  5448. {
  5449. OBSDataAutoRelease returnData =
  5450. obs_data_create_from_json(QT_TO_UTF8(text));
  5451. string resURL = obs_data_get_string(returnData, "url");
  5452. QString logURL = resURL.c_str();
  5453. OBSLogReply logDialog(this, logURL, crash);
  5454. logDialog.exec();
  5455. }
  5456. static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
  5457. obs_source_t *source, const string &name)
  5458. {
  5459. const char *prevName = obs_source_get_name(source);
  5460. if (name == prevName)
  5461. return;
  5462. OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str());
  5463. QListWidgetItem *listItem = listWidget->currentItem();
  5464. if (foundSource || name.empty()) {
  5465. listItem->setText(QT_UTF8(prevName));
  5466. if (foundSource) {
  5467. OBSMessageBox::warning(parent,
  5468. QTStr("NameExists.Title"),
  5469. QTStr("NameExists.Text"));
  5470. } else if (name.empty()) {
  5471. OBSMessageBox::warning(parent,
  5472. QTStr("NoNameEntered.Title"),
  5473. QTStr("NoNameEntered.Text"));
  5474. }
  5475. } else {
  5476. auto undo = [prev = std::string(prevName)](
  5477. const std::string &data) {
  5478. OBSSourceAutoRelease source =
  5479. obs_get_source_by_uuid(data.c_str());
  5480. obs_source_set_name(source, prev.c_str());
  5481. };
  5482. auto redo = [name](const std::string &data) {
  5483. OBSSourceAutoRelease source =
  5484. obs_get_source_by_uuid(data.c_str());
  5485. obs_source_set_name(source, name.c_str());
  5486. };
  5487. std::string source_uuid(obs_source_get_uuid(source));
  5488. parent->undo_s.add_action(
  5489. QTStr("Undo.Rename").arg(name.c_str()), undo, redo,
  5490. source_uuid, source_uuid);
  5491. listItem->setText(QT_UTF8(name.c_str()));
  5492. obs_source_set_name(source, name.c_str());
  5493. }
  5494. }
  5495. void OBSBasic::SceneNameEdited(QWidget *editor)
  5496. {
  5497. OBSScene scene = GetCurrentScene();
  5498. QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
  5499. string text = QT_TO_UTF8(edit->text().trimmed());
  5500. if (!scene)
  5501. return;
  5502. obs_source_t *source = obs_scene_get_source(scene);
  5503. RenameListItem(this, ui->scenes, source, text);
  5504. ui->scenesDock->addAction(renameScene);
  5505. if (api)
  5506. api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
  5507. }
  5508. void OBSBasic::OpenFilters(OBSSource source)
  5509. {
  5510. if (source == nullptr) {
  5511. OBSSceneItem item = GetCurrentSceneItem();
  5512. source = obs_sceneitem_get_source(item);
  5513. }
  5514. CreateFiltersWindow(source);
  5515. }
  5516. void OBSBasic::OpenProperties(OBSSource source)
  5517. {
  5518. if (source == nullptr) {
  5519. OBSSceneItem item = GetCurrentSceneItem();
  5520. source = obs_sceneitem_get_source(item);
  5521. }
  5522. CreatePropertiesWindow(source);
  5523. }
  5524. void OBSBasic::OpenInteraction(OBSSource source)
  5525. {
  5526. if (source == nullptr) {
  5527. OBSSceneItem item = GetCurrentSceneItem();
  5528. source = obs_sceneitem_get_source(item);
  5529. }
  5530. CreateInteractionWindow(source);
  5531. }
  5532. void OBSBasic::OpenEditTransform(OBSSceneItem item)
  5533. {
  5534. if (!item)
  5535. item = GetCurrentSceneItem();
  5536. if (!item)
  5537. return;
  5538. CreateEditTransformWindow(item);
  5539. }
  5540. void OBSBasic::OpenSceneFilters()
  5541. {
  5542. OBSScene scene = GetCurrentScene();
  5543. OBSSource source = obs_scene_get_source(scene);
  5544. CreateFiltersWindow(source);
  5545. }
  5546. #define RECORDING_START \
  5547. "==== Recording Start ==============================================="
  5548. #define RECORDING_STOP \
  5549. "==== Recording Stop ================================================"
  5550. #define REPLAY_BUFFER_START \
  5551. "==== Replay Buffer Start ==========================================="
  5552. #define REPLAY_BUFFER_STOP \
  5553. "==== Replay Buffer Stop ============================================"
  5554. #define STREAMING_START \
  5555. "==== Streaming Start ==============================================="
  5556. #define STREAMING_STOP \
  5557. "==== Streaming Stop ================================================"
  5558. #define VIRTUAL_CAM_START \
  5559. "==== Virtual Camera Start =========================================="
  5560. #define VIRTUAL_CAM_STOP \
  5561. "==== Virtual Camera Stop ==========================================="
  5562. void OBSBasic::DisplayStreamStartError()
  5563. {
  5564. QString message = !outputHandler->lastError.empty()
  5565. ? QTStr(outputHandler->lastError.c_str())
  5566. : QTStr("Output.StartFailedGeneric");
  5567. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  5568. ui->streamButton->setEnabled(true);
  5569. ui->streamButton->setChecked(false);
  5570. if (sysTrayStream) {
  5571. sysTrayStream->setText(ui->streamButton->text());
  5572. sysTrayStream->setEnabled(true);
  5573. }
  5574. QMessageBox::critical(this, QTStr("Output.StartStreamFailed"), message);
  5575. }
  5576. #ifdef YOUTUBE_ENABLED
  5577. void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id,
  5578. const QString &stream_id,
  5579. const QString &key, bool autostart,
  5580. bool autostop, bool start_now)
  5581. {
  5582. //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key));
  5583. obs_service_t *service_obj = GetService();
  5584. OBSDataAutoRelease settings = obs_service_get_settings(service_obj);
  5585. const std::string a_key = QT_TO_UTF8(key);
  5586. obs_data_set_string(settings, "key", a_key.c_str());
  5587. const std::string b_id = QT_TO_UTF8(broadcast_id);
  5588. obs_data_set_string(settings, "broadcast_id", b_id.c_str());
  5589. const std::string s_id = QT_TO_UTF8(stream_id);
  5590. obs_data_set_string(settings, "stream_id", s_id.c_str());
  5591. obs_service_update(service_obj, settings);
  5592. autoStartBroadcast = autostart;
  5593. autoStopBroadcast = autostop;
  5594. broadcastReady = true;
  5595. if (start_now)
  5596. QMetaObject::invokeMethod(this, "StartStreaming");
  5597. }
  5598. void OBSBasic::YoutubeStreamCheck(const std::string &key)
  5599. {
  5600. YoutubeApiWrappers *apiYouTube(
  5601. dynamic_cast<YoutubeApiWrappers *>(GetAuth()));
  5602. if (!apiYouTube) {
  5603. /* technically we should never get here -Lain */
  5604. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5605. Qt::QueuedConnection);
  5606. youtubeStreamCheckThread->deleteLater();
  5607. blog(LOG_ERROR, "==========================================");
  5608. blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__);
  5609. blog(LOG_ERROR, "==========================================");
  5610. return;
  5611. }
  5612. int timeout = 0;
  5613. json11::Json json;
  5614. QString id = key.c_str();
  5615. while (StreamingActive()) {
  5616. if (timeout == 14) {
  5617. QMetaObject::invokeMethod(this, "ForceStopStreaming",
  5618. Qt::QueuedConnection);
  5619. break;
  5620. }
  5621. if (!apiYouTube->FindStream(id, json)) {
  5622. QMetaObject::invokeMethod(this,
  5623. "DisplayStreamStartError",
  5624. Qt::QueuedConnection);
  5625. QMetaObject::invokeMethod(this, "StopStreaming",
  5626. Qt::QueuedConnection);
  5627. break;
  5628. }
  5629. auto item = json["items"][0];
  5630. auto status = item["status"]["streamStatus"].string_value();
  5631. if (status == "active") {
  5632. QMetaObject::invokeMethod(ui->broadcastButton,
  5633. "setEnabled",
  5634. Q_ARG(bool, true));
  5635. break;
  5636. } else {
  5637. QThread::sleep(1);
  5638. timeout++;
  5639. }
  5640. }
  5641. youtubeStreamCheckThread->deleteLater();
  5642. }
  5643. void OBSBasic::ShowYouTubeAutoStartWarning()
  5644. {
  5645. auto msgBox = []() {
  5646. QMessageBox msgbox(App()->GetMainWindow());
  5647. msgbox.setWindowTitle(QTStr(
  5648. "YouTube.Actions.AutoStartStreamingWarning.Title"));
  5649. msgbox.setText(
  5650. QTStr("YouTube.Actions.AutoStartStreamingWarning"));
  5651. msgbox.setIcon(QMessageBox::Icon::Information);
  5652. msgbox.addButton(QMessageBox::Ok);
  5653. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  5654. msgbox.setCheckBox(cb);
  5655. msgbox.exec();
  5656. if (cb->isChecked()) {
  5657. config_set_bool(App()->GlobalConfig(), "General",
  5658. "WarnedAboutYouTubeAutoStart", true);
  5659. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  5660. }
  5661. };
  5662. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  5663. "WarnedAboutYouTubeAutoStart");
  5664. if (!warned) {
  5665. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  5666. Q_ARG(VoidFunc, msgBox));
  5667. }
  5668. }
  5669. #endif
  5670. void OBSBasic::StartStreaming()
  5671. {
  5672. if (outputHandler->StreamingActive())
  5673. return;
  5674. if (disableOutputsRef)
  5675. return;
  5676. if (auth && auth->broadcastFlow()) {
  5677. if (!broadcastActive && !broadcastReady) {
  5678. ui->streamButton->setChecked(false);
  5679. QMessageBox no_broadcast(this);
  5680. no_broadcast.setText(QTStr("Output.NoBroadcast.Text"));
  5681. QPushButton *SetupBroadcast = no_broadcast.addButton(
  5682. QTStr("Basic.Main.SetupBroadcast"),
  5683. QMessageBox::YesRole);
  5684. no_broadcast.setDefaultButton(SetupBroadcast);
  5685. no_broadcast.addButton(QTStr("Close"),
  5686. QMessageBox::NoRole);
  5687. no_broadcast.setIcon(QMessageBox::Information);
  5688. no_broadcast.setWindowTitle(
  5689. QTStr("Output.NoBroadcast.Title"));
  5690. no_broadcast.exec();
  5691. if (no_broadcast.clickedButton() == SetupBroadcast)
  5692. QMetaObject::invokeMethod(this,
  5693. "SetupBroadcast");
  5694. return;
  5695. }
  5696. }
  5697. if (!outputHandler->SetupStreaming(service)) {
  5698. DisplayStreamStartError();
  5699. return;
  5700. }
  5701. if (api)
  5702. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);
  5703. SaveProject();
  5704. ui->streamButton->setEnabled(false);
  5705. ui->streamButton->setChecked(false);
  5706. ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
  5707. ui->broadcastButton->setChecked(false);
  5708. if (sysTrayStream) {
  5709. sysTrayStream->setEnabled(false);
  5710. sysTrayStream->setText(ui->streamButton->text());
  5711. }
  5712. if (!outputHandler->StartStreaming(service)) {
  5713. DisplayStreamStartError();
  5714. return;
  5715. }
  5716. if (!autoStartBroadcast) {
  5717. ui->broadcastButton->setText(
  5718. QTStr("Basic.Main.StartBroadcast"));
  5719. ui->broadcastButton->setProperty("broadcastState", "ready");
  5720. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5721. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5722. // well, we need to disable button while stream is not active
  5723. ui->broadcastButton->setEnabled(false);
  5724. } else {
  5725. if (!autoStopBroadcast) {
  5726. ui->broadcastButton->setText(
  5727. QTStr("Basic.Main.StopBroadcast"));
  5728. } else {
  5729. ui->broadcastButton->setText(
  5730. QTStr("Basic.Main.AutoStopEnabled"));
  5731. ui->broadcastButton->setEnabled(false);
  5732. }
  5733. ui->broadcastButton->setProperty("broadcastState", "active");
  5734. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5735. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5736. broadcastActive = true;
  5737. }
  5738. bool recordWhenStreaming = config_get_bool(
  5739. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5740. if (recordWhenStreaming)
  5741. StartRecording();
  5742. bool replayBufferWhileStreaming = config_get_bool(
  5743. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5744. if (replayBufferWhileStreaming)
  5745. StartReplayBuffer();
  5746. #ifdef YOUTUBE_ENABLED
  5747. if (!autoStartBroadcast)
  5748. OBSBasic::ShowYouTubeAutoStartWarning();
  5749. #endif
  5750. }
  5751. void OBSBasic::BroadcastButtonClicked()
  5752. {
  5753. if (!broadcastReady ||
  5754. (!broadcastActive && !outputHandler->StreamingActive())) {
  5755. SetupBroadcast();
  5756. if (broadcastReady)
  5757. ui->broadcastButton->setChecked(true);
  5758. return;
  5759. }
  5760. if (!autoStartBroadcast) {
  5761. #ifdef YOUTUBE_ENABLED
  5762. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5763. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5764. if (ytAuth.get()) {
  5765. if (!ytAuth->StartLatestBroadcast()) {
  5766. auto last_error = ytAuth->GetLastError();
  5767. if (last_error.isEmpty())
  5768. last_error = QTStr(
  5769. "YouTube.Actions.Error.YouTubeApi");
  5770. if (!ytAuth->GetTranslatedError(last_error))
  5771. last_error =
  5772. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5773. .arg(last_error,
  5774. ytAuth->GetBroadcastId());
  5775. OBSMessageBox::warning(
  5776. this,
  5777. QTStr("Output.BroadcastStartFailed"),
  5778. last_error, true);
  5779. ui->broadcastButton->setChecked(false);
  5780. return;
  5781. }
  5782. }
  5783. #endif
  5784. broadcastActive = true;
  5785. autoStartBroadcast = true; // and clear the flag
  5786. if (!autoStopBroadcast) {
  5787. ui->broadcastButton->setText(
  5788. QTStr("Basic.Main.StopBroadcast"));
  5789. } else {
  5790. ui->broadcastButton->setText(
  5791. QTStr("Basic.Main.AutoStopEnabled"));
  5792. ui->broadcastButton->setEnabled(false);
  5793. }
  5794. ui->broadcastButton->setProperty("broadcastState", "active");
  5795. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5796. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5797. } else if (!autoStopBroadcast) {
  5798. #ifdef YOUTUBE_ENABLED
  5799. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  5800. "WarnBeforeStoppingStream");
  5801. if (confirm && isVisible()) {
  5802. QMessageBox::StandardButton button = OBSMessageBox::question(
  5803. this, QTStr("ConfirmStop.Title"),
  5804. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  5805. QMessageBox::Yes | QMessageBox::No,
  5806. QMessageBox::No);
  5807. if (button == QMessageBox::No) {
  5808. ui->broadcastButton->setChecked(true);
  5809. return;
  5810. }
  5811. }
  5812. std::shared_ptr<YoutubeApiWrappers> ytAuth =
  5813. dynamic_pointer_cast<YoutubeApiWrappers>(auth);
  5814. if (ytAuth.get()) {
  5815. if (!ytAuth->StopLatestBroadcast()) {
  5816. auto last_error = ytAuth->GetLastError();
  5817. if (last_error.isEmpty())
  5818. last_error = QTStr(
  5819. "YouTube.Actions.Error.YouTubeApi");
  5820. if (!ytAuth->GetTranslatedError(last_error))
  5821. last_error =
  5822. QTStr("YouTube.Actions.Error.BroadcastTransitionFailed")
  5823. .arg(last_error,
  5824. ytAuth->GetBroadcastId());
  5825. OBSMessageBox::warning(
  5826. this,
  5827. QTStr("Output.BroadcastStopFailed"),
  5828. last_error, true);
  5829. }
  5830. }
  5831. #endif
  5832. broadcastActive = false;
  5833. broadcastReady = false;
  5834. autoStopBroadcast = true;
  5835. QMetaObject::invokeMethod(this, "StopStreaming");
  5836. SetBroadcastFlowEnabled(true);
  5837. }
  5838. }
  5839. void OBSBasic::SetBroadcastFlowEnabled(bool enabled)
  5840. {
  5841. ui->broadcastButton->setEnabled(enabled);
  5842. ui->broadcastButton->setVisible(enabled);
  5843. ui->broadcastButton->setChecked(broadcastReady);
  5844. ui->broadcastButton->setProperty("broadcastState", "idle");
  5845. ui->broadcastButton->style()->unpolish(ui->broadcastButton);
  5846. ui->broadcastButton->style()->polish(ui->broadcastButton);
  5847. ui->broadcastButton->setText(QTStr("Basic.Main.SetupBroadcast"));
  5848. }
  5849. void OBSBasic::SetupBroadcast()
  5850. {
  5851. #ifdef YOUTUBE_ENABLED
  5852. Auth *const auth = GetAuth();
  5853. if (IsYouTubeService(auth->service())) {
  5854. OBSYoutubeActions dialog(this, auth, broadcastReady);
  5855. connect(&dialog, &OBSYoutubeActions::ok, this,
  5856. &OBSBasic::YouTubeActionDialogOk);
  5857. int result = dialog.Valid() ? dialog.exec() : QDialog::Rejected;
  5858. if (result != QDialog::Accepted) {
  5859. if (!broadcastReady)
  5860. ui->broadcastButton->setChecked(false);
  5861. }
  5862. }
  5863. #endif
  5864. }
  5865. #ifdef _WIN32
  5866. static inline void UpdateProcessPriority()
  5867. {
  5868. const char *priority = config_get_string(App()->GlobalConfig(),
  5869. "General", "ProcessPriority");
  5870. if (priority && strcmp(priority, "Normal") != 0)
  5871. SetProcessPriority(priority);
  5872. }
  5873. static inline void ClearProcessPriority()
  5874. {
  5875. const char *priority = config_get_string(App()->GlobalConfig(),
  5876. "General", "ProcessPriority");
  5877. if (priority && strcmp(priority, "Normal") != 0)
  5878. SetProcessPriority("Normal");
  5879. }
  5880. #else
  5881. #define UpdateProcessPriority() \
  5882. do { \
  5883. } while (false)
  5884. #define ClearProcessPriority() \
  5885. do { \
  5886. } while (false)
  5887. #endif
  5888. inline void OBSBasic::OnActivate(bool force)
  5889. {
  5890. if (ui->profileMenu->isEnabled() || force) {
  5891. ui->profileMenu->setEnabled(false);
  5892. ui->autoConfigure->setEnabled(false);
  5893. App()->IncrementSleepInhibition();
  5894. UpdateProcessPriority();
  5895. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5896. if (trayIcon && trayIcon->isVisible()) {
  5897. #ifdef __APPLE__
  5898. QIcon trayMask =
  5899. QIcon(":/res/images/tray_active_macos.svg");
  5900. trayMask.setIsMask(true);
  5901. trayIcon->setIcon(
  5902. QIcon::fromTheme("obs-tray", trayMask));
  5903. #else
  5904. trayIcon->setIcon(QIcon::fromTheme(
  5905. "obs-tray-active",
  5906. QIcon(":/res/images/tray_active.png")));
  5907. #endif
  5908. }
  5909. }
  5910. }
  5911. extern volatile bool recording_paused;
  5912. extern volatile bool replaybuf_active;
  5913. inline void OBSBasic::OnDeactivate()
  5914. {
  5915. if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
  5916. ui->profileMenu->setEnabled(true);
  5917. ui->autoConfigure->setEnabled(true);
  5918. App()->DecrementSleepInhibition();
  5919. ClearProcessPriority();
  5920. TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive);
  5921. if (trayIcon && trayIcon->isVisible()) {
  5922. #ifdef __APPLE__
  5923. QIcon trayIconFile =
  5924. QIcon(":/res/images/obs_macos.svg");
  5925. trayIconFile.setIsMask(true);
  5926. #else
  5927. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  5928. #endif
  5929. trayIcon->setIcon(
  5930. QIcon::fromTheme("obs-tray", trayIconFile));
  5931. }
  5932. } else if (outputHandler->Active() && trayIcon &&
  5933. trayIcon->isVisible()) {
  5934. if (os_atomic_load_bool(&recording_paused)) {
  5935. #ifdef __APPLE__
  5936. QIcon trayIconFile =
  5937. QIcon(":/res/images/obs_paused_macos.svg");
  5938. trayIconFile.setIsMask(true);
  5939. #else
  5940. QIcon trayIconFile =
  5941. QIcon(":/res/images/obs_paused.png");
  5942. #endif
  5943. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  5944. trayIconFile));
  5945. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  5946. } else {
  5947. #ifdef __APPLE__
  5948. QIcon trayIconFile =
  5949. QIcon(":/res/images/tray_active_macos.svg");
  5950. trayIconFile.setIsMask(true);
  5951. #else
  5952. QIcon trayIconFile =
  5953. QIcon(":/res/images/tray_active.png");
  5954. #endif
  5955. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  5956. trayIconFile));
  5957. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  5958. }
  5959. }
  5960. }
  5961. void OBSBasic::StopStreaming()
  5962. {
  5963. SaveProject();
  5964. if (outputHandler->StreamingActive())
  5965. outputHandler->StopStreaming(streamingStopping);
  5966. // special case: force reset broadcast state if
  5967. // no autostart and no autostop selected
  5968. if (!autoStartBroadcast && !broadcastActive) {
  5969. broadcastActive = false;
  5970. autoStartBroadcast = true;
  5971. autoStopBroadcast = true;
  5972. broadcastReady = false;
  5973. }
  5974. if (autoStopBroadcast) {
  5975. broadcastActive = false;
  5976. broadcastReady = false;
  5977. }
  5978. OnDeactivate();
  5979. bool recordWhenStreaming = config_get_bool(
  5980. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  5981. bool keepRecordingWhenStreamStops =
  5982. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5983. "KeepRecordingWhenStreamStops");
  5984. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  5985. StopRecording();
  5986. bool replayBufferWhileStreaming = config_get_bool(
  5987. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  5988. bool keepReplayBufferStreamStops =
  5989. config_get_bool(GetGlobalConfig(), "BasicWindow",
  5990. "KeepReplayBufferStreamStops");
  5991. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  5992. StopReplayBuffer();
  5993. }
  5994. void OBSBasic::ForceStopStreaming()
  5995. {
  5996. SaveProject();
  5997. if (outputHandler->StreamingActive())
  5998. outputHandler->StopStreaming(true);
  5999. // special case: force reset broadcast state if
  6000. // no autostart and no autostop selected
  6001. if (!autoStartBroadcast && !broadcastActive) {
  6002. broadcastActive = false;
  6003. autoStartBroadcast = true;
  6004. autoStopBroadcast = true;
  6005. broadcastReady = false;
  6006. }
  6007. if (autoStopBroadcast) {
  6008. broadcastActive = false;
  6009. broadcastReady = false;
  6010. }
  6011. OnDeactivate();
  6012. bool recordWhenStreaming = config_get_bool(
  6013. GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
  6014. bool keepRecordingWhenStreamStops =
  6015. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6016. "KeepRecordingWhenStreamStops");
  6017. if (recordWhenStreaming && !keepRecordingWhenStreamStops)
  6018. StopRecording();
  6019. bool replayBufferWhileStreaming = config_get_bool(
  6020. GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
  6021. bool keepReplayBufferStreamStops =
  6022. config_get_bool(GetGlobalConfig(), "BasicWindow",
  6023. "KeepReplayBufferStreamStops");
  6024. if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
  6025. StopReplayBuffer();
  6026. }
  6027. void OBSBasic::StreamDelayStarting(int sec)
  6028. {
  6029. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6030. ui->streamButton->setEnabled(true);
  6031. ui->streamButton->setChecked(true);
  6032. if (sysTrayStream) {
  6033. sysTrayStream->setText(ui->streamButton->text());
  6034. sysTrayStream->setEnabled(true);
  6035. }
  6036. if (!startStreamMenu.isNull())
  6037. startStreamMenu->deleteLater();
  6038. startStreamMenu = new QMenu();
  6039. startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
  6040. &OBSBasic::StopStreaming);
  6041. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6042. &OBSBasic::ForceStopStreaming);
  6043. ui->streamButton->setMenu(startStreamMenu);
  6044. ui->statusbar->StreamDelayStarting(sec);
  6045. OnActivate();
  6046. }
  6047. void OBSBasic::StreamDelayStopping(int sec)
  6048. {
  6049. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6050. ui->streamButton->setEnabled(true);
  6051. ui->streamButton->setChecked(false);
  6052. if (sysTrayStream) {
  6053. sysTrayStream->setText(ui->streamButton->text());
  6054. sysTrayStream->setEnabled(true);
  6055. }
  6056. if (!startStreamMenu.isNull())
  6057. startStreamMenu->deleteLater();
  6058. startStreamMenu = new QMenu();
  6059. startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
  6060. &OBSBasic::StartStreaming);
  6061. startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
  6062. &OBSBasic::ForceStopStreaming);
  6063. ui->streamButton->setMenu(startStreamMenu);
  6064. ui->statusbar->StreamDelayStopping(sec);
  6065. if (api)
  6066. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6067. }
  6068. void OBSBasic::StreamingStart()
  6069. {
  6070. ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
  6071. ui->streamButton->setEnabled(true);
  6072. ui->streamButton->setChecked(true);
  6073. ui->statusbar->StreamStarted(outputHandler->streamOutput);
  6074. if (sysTrayStream) {
  6075. sysTrayStream->setText(ui->streamButton->text());
  6076. sysTrayStream->setEnabled(true);
  6077. }
  6078. #ifdef YOUTUBE_ENABLED
  6079. if (!autoStartBroadcast) {
  6080. // get a current stream key
  6081. obs_service_t *service_obj = GetService();
  6082. OBSDataAutoRelease settings =
  6083. obs_service_get_settings(service_obj);
  6084. std::string key = obs_data_get_string(settings, "stream_id");
  6085. if (!key.empty() && !youtubeStreamCheckThread) {
  6086. youtubeStreamCheckThread = CreateQThread(
  6087. [this, key] { YoutubeStreamCheck(key); });
  6088. youtubeStreamCheckThread->setObjectName(
  6089. "YouTubeStreamCheckThread");
  6090. youtubeStreamCheckThread->start();
  6091. }
  6092. }
  6093. #endif
  6094. if (api)
  6095. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);
  6096. OnActivate();
  6097. #ifdef YOUTUBE_ENABLED
  6098. if (YouTubeAppDock::IsYTServiceSelected())
  6099. youtubeAppDock->IngestionStarted();
  6100. #endif
  6101. blog(LOG_INFO, STREAMING_START);
  6102. }
  6103. void OBSBasic::StreamStopping()
  6104. {
  6105. ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
  6106. if (sysTrayStream)
  6107. sysTrayStream->setText(ui->streamButton->text());
  6108. streamingStopping = true;
  6109. if (api)
  6110. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
  6111. }
  6112. void OBSBasic::StreamingStop(int code, QString last_error)
  6113. {
  6114. const char *errorDescription = "";
  6115. DStr errorMessage;
  6116. bool use_last_error = false;
  6117. bool encode_error = false;
  6118. switch (code) {
  6119. case OBS_OUTPUT_BAD_PATH:
  6120. errorDescription = Str("Output.ConnectFail.BadPath");
  6121. break;
  6122. case OBS_OUTPUT_CONNECT_FAILED:
  6123. use_last_error = true;
  6124. errorDescription = Str("Output.ConnectFail.ConnectFailed");
  6125. break;
  6126. case OBS_OUTPUT_INVALID_STREAM:
  6127. errorDescription = Str("Output.ConnectFail.InvalidStream");
  6128. break;
  6129. case OBS_OUTPUT_ENCODE_ERROR:
  6130. encode_error = true;
  6131. break;
  6132. case OBS_OUTPUT_HDR_DISABLED:
  6133. errorDescription = Str("Output.ConnectFail.HdrDisabled");
  6134. break;
  6135. default:
  6136. case OBS_OUTPUT_ERROR:
  6137. use_last_error = true;
  6138. errorDescription = Str("Output.ConnectFail.Error");
  6139. break;
  6140. case OBS_OUTPUT_DISCONNECTED:
  6141. /* doesn't happen if output is set to reconnect. note that
  6142. * reconnects are handled in the output, not in the UI */
  6143. use_last_error = true;
  6144. errorDescription = Str("Output.ConnectFail.Disconnected");
  6145. }
  6146. if (use_last_error && !last_error.isEmpty())
  6147. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6148. QT_TO_UTF8(last_error));
  6149. else
  6150. dstr_copy(errorMessage, errorDescription);
  6151. ui->statusbar->StreamStopped();
  6152. ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
  6153. ui->streamButton->setEnabled(true);
  6154. ui->streamButton->setChecked(false);
  6155. if (sysTrayStream) {
  6156. sysTrayStream->setText(ui->streamButton->text());
  6157. sysTrayStream->setEnabled(true);
  6158. }
  6159. streamingStopping = false;
  6160. if (api)
  6161. api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);
  6162. OnDeactivate();
  6163. #ifdef YOUTUBE_ENABLED
  6164. if (YouTubeAppDock::IsYTServiceSelected())
  6165. youtubeAppDock->IngestionStopped();
  6166. #endif
  6167. blog(LOG_INFO, STREAMING_STOP);
  6168. if (encode_error) {
  6169. QString msg =
  6170. last_error.isEmpty()
  6171. ? QTStr("Output.StreamEncodeError.Msg")
  6172. : QTStr("Output.StreamEncodeError.Msg.LastError")
  6173. .arg(last_error);
  6174. OBSMessageBox::information(
  6175. this, QTStr("Output.StreamEncodeError.Title"), msg);
  6176. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6177. OBSMessageBox::information(this,
  6178. QTStr("Output.ConnectFail.Title"),
  6179. QT_UTF8(errorMessage));
  6180. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6181. SysTrayNotify(QT_UTF8(errorDescription),
  6182. QSystemTrayIcon::Warning);
  6183. }
  6184. if (!startStreamMenu.isNull()) {
  6185. ui->streamButton->setMenu(nullptr);
  6186. startStreamMenu->deleteLater();
  6187. startStreamMenu = nullptr;
  6188. }
  6189. // Reset broadcast button state/text
  6190. if (!broadcastActive)
  6191. SetBroadcastFlowEnabled(auth && auth->broadcastFlow());
  6192. }
  6193. void OBSBasic::AutoRemux(QString input, bool no_show)
  6194. {
  6195. auto config = Config();
  6196. bool autoRemux = config_get_bool(config, "Video", "AutoRemux");
  6197. if (!autoRemux)
  6198. return;
  6199. bool isSimpleMode = false;
  6200. const char *mode = config_get_string(config, "Output", "Mode");
  6201. if (!mode) {
  6202. isSimpleMode = true;
  6203. } else {
  6204. isSimpleMode = strcmp(mode, "Simple") == 0;
  6205. }
  6206. if (!isSimpleMode) {
  6207. const char *recType =
  6208. config_get_string(config, "AdvOut", "RecType");
  6209. bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0;
  6210. if (ffmpegOutput)
  6211. return;
  6212. }
  6213. if (input.isEmpty())
  6214. return;
  6215. QFileInfo fi(input);
  6216. QString suffix = fi.suffix();
  6217. /* do not remux if lossless */
  6218. if (suffix.compare("avi", Qt::CaseInsensitive) == 0) {
  6219. return;
  6220. }
  6221. QString path = fi.path();
  6222. QString output = input;
  6223. output.resize(output.size() - suffix.size());
  6224. const obs_encoder_t *videoEncoder =
  6225. obs_output_get_video_encoder(outputHandler->fileOutput);
  6226. const obs_encoder_t *audioEncoder =
  6227. obs_output_get_audio_encoder(outputHandler->fileOutput, 0);
  6228. const char *vCodecName = obs_encoder_get_codec(videoEncoder);
  6229. const char *aCodecName = obs_encoder_get_codec(audioEncoder);
  6230. const char *format = config_get_string(
  6231. config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2");
  6232. bool audio_is_pcm = strncmp(aCodecName, "pcm", 3) == 0;
  6233. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6234. /* FFmpeg <= 6.0 cannot remux AV1+PCM into any supported format. */
  6235. if (audio_is_pcm && strcmp(vCodecName, "av1") == 0)
  6236. return;
  6237. #endif
  6238. /* Retain original container for fMP4/fMOV */
  6239. if (strncmp(format, "fragmented", 10) == 0) {
  6240. output += "remuxed." + suffix;
  6241. } else if (strcmp(vCodecName, "prores") == 0) {
  6242. output += "mov";
  6243. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(60, 5, 100)
  6244. } else if (audio_is_pcm) {
  6245. output += "mov";
  6246. #endif
  6247. } else {
  6248. output += "mp4";
  6249. }
  6250. OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true);
  6251. if (!no_show)
  6252. remux->show();
  6253. remux->AutoRemux(input, output);
  6254. }
  6255. void OBSBasic::StartRecording()
  6256. {
  6257. if (outputHandler->RecordingActive())
  6258. return;
  6259. if (disableOutputsRef)
  6260. return;
  6261. if (!OutputPathValid()) {
  6262. OutputPathInvalidMessage();
  6263. ui->recordButton->setChecked(false);
  6264. return;
  6265. }
  6266. if (LowDiskSpace()) {
  6267. DiskSpaceMessage();
  6268. ui->recordButton->setChecked(false);
  6269. return;
  6270. }
  6271. if (api)
  6272. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);
  6273. SaveProject();
  6274. if (!outputHandler->StartRecording())
  6275. ui->recordButton->setChecked(false);
  6276. }
  6277. void OBSBasic::RecordStopping()
  6278. {
  6279. ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
  6280. if (sysTrayRecord)
  6281. sysTrayRecord->setText(ui->recordButton->text());
  6282. recordingStopping = true;
  6283. if (api)
  6284. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
  6285. }
  6286. void OBSBasic::StopRecording()
  6287. {
  6288. SaveProject();
  6289. if (outputHandler->RecordingActive())
  6290. outputHandler->StopRecording(recordingStopping);
  6291. OnDeactivate();
  6292. }
  6293. void OBSBasic::RecordingStart()
  6294. {
  6295. ui->statusbar->RecordingStarted(outputHandler->fileOutput);
  6296. ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
  6297. ui->recordButton->setChecked(true);
  6298. if (sysTrayRecord)
  6299. sysTrayRecord->setText(ui->recordButton->text());
  6300. recordingStopping = false;
  6301. if (api)
  6302. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);
  6303. if (!diskFullTimer->isActive())
  6304. diskFullTimer->start(1000);
  6305. OnActivate();
  6306. UpdatePause();
  6307. blog(LOG_INFO, RECORDING_START);
  6308. }
  6309. void OBSBasic::RecordingStop(int code, QString last_error)
  6310. {
  6311. ui->statusbar->RecordingStopped();
  6312. ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
  6313. ui->recordButton->setChecked(false);
  6314. if (sysTrayRecord)
  6315. sysTrayRecord->setText(ui->recordButton->text());
  6316. blog(LOG_INFO, RECORDING_STOP);
  6317. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6318. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6319. QTStr("Output.RecordFail.Unsupported"));
  6320. } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
  6321. QString msg =
  6322. last_error.isEmpty()
  6323. ? QTStr("Output.RecordError.EncodeErrorMsg")
  6324. : QTStr("Output.RecordError.EncodeErrorMsg.LastError")
  6325. .arg(last_error);
  6326. OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"),
  6327. msg);
  6328. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6329. OBSMessageBox::warning(this,
  6330. QTStr("Output.RecordNoSpace.Title"),
  6331. QTStr("Output.RecordNoSpace.Msg"));
  6332. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6333. const char *errorDescription;
  6334. DStr errorMessage;
  6335. bool use_last_error = true;
  6336. errorDescription = Str("Output.RecordError.Msg");
  6337. if (use_last_error && !last_error.isEmpty())
  6338. dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
  6339. QT_TO_UTF8(last_error));
  6340. else
  6341. dstr_copy(errorMessage, errorDescription);
  6342. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6343. QT_UTF8(errorMessage));
  6344. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6345. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6346. QSystemTrayIcon::Warning);
  6347. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6348. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6349. QSystemTrayIcon::Warning);
  6350. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6351. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6352. QSystemTrayIcon::Warning);
  6353. } else if (code == OBS_OUTPUT_SUCCESS) {
  6354. if (outputHandler) {
  6355. std::string path = outputHandler->lastRecordingPath;
  6356. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6357. ShowStatusBarMessage(str.arg(QT_UTF8(path.c_str())));
  6358. }
  6359. }
  6360. if (api)
  6361. api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);
  6362. if (diskFullTimer->isActive())
  6363. diskFullTimer->stop();
  6364. AutoRemux(outputHandler->lastRecordingPath.c_str());
  6365. OnDeactivate();
  6366. UpdatePause(false);
  6367. }
  6368. void OBSBasic::RecordingFileChanged(QString lastRecordingPath)
  6369. {
  6370. QString str = QTStr("Basic.StatusBar.RecordingSavedTo");
  6371. ShowStatusBarMessage(str.arg(lastRecordingPath));
  6372. AutoRemux(lastRecordingPath, true);
  6373. }
  6374. void OBSBasic::ShowReplayBufferPauseWarning()
  6375. {
  6376. auto msgBox = []() {
  6377. QMessageBox msgbox(App()->GetMainWindow());
  6378. msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
  6379. "PauseWarning.Title"));
  6380. msgbox.setText(QTStr("Output.ReplayBuffer."
  6381. "PauseWarning.Text"));
  6382. msgbox.setIcon(QMessageBox::Icon::Information);
  6383. msgbox.addButton(QMessageBox::Ok);
  6384. QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
  6385. msgbox.setCheckBox(cb);
  6386. msgbox.exec();
  6387. if (cb->isChecked()) {
  6388. config_set_bool(App()->GlobalConfig(), "General",
  6389. "WarnedAboutReplayBufferPausing", true);
  6390. config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
  6391. }
  6392. };
  6393. bool warned = config_get_bool(App()->GlobalConfig(), "General",
  6394. "WarnedAboutReplayBufferPausing");
  6395. if (!warned) {
  6396. QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
  6397. Q_ARG(VoidFunc, msgBox));
  6398. }
  6399. }
  6400. void OBSBasic::StartReplayBuffer()
  6401. {
  6402. if (!outputHandler || !outputHandler->replayBuffer)
  6403. return;
  6404. if (outputHandler->ReplayBufferActive())
  6405. return;
  6406. if (disableOutputsRef)
  6407. return;
  6408. if (!UIValidation::NoSourcesConfirmation(this)) {
  6409. replayBufferButton->first()->setChecked(false);
  6410. return;
  6411. }
  6412. if (!OutputPathValid()) {
  6413. OutputPathInvalidMessage();
  6414. replayBufferButton->first()->setChecked(false);
  6415. return;
  6416. }
  6417. if (LowDiskSpace()) {
  6418. DiskSpaceMessage();
  6419. replayBufferButton->first()->setChecked(false);
  6420. return;
  6421. }
  6422. if (api)
  6423. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);
  6424. SaveProject();
  6425. if (!outputHandler->StartReplayBuffer()) {
  6426. replayBufferButton->first()->setChecked(false);
  6427. } else if (os_atomic_load_bool(&recording_paused)) {
  6428. ShowReplayBufferPauseWarning();
  6429. }
  6430. }
  6431. void OBSBasic::ReplayBufferStopping()
  6432. {
  6433. if (!outputHandler || !outputHandler->replayBuffer)
  6434. return;
  6435. replayBufferButton->first()->setText(
  6436. QTStr("Basic.Main.StoppingReplayBuffer"));
  6437. if (sysTrayReplayBuffer)
  6438. sysTrayReplayBuffer->setText(
  6439. replayBufferButton->first()->text());
  6440. replayBufferStopping = true;
  6441. if (api)
  6442. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
  6443. }
  6444. void OBSBasic::StopReplayBuffer()
  6445. {
  6446. if (!outputHandler || !outputHandler->replayBuffer)
  6447. return;
  6448. SaveProject();
  6449. if (outputHandler->ReplayBufferActive())
  6450. outputHandler->StopReplayBuffer(replayBufferStopping);
  6451. OnDeactivate();
  6452. }
  6453. void OBSBasic::ReplayBufferStart()
  6454. {
  6455. if (!outputHandler || !outputHandler->replayBuffer)
  6456. return;
  6457. replayBufferButton->first()->setText(
  6458. QTStr("Basic.Main.StopReplayBuffer"));
  6459. replayBufferButton->first()->setChecked(true);
  6460. if (sysTrayReplayBuffer)
  6461. sysTrayReplayBuffer->setText(
  6462. replayBufferButton->first()->text());
  6463. replayBufferStopping = false;
  6464. if (api)
  6465. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);
  6466. OnActivate();
  6467. UpdateReplayBuffer();
  6468. blog(LOG_INFO, REPLAY_BUFFER_START);
  6469. }
  6470. void OBSBasic::ReplayBufferSave()
  6471. {
  6472. if (!outputHandler || !outputHandler->replayBuffer)
  6473. return;
  6474. if (!outputHandler->ReplayBufferActive())
  6475. return;
  6476. calldata_t cd = {0};
  6477. proc_handler_t *ph =
  6478. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6479. proc_handler_call(ph, "save", &cd);
  6480. calldata_free(&cd);
  6481. }
  6482. void OBSBasic::ReplayBufferSaved()
  6483. {
  6484. if (!outputHandler || !outputHandler->replayBuffer)
  6485. return;
  6486. if (!outputHandler->ReplayBufferActive())
  6487. return;
  6488. calldata_t cd = {0};
  6489. proc_handler_t *ph =
  6490. obs_output_get_proc_handler(outputHandler->replayBuffer);
  6491. proc_handler_call(ph, "get_last_replay", &cd);
  6492. std::string path = calldata_string(&cd, "path");
  6493. QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo")
  6494. .arg(QT_UTF8(path.c_str()));
  6495. ShowStatusBarMessage(msg);
  6496. lastReplay = path;
  6497. calldata_free(&cd);
  6498. if (api)
  6499. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_SAVED);
  6500. AutoRemux(QT_UTF8(path.c_str()));
  6501. }
  6502. void OBSBasic::ReplayBufferStop(int code)
  6503. {
  6504. if (!outputHandler || !outputHandler->replayBuffer)
  6505. return;
  6506. replayBufferButton->first()->setText(
  6507. QTStr("Basic.Main.StartReplayBuffer"));
  6508. replayBufferButton->first()->setChecked(false);
  6509. if (sysTrayReplayBuffer)
  6510. sysTrayReplayBuffer->setText(
  6511. replayBufferButton->first()->text());
  6512. blog(LOG_INFO, REPLAY_BUFFER_STOP);
  6513. if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
  6514. OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
  6515. QTStr("Output.RecordFail.Unsupported"));
  6516. } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
  6517. OBSMessageBox::warning(this,
  6518. QTStr("Output.RecordNoSpace.Title"),
  6519. QTStr("Output.RecordNoSpace.Msg"));
  6520. } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
  6521. OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
  6522. QTStr("Output.RecordError.Msg"));
  6523. } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
  6524. SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
  6525. QSystemTrayIcon::Warning);
  6526. } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
  6527. SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
  6528. QSystemTrayIcon::Warning);
  6529. } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
  6530. SysTrayNotify(QTStr("Output.RecordError.Msg"),
  6531. QSystemTrayIcon::Warning);
  6532. }
  6533. if (api)
  6534. api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);
  6535. OnDeactivate();
  6536. UpdateReplayBuffer(false);
  6537. }
  6538. void OBSBasic::StartVirtualCam()
  6539. {
  6540. if (!outputHandler || !outputHandler->virtualCam)
  6541. return;
  6542. if (outputHandler->VirtualCamActive())
  6543. return;
  6544. if (disableOutputsRef)
  6545. return;
  6546. SaveProject();
  6547. if (!outputHandler->StartVirtualCam()) {
  6548. vcamButton->first()->setChecked(false);
  6549. }
  6550. }
  6551. void OBSBasic::StopVirtualCam()
  6552. {
  6553. if (!outputHandler || !outputHandler->virtualCam)
  6554. return;
  6555. SaveProject();
  6556. if (outputHandler->VirtualCamActive())
  6557. outputHandler->StopVirtualCam();
  6558. OnDeactivate();
  6559. }
  6560. void OBSBasic::OnVirtualCamStart()
  6561. {
  6562. if (!outputHandler || !outputHandler->virtualCam)
  6563. return;
  6564. vcamButton->first()->setText(QTStr("Basic.Main.StopVirtualCam"));
  6565. if (sysTrayVirtualCam)
  6566. sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam"));
  6567. vcamButton->first()->setChecked(true);
  6568. if (api)
  6569. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED);
  6570. OnActivate();
  6571. blog(LOG_INFO, VIRTUAL_CAM_START);
  6572. }
  6573. void OBSBasic::OnVirtualCamStop(int)
  6574. {
  6575. if (!outputHandler || !outputHandler->virtualCam)
  6576. return;
  6577. vcamButton->first()->setText(QTStr("Basic.Main.StartVirtualCam"));
  6578. if (sysTrayVirtualCam)
  6579. sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam"));
  6580. vcamButton->first()->setChecked(false);
  6581. if (api)
  6582. api->on_event(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED);
  6583. blog(LOG_INFO, VIRTUAL_CAM_STOP);
  6584. OnDeactivate();
  6585. if (!restartingVCam)
  6586. return;
  6587. /* Restarting needs to be delayed to make sure that the virtual camera
  6588. * implementation is stopped and avoid race condition. */
  6589. QTimer::singleShot(100, this, &OBSBasic::RestartingVirtualCam);
  6590. }
  6591. void OBSBasic::on_streamButton_clicked()
  6592. {
  6593. if (outputHandler->StreamingActive()) {
  6594. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6595. "WarnBeforeStoppingStream");
  6596. #ifdef YOUTUBE_ENABLED
  6597. if (isVisible() && auth && IsYouTubeService(auth->service()) &&
  6598. autoStopBroadcast) {
  6599. QMessageBox::StandardButton button = OBSMessageBox::question(
  6600. this, QTStr("ConfirmStop.Title"),
  6601. QTStr("YouTube.Actions.AutoStopStreamingWarning"),
  6602. QMessageBox::Yes | QMessageBox::No,
  6603. QMessageBox::No);
  6604. if (button == QMessageBox::No) {
  6605. ui->streamButton->setChecked(true);
  6606. return;
  6607. }
  6608. confirm = false;
  6609. }
  6610. #endif
  6611. if (confirm && isVisible()) {
  6612. QMessageBox::StandardButton button =
  6613. OBSMessageBox::question(
  6614. this, QTStr("ConfirmStop.Title"),
  6615. QTStr("ConfirmStop.Text"),
  6616. QMessageBox::Yes | QMessageBox::No,
  6617. QMessageBox::No);
  6618. if (button == QMessageBox::No) {
  6619. ui->streamButton->setChecked(true);
  6620. return;
  6621. }
  6622. }
  6623. StopStreaming();
  6624. } else {
  6625. if (!UIValidation::NoSourcesConfirmation(this)) {
  6626. ui->streamButton->setChecked(false);
  6627. return;
  6628. }
  6629. Auth *auth = GetAuth();
  6630. auto action =
  6631. (auth && auth->external())
  6632. ? StreamSettingsAction::ContinueStream
  6633. : UIValidation::StreamSettingsConfirmation(
  6634. this, service);
  6635. switch (action) {
  6636. case StreamSettingsAction::ContinueStream:
  6637. break;
  6638. case StreamSettingsAction::OpenSettings:
  6639. on_action_Settings_triggered();
  6640. ui->streamButton->setChecked(false);
  6641. return;
  6642. case StreamSettingsAction::Cancel:
  6643. ui->streamButton->setChecked(false);
  6644. return;
  6645. }
  6646. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6647. "WarnBeforeStartingStream");
  6648. bool bwtest = false;
  6649. if (this->auth) {
  6650. OBSDataAutoRelease settings =
  6651. obs_service_get_settings(service);
  6652. bwtest = obs_data_get_bool(settings, "bwtest");
  6653. // Disable confirmation if this is going to open broadcast setup
  6654. if (auth && auth->broadcastFlow() && !broadcastReady &&
  6655. !broadcastActive)
  6656. confirm = false;
  6657. }
  6658. if (bwtest && isVisible()) {
  6659. QMessageBox::StandardButton button =
  6660. OBSMessageBox::question(
  6661. this, QTStr("ConfirmBWTest.Title"),
  6662. QTStr("ConfirmBWTest.Text"));
  6663. if (button == QMessageBox::No) {
  6664. ui->streamButton->setChecked(false);
  6665. return;
  6666. }
  6667. } else if (confirm && isVisible()) {
  6668. QMessageBox::StandardButton button =
  6669. OBSMessageBox::question(
  6670. this, QTStr("ConfirmStart.Title"),
  6671. QTStr("ConfirmStart.Text"),
  6672. QMessageBox::Yes | QMessageBox::No,
  6673. QMessageBox::No);
  6674. if (button == QMessageBox::No) {
  6675. ui->streamButton->setChecked(false);
  6676. return;
  6677. }
  6678. }
  6679. StartStreaming();
  6680. }
  6681. }
  6682. void OBSBasic::on_recordButton_clicked()
  6683. {
  6684. if (outputHandler->RecordingActive()) {
  6685. bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
  6686. "WarnBeforeStoppingRecord");
  6687. if (confirm && isVisible()) {
  6688. QMessageBox::StandardButton button =
  6689. OBSMessageBox::question(
  6690. this, QTStr("ConfirmStopRecord.Title"),
  6691. QTStr("ConfirmStopRecord.Text"),
  6692. QMessageBox::Yes | QMessageBox::No,
  6693. QMessageBox::No);
  6694. if (button == QMessageBox::No) {
  6695. ui->recordButton->setChecked(true);
  6696. return;
  6697. }
  6698. }
  6699. StopRecording();
  6700. } else {
  6701. if (!UIValidation::NoSourcesConfirmation(this)) {
  6702. ui->recordButton->setChecked(false);
  6703. return;
  6704. }
  6705. StartRecording();
  6706. }
  6707. }
  6708. void OBSBasic::VCamButtonClicked()
  6709. {
  6710. if (outputHandler->VirtualCamActive()) {
  6711. StopVirtualCam();
  6712. } else {
  6713. if (!UIValidation::NoSourcesConfirmation(this)) {
  6714. vcamButton->first()->setChecked(false);
  6715. return;
  6716. }
  6717. StartVirtualCam();
  6718. }
  6719. }
  6720. void OBSBasic::VCamConfigButtonClicked()
  6721. {
  6722. OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(),
  6723. this);
  6724. connect(&dialog, &OBSBasicVCamConfig::Accepted, this,
  6725. &OBSBasic::UpdateVirtualCamConfig);
  6726. connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this,
  6727. &OBSBasic::RestartVirtualCam);
  6728. dialog.exec();
  6729. }
  6730. void OBSBasic::UpdateVirtualCamConfig(const VCamConfig &config)
  6731. {
  6732. vcamConfig = config;
  6733. outputHandler->UpdateVirtualCamOutputSource();
  6734. }
  6735. void OBSBasic::RestartVirtualCam(const VCamConfig &config)
  6736. {
  6737. restartingVCam = true;
  6738. StopVirtualCam();
  6739. vcamConfig = config;
  6740. }
  6741. void OBSBasic::RestartingVirtualCam()
  6742. {
  6743. if (!restartingVCam)
  6744. return;
  6745. outputHandler->UpdateVirtualCamOutputSource();
  6746. StartVirtualCam();
  6747. restartingVCam = false;
  6748. }
  6749. void OBSBasic::on_settingsButton_clicked()
  6750. {
  6751. on_action_Settings_triggered();
  6752. }
  6753. void OBSBasic::on_actionHelpPortal_triggered()
  6754. {
  6755. QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
  6756. QDesktopServices::openUrl(url);
  6757. }
  6758. void OBSBasic::on_actionWebsite_triggered()
  6759. {
  6760. QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
  6761. QDesktopServices::openUrl(url);
  6762. }
  6763. void OBSBasic::on_actionDiscord_triggered()
  6764. {
  6765. QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
  6766. QDesktopServices::openUrl(url);
  6767. }
  6768. void OBSBasic::on_actionShowWhatsNew_triggered()
  6769. {
  6770. #ifdef WHATSNEW_ENABLED
  6771. if (introCheckThread && introCheckThread->isRunning())
  6772. return;
  6773. if (!cef)
  6774. return;
  6775. config_set_int(App()->GlobalConfig(), "General", "InfoIncrement", -1);
  6776. WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
  6777. connect(wnit, &WhatsNewInfoThread::Result, this,
  6778. &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection);
  6779. introCheckThread.reset(wnit);
  6780. introCheckThread->start();
  6781. #endif
  6782. }
  6783. void OBSBasic::on_actionShowSettingsFolder_triggered()
  6784. {
  6785. char path[512];
  6786. int ret = GetConfigPath(path, 512, "obs-studio");
  6787. if (ret <= 0)
  6788. return;
  6789. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6790. }
  6791. void OBSBasic::on_actionShowProfileFolder_triggered()
  6792. {
  6793. char path[512];
  6794. int ret = GetProfilePath(path, 512, "");
  6795. if (ret <= 0)
  6796. return;
  6797. QDesktopServices::openUrl(QUrl::fromLocalFile(path));
  6798. }
  6799. int OBSBasic::GetTopSelectedSourceItem()
  6800. {
  6801. QModelIndexList selectedItems =
  6802. ui->sources->selectionModel()->selectedIndexes();
  6803. return selectedItems.count() ? selectedItems[0].row() : -1;
  6804. }
  6805. QModelIndexList OBSBasic::GetAllSelectedSourceItems()
  6806. {
  6807. return ui->sources->selectionModel()->selectedIndexes();
  6808. }
  6809. void OBSBasic::on_preview_customContextMenuRequested()
  6810. {
  6811. CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
  6812. }
  6813. void OBSBasic::ProgramViewContextMenuRequested()
  6814. {
  6815. QMenu popup(this);
  6816. QPointer<QMenu> studioProgramProjector;
  6817. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  6818. AddProjectorMenuMonitors(studioProgramProjector, this,
  6819. &OBSBasic::OpenStudioProgramProjector);
  6820. popup.addMenu(studioProgramProjector);
  6821. QAction *studioProgramWindow =
  6822. popup.addAction(QTStr("StudioProgramWindow"), this,
  6823. &OBSBasic::OpenStudioProgramWindow);
  6824. popup.addAction(studioProgramWindow);
  6825. popup.addAction(QTStr("Screenshot.StudioProgram"), this,
  6826. &OBSBasic::ScreenshotProgram);
  6827. popup.exec(QCursor::pos());
  6828. }
  6829. void OBSBasic::on_previewDisabledWidget_customContextMenuRequested()
  6830. {
  6831. QMenu popup(this);
  6832. delete previewProjectorMain;
  6833. QAction *action =
  6834. popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
  6835. this, &OBSBasic::TogglePreview);
  6836. action->setCheckable(true);
  6837. action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
  6838. previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
  6839. AddProjectorMenuMonitors(previewProjectorMain, this,
  6840. &OBSBasic::OpenPreviewProjector);
  6841. QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
  6842. &OBSBasic::OpenPreviewWindow);
  6843. popup.addMenu(previewProjectorMain);
  6844. popup.addAction(previewWindow);
  6845. popup.exec(QCursor::pos());
  6846. }
  6847. void OBSBasic::on_actionAlwaysOnTop_triggered()
  6848. {
  6849. #ifndef _WIN32
  6850. /* Make sure all dialogs are safely and successfully closed before
  6851. * switching the always on top mode due to the fact that windows all
  6852. * have to be recreated, so queue the actual toggle to happen after
  6853. * all events related to closing the dialogs have finished */
  6854. CloseDialogs();
  6855. #endif
  6856. QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
  6857. Qt::QueuedConnection);
  6858. }
  6859. void OBSBasic::ToggleAlwaysOnTop()
  6860. {
  6861. bool isAlwaysOnTop = IsAlwaysOnTop(this);
  6862. ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
  6863. SetAlwaysOnTop(this, !isAlwaysOnTop);
  6864. show();
  6865. }
  6866. void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
  6867. {
  6868. const char *val = config_get_string(basicConfig, "Video", "FPSCommon");
  6869. if (strcmp(val, "10") == 0) {
  6870. num = 10;
  6871. den = 1;
  6872. } else if (strcmp(val, "20") == 0) {
  6873. num = 20;
  6874. den = 1;
  6875. } else if (strcmp(val, "24 NTSC") == 0) {
  6876. num = 24000;
  6877. den = 1001;
  6878. } else if (strcmp(val, "25 PAL") == 0) {
  6879. num = 25;
  6880. den = 1;
  6881. } else if (strcmp(val, "29.97") == 0) {
  6882. num = 30000;
  6883. den = 1001;
  6884. } else if (strcmp(val, "48") == 0) {
  6885. num = 48;
  6886. den = 1;
  6887. } else if (strcmp(val, "50 PAL") == 0) {
  6888. num = 50;
  6889. den = 1;
  6890. } else if (strcmp(val, "59.94") == 0) {
  6891. num = 60000;
  6892. den = 1001;
  6893. } else if (strcmp(val, "60") == 0) {
  6894. num = 60;
  6895. den = 1;
  6896. } else {
  6897. num = 30;
  6898. den = 1;
  6899. }
  6900. }
  6901. void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
  6902. {
  6903. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
  6904. den = 1;
  6905. }
  6906. void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
  6907. {
  6908. num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
  6909. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
  6910. }
  6911. void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
  6912. {
  6913. num = 1000000000;
  6914. den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
  6915. }
  6916. void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
  6917. {
  6918. uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");
  6919. if (type == 1) //"Integer"
  6920. GetFPSInteger(num, den);
  6921. else if (type == 2) //"Fraction"
  6922. GetFPSFraction(num, den);
  6923. /*
  6924. * else if (false) //"Nanoseconds", currently not implemented
  6925. * GetFPSNanoseconds(num, den);
  6926. */
  6927. else
  6928. GetFPSCommon(num, den);
  6929. }
  6930. config_t *OBSBasic::Config() const
  6931. {
  6932. return basicConfig;
  6933. }
  6934. #ifdef YOUTUBE_ENABLED
  6935. YouTubeAppDock *OBSBasic::GetYouTubeAppDock()
  6936. {
  6937. return youtubeAppDock;
  6938. }
  6939. void OBSBasic::NewYouTubeAppDock()
  6940. {
  6941. if (!cef_js_avail)
  6942. return;
  6943. if (youtubeAppDock)
  6944. RemoveDockWidget(youtubeAppDock->objectName());
  6945. youtubeAppDock = new YouTubeAppDock();
  6946. }
  6947. void OBSBasic::DeleteYouTubeAppDock()
  6948. {
  6949. if (!cef_js_avail)
  6950. return;
  6951. if (youtubeAppDock)
  6952. RemoveDockWidget(youtubeAppDock->objectName());
  6953. youtubeAppDock = nullptr;
  6954. }
  6955. #endif
  6956. void OBSBasic::UpdateEditMenu()
  6957. {
  6958. QModelIndexList items = GetAllSelectedSourceItems();
  6959. int count = items.count();
  6960. size_t filter_count = 0;
  6961. if (count == 1) {
  6962. OBSSceneItem sceneItem =
  6963. ui->sources->Get(GetTopSelectedSourceItem());
  6964. OBSSource source = obs_sceneitem_get_source(sceneItem);
  6965. filter_count = obs_source_filter_count(source);
  6966. }
  6967. bool allowPastingDuplicate = !!clipboard.size();
  6968. for (size_t i = clipboard.size(); i > 0; i--) {
  6969. const size_t idx = i - 1;
  6970. OBSWeakSource &weak = clipboard[idx].weak_source;
  6971. if (obs_weak_source_expired(weak)) {
  6972. clipboard.erase(clipboard.begin() + idx);
  6973. continue;
  6974. }
  6975. OBSSourceAutoRelease strong =
  6976. obs_weak_source_get_source(weak.Get());
  6977. if (allowPastingDuplicate &&
  6978. obs_source_get_output_flags(strong) &
  6979. OBS_SOURCE_DO_NOT_DUPLICATE)
  6980. allowPastingDuplicate = false;
  6981. }
  6982. ui->actionCopySource->setEnabled(count > 0);
  6983. ui->actionEditTransform->setEnabled(count == 1);
  6984. ui->actionCopyTransform->setEnabled(count == 1);
  6985. ui->actionPasteTransform->setEnabled(hasCopiedTransform && count > 0);
  6986. ui->actionCopyFilters->setEnabled(filter_count > 0);
  6987. ui->actionPasteFilters->setEnabled(
  6988. !obs_weak_source_expired(copyFiltersSource) && count > 0);
  6989. ui->actionPasteRef->setEnabled(!!clipboard.size());
  6990. ui->actionPasteDup->setEnabled(allowPastingDuplicate);
  6991. ui->actionMoveUp->setEnabled(count > 0);
  6992. ui->actionMoveDown->setEnabled(count > 0);
  6993. ui->actionMoveToTop->setEnabled(count > 0);
  6994. ui->actionMoveToBottom->setEnabled(count > 0);
  6995. bool canTransform = false;
  6996. for (int i = 0; i < count; i++) {
  6997. OBSSceneItem item = ui->sources->Get(items.value(i).row());
  6998. if (!obs_sceneitem_locked(item))
  6999. canTransform = true;
  7000. }
  7001. ui->actionResetTransform->setEnabled(canTransform);
  7002. ui->actionRotate90CW->setEnabled(canTransform);
  7003. ui->actionRotate90CCW->setEnabled(canTransform);
  7004. ui->actionRotate180->setEnabled(canTransform);
  7005. ui->actionFlipHorizontal->setEnabled(canTransform);
  7006. ui->actionFlipVertical->setEnabled(canTransform);
  7007. ui->actionFitToScreen->setEnabled(canTransform);
  7008. ui->actionStretchToScreen->setEnabled(canTransform);
  7009. ui->actionCenterToScreen->setEnabled(canTransform);
  7010. ui->actionVerticalCenter->setEnabled(canTransform);
  7011. ui->actionHorizontalCenter->setEnabled(canTransform);
  7012. }
  7013. void OBSBasic::on_actionEditTransform_triggered()
  7014. {
  7015. const auto item = GetCurrentSceneItem();
  7016. if (!item)
  7017. return;
  7018. CreateEditTransformWindow(item);
  7019. }
  7020. void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item)
  7021. {
  7022. if (transformWindow)
  7023. transformWindow->close();
  7024. transformWindow = new OBSBasicTransform(item, this);
  7025. connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow,
  7026. &OBSBasicTransform::OnSceneChanged);
  7027. transformWindow->show();
  7028. transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  7029. }
  7030. void OBSBasic::on_actionCopyTransform_triggered()
  7031. {
  7032. OBSSceneItem item = GetCurrentSceneItem();
  7033. obs_sceneitem_get_info(item, &copiedTransformInfo);
  7034. obs_sceneitem_get_crop(item, &copiedCropInfo);
  7035. ui->actionPasteTransform->setEnabled(true);
  7036. hasCopiedTransform = true;
  7037. }
  7038. void undo_redo(const std::string &data)
  7039. {
  7040. OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str());
  7041. OBSSourceAutoRelease source =
  7042. obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid"));
  7043. reinterpret_cast<OBSBasic *>(App()->GetMainWindow())
  7044. ->SetCurrentScene(source.Get(), true);
  7045. obs_scene_load_transform_states(data.c_str());
  7046. }
  7047. void OBSBasic::on_actionPasteTransform_triggered()
  7048. {
  7049. OBSDataAutoRelease wrapper =
  7050. obs_scene_save_transform_states(GetCurrentScene(), false);
  7051. auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) {
  7052. if (!obs_sceneitem_selected(item))
  7053. return true;
  7054. OBSBasic *main = reinterpret_cast<OBSBasic *>(data);
  7055. obs_sceneitem_defer_update_begin(item);
  7056. obs_sceneitem_set_info(item, &main->copiedTransformInfo);
  7057. obs_sceneitem_set_crop(item, &main->copiedCropInfo);
  7058. obs_sceneitem_defer_update_end(item);
  7059. return true;
  7060. };
  7061. obs_scene_enum_items(GetCurrentScene(), func, this);
  7062. OBSDataAutoRelease rwrapper =
  7063. obs_scene_save_transform_states(GetCurrentScene(), false);
  7064. std::string undo_data(obs_data_get_json(wrapper));
  7065. std::string redo_data(obs_data_get_json(rwrapper));
  7066. undo_s.add_action(
  7067. QTStr("Undo.Transform.Paste")
  7068. .arg(obs_source_get_name(GetCurrentSceneSource())),
  7069. undo_redo, undo_redo, undo_data, redo_data);
  7070. }
  7071. static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *)
  7072. {
  7073. if (obs_sceneitem_is_group(item))
  7074. obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
  7075. if (!obs_sceneitem_selected(item))
  7076. return true;
  7077. if (obs_sceneitem_locked(item))
  7078. return true;
  7079. obs_sceneitem_defer_update_begin(item);
  7080. obs_transform_info info;
  7081. vec2_set(&info.pos, 0.0f, 0.0f);
  7082. vec2_set(&info.scale, 1.0f, 1.0f);
  7083. info.rot = 0.0f;
  7084. info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
  7085. info.bounds_type = OBS_BOUNDS_NONE;
  7086. info.bounds_alignment = OBS_ALIGN_CENTER;
  7087. vec2_set(&info.bounds, 0.0f, 0.0f);
  7088. obs_sceneitem_set_info(item, &info);
  7089. obs_sceneitem_crop crop = {};
  7090. obs_sceneitem_set_crop(item, &crop);
  7091. obs_sceneitem_defer_update_end(item);
  7092. return true;
  7093. }
  7094. void OBSBasic::on_actionResetTransform_triggered()
  7095. {
  7096. OBSScene scene = GetCurrentScene();
  7097. OBSDataAutoRelease wrapper =
  7098. obs_scene_save_transform_states(scene, false);
  7099. obs_scene_enum_items(scene, reset_tr, nullptr);
  7100. OBSDataAutoRelease rwrapper =
  7101. obs_scene_save_transform_states(scene, false);
  7102. std::string undo_data(obs_data_get_json(wrapper));
  7103. std::string redo_data(obs_data_get_json(rwrapper));
  7104. undo_s.add_action(
  7105. QTStr("Undo.Transform.Reset")
  7106. .arg(obs_source_get_name(obs_scene_get_source(scene))),
  7107. undo_redo, undo_redo, undo_data, redo_data);
  7108. obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
  7109. }
  7110. static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
  7111. {
  7112. matrix4 boxTransform;
  7113. obs_sceneitem_get_box_transform(item, &boxTransform);
  7114. vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
  7115. vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
  7116. auto GetMinPos = [&](float x, float y) {
  7117. vec3 pos;
  7118. vec3_set(&pos, x, y, 0.0f);
  7119. vec3_transform(&pos, &pos, &boxTransform);
  7120. vec3_min(&tl, &tl, &pos);
  7121. vec3_max(&br, &br, &pos);
  7122. };
  7123. GetMinPos(0.0f, 0.0f);
  7124. GetMinPos(1.0f, 0.0f);
  7125. GetMinPos(0.0f, 1.0f);
  7126. GetMinPos(1.0f, 1.0f);
  7127. }
  7128. static vec3 GetItemTL(obs_sceneitem_t *item)
  7129. {
  7130. vec3 tl, br;
  7131. GetItemBox(item, tl, br);
  7132. return tl;
  7133. }
  7134. static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
  7135. {
  7136. vec3 newTL;
  7137. vec2 pos;
  7138. obs_sceneitem_get_pos(item, &pos);
  7139. newTL = GetItemTL(item);
  7140. pos.x += tl.x - newTL.x;
  7141. pos.y += tl.y - newTL.y;
  7142. obs_sceneitem_set_pos(item, &pos);
  7143. }
  7144. static bool RotateSelectedSources(obs_scene_t * /* scene */,
  7145. obs_sceneitem_t *item, void *param)
  7146. {
  7147. if (obs_sceneitem_is_group(item))
  7148. obs_sceneitem_group_enum_items(item, RotateSelectedSources,
  7149. param);
  7150. if (!obs_sceneitem_selected(item))
  7151. return true;
  7152. if (obs_sceneitem_locked(item))
  7153. return true;
  7154. float rot = *reinterpret_cast<float *>(param);
  7155. vec3 tl = GetItemTL(item);
  7156. rot += obs_sceneitem_get_rot(item);
  7157. if (rot >= 360.0f)
  7158. rot -= 360.0f;
  7159. else if (rot <= -360.0f)
  7160. rot += 360.0f;
  7161. obs_sceneitem_set_rot(item, rot);
  7162. obs_sceneitem_force_update_transform(item);
  7163. SetItemTL(item, tl);
  7164. return true;
  7165. };
  7166. void OBSBasic::on_actionRotate90CW_triggered()
  7167. {
  7168. float f90CW = 90.0f;
  7169. OBSDataAutoRelease wrapper =
  7170. obs_scene_save_transform_states(GetCurrentScene(), false);
  7171. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
  7172. OBSDataAutoRelease rwrapper =
  7173. obs_scene_save_transform_states(GetCurrentScene(), false);
  7174. std::string undo_data(obs_data_get_json(wrapper));
  7175. std::string redo_data(obs_data_get_json(rwrapper));
  7176. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7177. .arg(obs_source_get_name(obs_scene_get_source(
  7178. GetCurrentScene()))),
  7179. undo_redo, undo_redo, undo_data, redo_data);
  7180. }
  7181. void OBSBasic::on_actionRotate90CCW_triggered()
  7182. {
  7183. float f90CCW = -90.0f;
  7184. OBSDataAutoRelease wrapper =
  7185. obs_scene_save_transform_states(GetCurrentScene(), false);
  7186. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
  7187. OBSDataAutoRelease rwrapper =
  7188. obs_scene_save_transform_states(GetCurrentScene(), false);
  7189. std::string undo_data(obs_data_get_json(wrapper));
  7190. std::string redo_data(obs_data_get_json(rwrapper));
  7191. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7192. .arg(obs_source_get_name(obs_scene_get_source(
  7193. GetCurrentScene()))),
  7194. undo_redo, undo_redo, undo_data, redo_data);
  7195. }
  7196. void OBSBasic::on_actionRotate180_triggered()
  7197. {
  7198. float f180 = 180.0f;
  7199. OBSDataAutoRelease wrapper =
  7200. obs_scene_save_transform_states(GetCurrentScene(), false);
  7201. obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
  7202. OBSDataAutoRelease rwrapper =
  7203. obs_scene_save_transform_states(GetCurrentScene(), false);
  7204. std::string undo_data(obs_data_get_json(wrapper));
  7205. std::string redo_data(obs_data_get_json(rwrapper));
  7206. undo_s.add_action(QTStr("Undo.Transform.Rotate")
  7207. .arg(obs_source_get_name(obs_scene_get_source(
  7208. GetCurrentScene()))),
  7209. undo_redo, undo_redo, undo_data, redo_data);
  7210. }
  7211. static bool MultiplySelectedItemScale(obs_scene_t * /* scene */,
  7212. obs_sceneitem_t *item, void *param)
  7213. {
  7214. vec2 &mul = *reinterpret_cast<vec2 *>(param);
  7215. if (obs_sceneitem_is_group(item))
  7216. obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
  7217. param);
  7218. if (!obs_sceneitem_selected(item))
  7219. return true;
  7220. if (obs_sceneitem_locked(item))
  7221. return true;
  7222. vec3 tl = GetItemTL(item);
  7223. vec2 scale;
  7224. obs_sceneitem_get_scale(item, &scale);
  7225. vec2_mul(&scale, &scale, &mul);
  7226. obs_sceneitem_set_scale(item, &scale);
  7227. obs_sceneitem_force_update_transform(item);
  7228. SetItemTL(item, tl);
  7229. return true;
  7230. }
  7231. void OBSBasic::on_actionFlipHorizontal_triggered()
  7232. {
  7233. vec2 scale;
  7234. vec2_set(&scale, -1.0f, 1.0f);
  7235. OBSDataAutoRelease wrapper =
  7236. obs_scene_save_transform_states(GetCurrentScene(), false);
  7237. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7238. &scale);
  7239. OBSDataAutoRelease rwrapper =
  7240. obs_scene_save_transform_states(GetCurrentScene(), false);
  7241. std::string undo_data(obs_data_get_json(wrapper));
  7242. std::string redo_data(obs_data_get_json(rwrapper));
  7243. undo_s.add_action(QTStr("Undo.Transform.HFlip")
  7244. .arg(obs_source_get_name(obs_scene_get_source(
  7245. GetCurrentScene()))),
  7246. undo_redo, undo_redo, undo_data, redo_data);
  7247. }
  7248. void OBSBasic::on_actionFlipVertical_triggered()
  7249. {
  7250. vec2 scale;
  7251. vec2_set(&scale, 1.0f, -1.0f);
  7252. OBSDataAutoRelease wrapper =
  7253. obs_scene_save_transform_states(GetCurrentScene(), false);
  7254. obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
  7255. &scale);
  7256. OBSDataAutoRelease rwrapper =
  7257. obs_scene_save_transform_states(GetCurrentScene(), false);
  7258. std::string undo_data(obs_data_get_json(wrapper));
  7259. std::string redo_data(obs_data_get_json(rwrapper));
  7260. undo_s.add_action(QTStr("Undo.Transform.VFlip")
  7261. .arg(obs_source_get_name(obs_scene_get_source(
  7262. GetCurrentScene()))),
  7263. undo_redo, undo_redo, undo_data, redo_data);
  7264. }
  7265. static bool CenterAlignSelectedItems(obs_scene_t * /* scene */,
  7266. obs_sceneitem_t *item, void *param)
  7267. {
  7268. obs_bounds_type boundsType =
  7269. *reinterpret_cast<obs_bounds_type *>(param);
  7270. if (obs_sceneitem_is_group(item))
  7271. obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
  7272. param);
  7273. if (!obs_sceneitem_selected(item))
  7274. return true;
  7275. if (obs_sceneitem_locked(item))
  7276. return true;
  7277. obs_video_info ovi;
  7278. obs_get_video_info(&ovi);
  7279. obs_transform_info itemInfo;
  7280. vec2_set(&itemInfo.pos, 0.0f, 0.0f);
  7281. vec2_set(&itemInfo.scale, 1.0f, 1.0f);
  7282. itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
  7283. itemInfo.rot = 0.0f;
  7284. vec2_set(&itemInfo.bounds, float(ovi.base_width),
  7285. float(ovi.base_height));
  7286. itemInfo.bounds_type = boundsType;
  7287. itemInfo.bounds_alignment = OBS_ALIGN_CENTER;
  7288. obs_sceneitem_set_info(item, &itemInfo);
  7289. return true;
  7290. }
  7291. void OBSBasic::on_actionFitToScreen_triggered()
  7292. {
  7293. obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
  7294. OBSDataAutoRelease wrapper =
  7295. obs_scene_save_transform_states(GetCurrentScene(), false);
  7296. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7297. &boundsType);
  7298. OBSDataAutoRelease rwrapper =
  7299. obs_scene_save_transform_states(GetCurrentScene(), false);
  7300. std::string undo_data(obs_data_get_json(wrapper));
  7301. std::string redo_data(obs_data_get_json(rwrapper));
  7302. undo_s.add_action(QTStr("Undo.Transform.FitToScreen")
  7303. .arg(obs_source_get_name(obs_scene_get_source(
  7304. GetCurrentScene()))),
  7305. undo_redo, undo_redo, undo_data, redo_data);
  7306. }
  7307. void OBSBasic::on_actionStretchToScreen_triggered()
  7308. {
  7309. obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
  7310. OBSDataAutoRelease wrapper =
  7311. obs_scene_save_transform_states(GetCurrentScene(), false);
  7312. obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
  7313. &boundsType);
  7314. OBSDataAutoRelease rwrapper =
  7315. obs_scene_save_transform_states(GetCurrentScene(), false);
  7316. std::string undo_data(obs_data_get_json(wrapper));
  7317. std::string redo_data(obs_data_get_json(rwrapper));
  7318. undo_s.add_action(QTStr("Undo.Transform.StretchToScreen")
  7319. .arg(obs_source_get_name(obs_scene_get_source(
  7320. GetCurrentScene()))),
  7321. undo_redo, undo_redo, undo_data, redo_data);
  7322. }
  7323. void OBSBasic::CenterSelectedSceneItems(const CenterType &centerType)
  7324. {
  7325. QModelIndexList selectedItems = GetAllSelectedSourceItems();
  7326. if (!selectedItems.count())
  7327. return;
  7328. vector<OBSSceneItem> items;
  7329. // Filter out items that have no size
  7330. for (int x = 0; x < selectedItems.count(); x++) {
  7331. OBSSceneItem item = ui->sources->Get(selectedItems[x].row());
  7332. obs_transform_info oti;
  7333. obs_sceneitem_get_info(item, &oti);
  7334. obs_source_t *source = obs_sceneitem_get_source(item);
  7335. float width = float(obs_source_get_width(source)) * oti.scale.x;
  7336. float height =
  7337. float(obs_source_get_height(source)) * oti.scale.y;
  7338. if (width == 0.0f || height == 0.0f)
  7339. continue;
  7340. items.emplace_back(item);
  7341. }
  7342. if (!items.size())
  7343. return;
  7344. // Get center x, y coordinates of items
  7345. vec3 center;
  7346. float top = M_INFINITE;
  7347. float left = M_INFINITE;
  7348. float right = 0.0f;
  7349. float bottom = 0.0f;
  7350. for (auto &item : items) {
  7351. vec3 tl, br;
  7352. GetItemBox(item, tl, br);
  7353. left = (std::min)(tl.x, left);
  7354. top = (std::min)(tl.y, top);
  7355. right = (std::max)(br.x, right);
  7356. bottom = (std::max)(br.y, bottom);
  7357. }
  7358. center.x = (right + left) / 2.0f;
  7359. center.y = (top + bottom) / 2.0f;
  7360. center.z = 0.0f;
  7361. // Get coordinates of screen center
  7362. obs_video_info ovi;
  7363. obs_get_video_info(&ovi);
  7364. vec3 screenCenter;
  7365. vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height),
  7366. 0.0f);
  7367. vec3_mulf(&screenCenter, &screenCenter, 0.5f);
  7368. // Calculate difference between screen center and item center
  7369. vec3 offset;
  7370. vec3_sub(&offset, &screenCenter, &center);
  7371. // Shift items by offset
  7372. for (auto &item : items) {
  7373. vec3 tl, br;
  7374. GetItemBox(item, tl, br);
  7375. vec3_add(&tl, &tl, &offset);
  7376. vec3 itemTL = GetItemTL(item);
  7377. if (centerType == CenterType::Vertical)
  7378. tl.x = itemTL.x;
  7379. else if (centerType == CenterType::Horizontal)
  7380. tl.y = itemTL.y;
  7381. SetItemTL(item, tl);
  7382. }
  7383. }
  7384. void OBSBasic::on_actionCenterToScreen_triggered()
  7385. {
  7386. CenterType centerType = CenterType::Scene;
  7387. OBSDataAutoRelease wrapper =
  7388. obs_scene_save_transform_states(GetCurrentScene(), false);
  7389. CenterSelectedSceneItems(centerType);
  7390. OBSDataAutoRelease rwrapper =
  7391. obs_scene_save_transform_states(GetCurrentScene(), false);
  7392. std::string undo_data(obs_data_get_json(wrapper));
  7393. std::string redo_data(obs_data_get_json(rwrapper));
  7394. undo_s.add_action(QTStr("Undo.Transform.Center")
  7395. .arg(obs_source_get_name(obs_scene_get_source(
  7396. GetCurrentScene()))),
  7397. undo_redo, undo_redo, undo_data, redo_data);
  7398. }
  7399. void OBSBasic::on_actionVerticalCenter_triggered()
  7400. {
  7401. CenterType centerType = CenterType::Vertical;
  7402. OBSDataAutoRelease wrapper =
  7403. obs_scene_save_transform_states(GetCurrentScene(), false);
  7404. CenterSelectedSceneItems(centerType);
  7405. OBSDataAutoRelease rwrapper =
  7406. obs_scene_save_transform_states(GetCurrentScene(), false);
  7407. std::string undo_data(obs_data_get_json(wrapper));
  7408. std::string redo_data(obs_data_get_json(rwrapper));
  7409. undo_s.add_action(QTStr("Undo.Transform.VCenter")
  7410. .arg(obs_source_get_name(obs_scene_get_source(
  7411. GetCurrentScene()))),
  7412. undo_redo, undo_redo, undo_data, redo_data);
  7413. }
  7414. void OBSBasic::on_actionHorizontalCenter_triggered()
  7415. {
  7416. CenterType centerType = CenterType::Horizontal;
  7417. OBSDataAutoRelease wrapper =
  7418. obs_scene_save_transform_states(GetCurrentScene(), false);
  7419. CenterSelectedSceneItems(centerType);
  7420. OBSDataAutoRelease rwrapper =
  7421. obs_scene_save_transform_states(GetCurrentScene(), false);
  7422. std::string undo_data(obs_data_get_json(wrapper));
  7423. std::string redo_data(obs_data_get_json(rwrapper));
  7424. undo_s.add_action(QTStr("Undo.Transform.HCenter")
  7425. .arg(obs_source_get_name(obs_scene_get_source(
  7426. GetCurrentScene()))),
  7427. undo_redo, undo_redo, undo_data, redo_data);
  7428. }
  7429. void OBSBasic::EnablePreviewDisplay(bool enable)
  7430. {
  7431. obs_display_set_enabled(ui->preview->GetDisplay(), enable);
  7432. ui->preview->setVisible(enable);
  7433. ui->previewDisabledWidget->setVisible(!enable);
  7434. }
  7435. void OBSBasic::TogglePreview()
  7436. {
  7437. previewEnabled = !previewEnabled;
  7438. EnablePreviewDisplay(previewEnabled);
  7439. }
  7440. void OBSBasic::EnablePreview()
  7441. {
  7442. if (previewProgramMode)
  7443. return;
  7444. previewEnabled = true;
  7445. EnablePreviewDisplay(true);
  7446. }
  7447. void OBSBasic::DisablePreview()
  7448. {
  7449. if (previewProgramMode)
  7450. return;
  7451. previewEnabled = false;
  7452. EnablePreviewDisplay(false);
  7453. }
  7454. void OBSBasic::EnablePreviewProgram()
  7455. {
  7456. SetPreviewProgramMode(true);
  7457. }
  7458. void OBSBasic::DisablePreviewProgram()
  7459. {
  7460. SetPreviewProgramMode(false);
  7461. }
  7462. static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
  7463. {
  7464. if (obs_sceneitem_locked(item))
  7465. return true;
  7466. struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
  7467. struct vec2 pos;
  7468. if (!obs_sceneitem_selected(item)) {
  7469. if (obs_sceneitem_is_group(item)) {
  7470. struct vec3 offset3;
  7471. vec3_set(&offset3, offset.x, offset.y, 0.0f);
  7472. struct matrix4 matrix;
  7473. obs_sceneitem_get_draw_transform(item, &matrix);
  7474. vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
  7475. matrix4_inv(&matrix, &matrix);
  7476. vec3_transform(&offset3, &offset3, &matrix);
  7477. struct vec2 new_offset;
  7478. vec2_set(&new_offset, offset3.x, offset3.y);
  7479. obs_sceneitem_group_enum_items(item, nudge_callback,
  7480. &new_offset);
  7481. }
  7482. return true;
  7483. }
  7484. obs_sceneitem_get_pos(item, &pos);
  7485. vec2_add(&pos, &pos, &offset);
  7486. obs_sceneitem_set_pos(item, &pos);
  7487. return true;
  7488. }
  7489. void OBSBasic::Nudge(int dist, MoveDir dir)
  7490. {
  7491. if (ui->preview->Locked())
  7492. return;
  7493. struct vec2 offset;
  7494. vec2_set(&offset, 0.0f, 0.0f);
  7495. switch (dir) {
  7496. case MoveDir::Up:
  7497. offset.y = (float)-dist;
  7498. break;
  7499. case MoveDir::Down:
  7500. offset.y = (float)dist;
  7501. break;
  7502. case MoveDir::Left:
  7503. offset.x = (float)-dist;
  7504. break;
  7505. case MoveDir::Right:
  7506. offset.x = (float)dist;
  7507. break;
  7508. }
  7509. if (!recent_nudge) {
  7510. recent_nudge = true;
  7511. OBSDataAutoRelease wrapper = obs_scene_save_transform_states(
  7512. GetCurrentScene(), true);
  7513. std::string undo_data(obs_data_get_json(wrapper));
  7514. nudge_timer = new QTimer;
  7515. QObject::connect(
  7516. nudge_timer, &QTimer::timeout,
  7517. [this, &recent_nudge = recent_nudge, undo_data]() {
  7518. OBSDataAutoRelease rwrapper =
  7519. obs_scene_save_transform_states(
  7520. GetCurrentScene(), true);
  7521. std::string redo_data(
  7522. obs_data_get_json(rwrapper));
  7523. undo_s.add_action(
  7524. QTStr("Undo.Transform")
  7525. .arg(obs_source_get_name(
  7526. GetCurrentSceneSource())),
  7527. undo_redo, undo_redo, undo_data,
  7528. redo_data);
  7529. recent_nudge = false;
  7530. });
  7531. connect(nudge_timer, &QTimer::timeout, nudge_timer,
  7532. &QTimer::deleteLater);
  7533. nudge_timer->setSingleShot(true);
  7534. }
  7535. if (nudge_timer) {
  7536. nudge_timer->stop();
  7537. nudge_timer->start(1000);
  7538. } else {
  7539. blog(LOG_ERROR, "No nudge timer!");
  7540. }
  7541. obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
  7542. }
  7543. void OBSBasic::DeleteProjector(OBSProjector *projector)
  7544. {
  7545. for (size_t i = 0; i < projectors.size(); i++) {
  7546. if (projectors[i] == projector) {
  7547. projectors[i]->deleteLater();
  7548. projectors.erase(projectors.begin() + i);
  7549. break;
  7550. }
  7551. }
  7552. }
  7553. OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
  7554. ProjectorType type)
  7555. {
  7556. /* seriously? 10 monitors? */
  7557. if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
  7558. return nullptr;
  7559. bool closeProjectors = config_get_bool(GetGlobalConfig(), "BasicWindow",
  7560. "CloseExistingProjectors");
  7561. if (closeProjectors && monitor > -1) {
  7562. for (size_t i = projectors.size(); i > 0; i--) {
  7563. size_t idx = i - 1;
  7564. if (projectors[idx]->GetMonitor() == monitor)
  7565. DeleteProjector(projectors[idx]);
  7566. }
  7567. }
  7568. OBSProjector *projector =
  7569. new OBSProjector(nullptr, source, monitor, type);
  7570. projectors.emplace_back(projector);
  7571. return projector;
  7572. }
  7573. void OBSBasic::OpenStudioProgramProjector()
  7574. {
  7575. int monitor = sender()->property("monitor").toInt();
  7576. OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
  7577. }
  7578. void OBSBasic::OpenPreviewProjector()
  7579. {
  7580. int monitor = sender()->property("monitor").toInt();
  7581. OpenProjector(nullptr, monitor, ProjectorType::Preview);
  7582. }
  7583. void OBSBasic::OpenSourceProjector()
  7584. {
  7585. int monitor = sender()->property("monitor").toInt();
  7586. OBSSceneItem item = GetCurrentSceneItem();
  7587. if (!item)
  7588. return;
  7589. OpenProjector(obs_sceneitem_get_source(item), monitor,
  7590. ProjectorType::Source);
  7591. }
  7592. void OBSBasic::OpenMultiviewProjector()
  7593. {
  7594. int monitor = sender()->property("monitor").toInt();
  7595. OpenProjector(nullptr, monitor, ProjectorType::Multiview);
  7596. }
  7597. void OBSBasic::OpenSceneProjector()
  7598. {
  7599. int monitor = sender()->property("monitor").toInt();
  7600. OBSScene scene = GetCurrentScene();
  7601. if (!scene)
  7602. return;
  7603. OpenProjector(obs_scene_get_source(scene), monitor,
  7604. ProjectorType::Scene);
  7605. }
  7606. void OBSBasic::OpenStudioProgramWindow()
  7607. {
  7608. OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
  7609. }
  7610. void OBSBasic::OpenPreviewWindow()
  7611. {
  7612. OpenProjector(nullptr, -1, ProjectorType::Preview);
  7613. }
  7614. void OBSBasic::OpenSourceWindow()
  7615. {
  7616. OBSSceneItem item = GetCurrentSceneItem();
  7617. if (!item)
  7618. return;
  7619. OBSSource source = obs_sceneitem_get_source(item);
  7620. OpenProjector(obs_sceneitem_get_source(item), -1,
  7621. ProjectorType::Source);
  7622. }
  7623. void OBSBasic::OpenSceneWindow()
  7624. {
  7625. OBSScene scene = GetCurrentScene();
  7626. if (!scene)
  7627. return;
  7628. OBSSource source = obs_scene_get_source(scene);
  7629. OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
  7630. }
  7631. void OBSBasic::OpenSavedProjectors()
  7632. {
  7633. for (SavedProjectorInfo *info : savedProjectorsArray) {
  7634. OpenSavedProjector(info);
  7635. }
  7636. }
  7637. void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
  7638. {
  7639. if (info) {
  7640. OBSProjector *projector = nullptr;
  7641. switch (info->type) {
  7642. case ProjectorType::Source:
  7643. case ProjectorType::Scene: {
  7644. OBSSourceAutoRelease source =
  7645. obs_get_source_by_name(info->name.c_str());
  7646. if (!source)
  7647. return;
  7648. projector = OpenProjector(source, info->monitor,
  7649. info->type);
  7650. break;
  7651. }
  7652. default: {
  7653. projector = OpenProjector(nullptr, info->monitor,
  7654. info->type);
  7655. break;
  7656. }
  7657. }
  7658. if (projector && !info->geometry.empty() && info->monitor < 0) {
  7659. QByteArray byteArray = QByteArray::fromBase64(
  7660. QByteArray(info->geometry.c_str()));
  7661. projector->restoreGeometry(byteArray);
  7662. if (!WindowPositionValid(projector->normalGeometry())) {
  7663. QRect rect = QGuiApplication::primaryScreen()
  7664. ->geometry();
  7665. projector->setGeometry(QStyle::alignedRect(
  7666. Qt::LeftToRight, Qt::AlignCenter,
  7667. size(), rect));
  7668. }
  7669. if (info->alwaysOnTopOverridden)
  7670. projector->SetIsAlwaysOnTop(info->alwaysOnTop,
  7671. true);
  7672. }
  7673. }
  7674. }
  7675. void OBSBasic::on_actionFullscreenInterface_triggered()
  7676. {
  7677. if (!isFullScreen())
  7678. showFullScreen();
  7679. else
  7680. showNormal();
  7681. }
  7682. void OBSBasic::UpdateTitleBar()
  7683. {
  7684. stringstream name;
  7685. const char *profile =
  7686. config_get_string(App()->GlobalConfig(), "Basic", "Profile");
  7687. const char *sceneCollection = config_get_string(
  7688. App()->GlobalConfig(), "Basic", "SceneCollection");
  7689. name << "OBS ";
  7690. if (previewProgramMode)
  7691. name << "Studio ";
  7692. name << App()->GetVersionString(false);
  7693. if (safe_mode)
  7694. name << " (SAFE MODE)";
  7695. if (App()->IsPortableMode())
  7696. name << " - " << Str("TitleBar.PortableMode");
  7697. name << " - " << Str("TitleBar.Profile") << ": " << profile;
  7698. name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
  7699. setWindowTitle(QT_UTF8(name.str().c_str()));
  7700. }
  7701. int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
  7702. {
  7703. char profiles_path[512];
  7704. const char *profile =
  7705. config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
  7706. int ret;
  7707. if (!profile)
  7708. return -1;
  7709. if (!path)
  7710. return -1;
  7711. if (!file)
  7712. file = "";
  7713. ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
  7714. if (ret <= 0)
  7715. return ret;
  7716. if (!*file)
  7717. return snprintf(path, size, "%s/%s", profiles_path, profile);
  7718. return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
  7719. }
  7720. void OBSBasic::on_resetDocks_triggered(bool force)
  7721. {
  7722. /* prune deleted extra docks */
  7723. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7724. if (!oldExtraDocks[i]) {
  7725. oldExtraDocks.removeAt(i);
  7726. oldExtraDockNames.removeAt(i);
  7727. }
  7728. }
  7729. #ifdef BROWSER_AVAILABLE
  7730. if ((oldExtraDocks.size() || extraDocks.size() ||
  7731. extraCustomDocks.size() || extraBrowserDocks.size()) &&
  7732. !force) {
  7733. #else
  7734. if ((oldExtraDocks.size() || extraDocks.size() ||
  7735. extraCustomDocks.size()) &&
  7736. !force) {
  7737. #endif
  7738. QMessageBox::StandardButton button = QMessageBox::question(
  7739. this, QTStr("ResetUIWarning.Title"),
  7740. QTStr("ResetUIWarning.Text"));
  7741. if (button == QMessageBox::No)
  7742. return;
  7743. }
  7744. /* undock/hide/center extra docks */
  7745. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7746. if (oldExtraDocks[i]) {
  7747. oldExtraDocks[i]->setVisible(true);
  7748. oldExtraDocks[i]->setFloating(true);
  7749. oldExtraDocks[i]->move(
  7750. frameGeometry().topLeft() + rect().center() -
  7751. oldExtraDocks[i]->rect().center());
  7752. oldExtraDocks[i]->setVisible(false);
  7753. }
  7754. }
  7755. #define RESET_DOCKLIST(dockList) \
  7756. for (int i = dockList.size() - 1; i >= 0; i--) { \
  7757. dockList[i]->setVisible(true); \
  7758. dockList[i]->setFloating(true); \
  7759. dockList[i]->move(frameGeometry().topLeft() + \
  7760. rect().center() - \
  7761. dockList[i]->rect().center()); \
  7762. dockList[i]->setVisible(false); \
  7763. }
  7764. RESET_DOCKLIST(extraDocks)
  7765. RESET_DOCKLIST(extraCustomDocks)
  7766. #ifdef BROWSER_AVAILABLE
  7767. RESET_DOCKLIST(extraBrowserDocks)
  7768. #endif
  7769. #undef RESET_DOCKLIST
  7770. restoreState(startingDockLayout);
  7771. int cx = width();
  7772. int cy = height();
  7773. int cx22_5 = cx * 225 / 1000;
  7774. int cx5 = cx * 5 / 100;
  7775. int cx21 = cx * 21 / 100;
  7776. cy = cy * 225 / 1000;
  7777. int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21);
  7778. QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
  7779. ui->mixerDock, ui->transitionsDock,
  7780. ui->controlsDock};
  7781. QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx21};
  7782. ui->scenesDock->setVisible(true);
  7783. ui->sourcesDock->setVisible(true);
  7784. ui->mixerDock->setVisible(true);
  7785. ui->transitionsDock->setVisible(true);
  7786. ui->controlsDock->setVisible(true);
  7787. statsDock->setVisible(false);
  7788. statsDock->setFloating(true);
  7789. resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
  7790. resizeDocks(docks, sizes, Qt::Horizontal);
  7791. activateWindow();
  7792. }
  7793. void OBSBasic::on_lockDocks_toggled(bool lock)
  7794. {
  7795. QDockWidget::DockWidgetFeatures features =
  7796. lock ? QDockWidget::NoDockWidgetFeatures
  7797. : (QDockWidget::DockWidgetClosable |
  7798. QDockWidget::DockWidgetMovable |
  7799. QDockWidget::DockWidgetFloatable);
  7800. QDockWidget::DockWidgetFeatures mainFeatures = features;
  7801. mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;
  7802. ui->scenesDock->setFeatures(mainFeatures);
  7803. ui->sourcesDock->setFeatures(mainFeatures);
  7804. ui->mixerDock->setFeatures(mainFeatures);
  7805. ui->transitionsDock->setFeatures(mainFeatures);
  7806. ui->controlsDock->setFeatures(mainFeatures);
  7807. statsDock->setFeatures(features);
  7808. for (int i = extraDocks.size() - 1; i >= 0; i--)
  7809. extraDocks[i]->setFeatures(features);
  7810. for (int i = extraCustomDocks.size() - 1; i >= 0; i--)
  7811. extraCustomDocks[i]->setFeatures(features);
  7812. #ifdef BROWSER_AVAILABLE
  7813. for (int i = extraBrowserDocks.size() - 1; i >= 0; i--)
  7814. extraBrowserDocks[i]->setFeatures(features);
  7815. #endif
  7816. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  7817. if (!oldExtraDocks[i]) {
  7818. oldExtraDocks.removeAt(i);
  7819. oldExtraDockNames.removeAt(i);
  7820. } else {
  7821. oldExtraDocks[i]->setFeatures(features);
  7822. }
  7823. }
  7824. }
  7825. void OBSBasic::on_sideDocks_toggled(bool side)
  7826. {
  7827. if (side) {
  7828. setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);
  7829. setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);
  7830. setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);
  7831. setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea);
  7832. } else {
  7833. setCorner(Qt::TopLeftCorner, Qt::TopDockWidgetArea);
  7834. setCorner(Qt::TopRightCorner, Qt::TopDockWidgetArea);
  7835. setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
  7836. setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
  7837. }
  7838. }
  7839. void OBSBasic::on_resetUI_triggered()
  7840. {
  7841. on_resetDocks_triggered();
  7842. ui->toggleListboxToolbars->setChecked(true);
  7843. ui->toggleContextBar->setChecked(true);
  7844. ui->toggleSourceIcons->setChecked(true);
  7845. ui->toggleStatusBar->setChecked(true);
  7846. ui->scenes->SetGridMode(false);
  7847. ui->actionSceneListMode->setChecked(true);
  7848. }
  7849. void OBSBasic::on_multiviewProjectorWindowed_triggered()
  7850. {
  7851. OpenProjector(nullptr, -1, ProjectorType::Multiview);
  7852. }
  7853. void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
  7854. {
  7855. ui->sourcesToolbar->setVisible(visible);
  7856. ui->scenesToolbar->setVisible(visible);
  7857. ui->mixerToolbar->setVisible(visible);
  7858. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7859. "ShowListboxToolbars", visible);
  7860. }
  7861. void OBSBasic::ShowContextBar()
  7862. {
  7863. on_toggleContextBar_toggled(true);
  7864. ui->toggleContextBar->setChecked(true);
  7865. }
  7866. void OBSBasic::HideContextBar()
  7867. {
  7868. on_toggleContextBar_toggled(false);
  7869. ui->toggleContextBar->setChecked(false);
  7870. }
  7871. void OBSBasic::on_toggleContextBar_toggled(bool visible)
  7872. {
  7873. config_set_bool(App()->GlobalConfig(), "BasicWindow",
  7874. "ShowContextToolbars", visible);
  7875. this->ui->contextContainer->setVisible(visible);
  7876. UpdateContextBar(true);
  7877. }
  7878. void OBSBasic::on_toggleStatusBar_toggled(bool visible)
  7879. {
  7880. ui->statusbar->setVisible(visible);
  7881. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
  7882. visible);
  7883. }
  7884. void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
  7885. {
  7886. ui->sources->SetIconsVisible(visible);
  7887. if (advAudioWindow != nullptr)
  7888. advAudioWindow->SetIconsVisible(visible);
  7889. config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
  7890. visible);
  7891. }
  7892. void OBSBasic::on_actionLockPreview_triggered()
  7893. {
  7894. ui->preview->ToggleLocked();
  7895. ui->actionLockPreview->setChecked(ui->preview->Locked());
  7896. }
  7897. void OBSBasic::on_scalingMenu_aboutToShow()
  7898. {
  7899. obs_video_info ovi;
  7900. obs_get_video_info(&ovi);
  7901. QAction *action = ui->actionScaleCanvas;
  7902. QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
  7903. text = text.arg(QString::number(ovi.base_width),
  7904. QString::number(ovi.base_height));
  7905. action->setText(text);
  7906. action = ui->actionScaleOutput;
  7907. text = QTStr("Basic.MainMenu.Edit.Scale.Output");
  7908. text = text.arg(QString::number(ovi.output_width),
  7909. QString::number(ovi.output_height));
  7910. action->setText(text);
  7911. action->setVisible(!(ovi.output_width == ovi.base_width &&
  7912. ovi.output_height == ovi.base_height));
  7913. UpdatePreviewScalingMenu();
  7914. }
  7915. void OBSBasic::on_actionScaleWindow_triggered()
  7916. {
  7917. ui->preview->SetFixedScaling(false);
  7918. ui->preview->ResetScrollingOffset();
  7919. emit ui->preview->DisplayResized();
  7920. }
  7921. void OBSBasic::on_actionScaleCanvas_triggered()
  7922. {
  7923. ui->preview->SetFixedScaling(true);
  7924. ui->preview->SetScalingLevel(0);
  7925. emit ui->preview->DisplayResized();
  7926. }
  7927. void OBSBasic::on_actionScaleOutput_triggered()
  7928. {
  7929. obs_video_info ovi;
  7930. obs_get_video_info(&ovi);
  7931. ui->preview->SetFixedScaling(true);
  7932. float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
  7933. // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
  7934. int32_t approxScalingLevel =
  7935. int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
  7936. ui->preview->SetScalingLevel(approxScalingLevel);
  7937. ui->preview->SetScalingAmount(scalingAmount);
  7938. emit ui->preview->DisplayResized();
  7939. }
  7940. void OBSBasic::SetShowing(bool showing)
  7941. {
  7942. if (!showing && isVisible()) {
  7943. config_set_string(App()->GlobalConfig(), "BasicWindow",
  7944. "geometry",
  7945. saveGeometry().toBase64().constData());
  7946. /* hide all visible child dialogs */
  7947. visDlgPositions.clear();
  7948. if (!visDialogs.isEmpty()) {
  7949. for (QDialog *dlg : visDialogs) {
  7950. visDlgPositions.append(dlg->pos());
  7951. dlg->hide();
  7952. }
  7953. }
  7954. if (showHide)
  7955. showHide->setText(QTStr("Basic.SystemTray.Show"));
  7956. QTimer::singleShot(0, this, &OBSBasic::hide);
  7957. if (previewEnabled)
  7958. EnablePreviewDisplay(false);
  7959. #ifdef __APPLE__
  7960. EnableOSXDockIcon(false);
  7961. #endif
  7962. } else if (showing && !isVisible()) {
  7963. if (showHide)
  7964. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  7965. QTimer::singleShot(0, this, &OBSBasic::show);
  7966. if (previewEnabled)
  7967. EnablePreviewDisplay(true);
  7968. #ifdef __APPLE__
  7969. EnableOSXDockIcon(true);
  7970. #endif
  7971. /* raise and activate window to ensure it is on top */
  7972. raise();
  7973. activateWindow();
  7974. /* show all child dialogs that was visible earlier */
  7975. if (!visDialogs.isEmpty()) {
  7976. for (int i = 0; i < visDialogs.size(); ++i) {
  7977. QDialog *dlg = visDialogs[i];
  7978. dlg->move(visDlgPositions[i]);
  7979. dlg->show();
  7980. }
  7981. }
  7982. /* Unminimize window if it was hidden to tray instead of task
  7983. * bar. */
  7984. if (sysTrayMinimizeToTray()) {
  7985. Qt::WindowStates state;
  7986. state = windowState() & ~Qt::WindowMinimized;
  7987. state |= Qt::WindowActive;
  7988. setWindowState(state);
  7989. }
  7990. }
  7991. }
  7992. void OBSBasic::ToggleShowHide()
  7993. {
  7994. bool showing = isVisible();
  7995. if (showing) {
  7996. /* check for modal dialogs */
  7997. EnumDialogs();
  7998. if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
  7999. return;
  8000. }
  8001. SetShowing(!showing);
  8002. }
  8003. void OBSBasic::SystemTrayInit()
  8004. {
  8005. #ifdef __APPLE__
  8006. QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg");
  8007. trayIconFile.setIsMask(true);
  8008. #else
  8009. QIcon trayIconFile = QIcon(":/res/images/obs.png");
  8010. #endif
  8011. trayIcon.reset(new QSystemTrayIcon(
  8012. QIcon::fromTheme("obs-tray", trayIconFile), this));
  8013. trayIcon->setToolTip("OBS Studio");
  8014. showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
  8015. sysTrayStream = new QAction(
  8016. StreamingActive() ? QTStr("Basic.Main.StopStreaming")
  8017. : QTStr("Basic.Main.StartStreaming"),
  8018. trayIcon.data());
  8019. sysTrayRecord = new QAction(
  8020. RecordingActive() ? QTStr("Basic.Main.StopRecording")
  8021. : QTStr("Basic.Main.StartRecording"),
  8022. trayIcon.data());
  8023. sysTrayReplayBuffer = new QAction(
  8024. ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer")
  8025. : QTStr("Basic.Main.StartReplayBuffer"),
  8026. trayIcon.data());
  8027. sysTrayVirtualCam = new QAction(
  8028. VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam")
  8029. : QTStr("Basic.Main.StartVirtualCam"),
  8030. trayIcon.data());
  8031. exit = new QAction(QTStr("Exit"), trayIcon.data());
  8032. trayMenu = new QMenu;
  8033. previewProjector = new QMenu(QTStr("PreviewProjector"));
  8034. studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
  8035. AddProjectorMenuMonitors(previewProjector, this,
  8036. &OBSBasic::OpenPreviewProjector);
  8037. AddProjectorMenuMonitors(studioProgramProjector, this,
  8038. &OBSBasic::OpenStudioProgramProjector);
  8039. trayMenu->addAction(showHide);
  8040. trayMenu->addSeparator();
  8041. trayMenu->addMenu(previewProjector);
  8042. trayMenu->addMenu(studioProgramProjector);
  8043. trayMenu->addSeparator();
  8044. trayMenu->addAction(sysTrayStream);
  8045. trayMenu->addAction(sysTrayRecord);
  8046. trayMenu->addAction(sysTrayReplayBuffer);
  8047. trayMenu->addAction(sysTrayVirtualCam);
  8048. trayMenu->addSeparator();
  8049. trayMenu->addAction(exit);
  8050. trayIcon->setContextMenu(trayMenu);
  8051. trayIcon->show();
  8052. if (outputHandler && !outputHandler->replayBuffer)
  8053. sysTrayReplayBuffer->setEnabled(false);
  8054. sysTrayVirtualCam->setEnabled(vcamEnabled);
  8055. if (Active())
  8056. OnActivate(true);
  8057. connect(trayIcon.data(), &QSystemTrayIcon::activated, this,
  8058. &OBSBasic::IconActivated);
  8059. connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide);
  8060. connect(sysTrayStream, &QAction::triggered, this,
  8061. &OBSBasic::on_streamButton_clicked);
  8062. connect(sysTrayRecord, &QAction::triggered, this,
  8063. &OBSBasic::on_recordButton_clicked);
  8064. connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
  8065. &OBSBasic::ReplayBufferClicked);
  8066. connect(sysTrayVirtualCam.data(), &QAction::triggered, this,
  8067. &OBSBasic::VCamButtonClicked);
  8068. connect(exit, &QAction::triggered, this, &OBSBasic::close);
  8069. }
  8070. void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
  8071. {
  8072. // Refresh projector list
  8073. previewProjector->clear();
  8074. studioProgramProjector->clear();
  8075. AddProjectorMenuMonitors(previewProjector, this,
  8076. &OBSBasic::OpenPreviewProjector);
  8077. AddProjectorMenuMonitors(studioProgramProjector, this,
  8078. &OBSBasic::OpenStudioProgramProjector);
  8079. #ifdef __APPLE__
  8080. UNUSED_PARAMETER(reason);
  8081. #else
  8082. if (reason == QSystemTrayIcon::Trigger) {
  8083. EnablePreviewDisplay(previewEnabled && !isVisible());
  8084. ToggleShowHide();
  8085. }
  8086. #endif
  8087. }
  8088. void OBSBasic::SysTrayNotify(const QString &text,
  8089. QSystemTrayIcon::MessageIcon n)
  8090. {
  8091. if (trayIcon && trayIcon->isVisible() &&
  8092. QSystemTrayIcon::supportsMessages()) {
  8093. QSystemTrayIcon::MessageIcon icon =
  8094. QSystemTrayIcon::MessageIcon(n);
  8095. trayIcon->showMessage("OBS Studio", text, icon, 10000);
  8096. }
  8097. }
  8098. void OBSBasic::SystemTray(bool firstStarted)
  8099. {
  8100. if (!QSystemTrayIcon::isSystemTrayAvailable())
  8101. return;
  8102. if (!trayIcon && !firstStarted)
  8103. return;
  8104. bool sysTrayWhenStarted = config_get_bool(
  8105. GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
  8106. bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
  8107. "SysTrayEnabled");
  8108. if (firstStarted)
  8109. SystemTrayInit();
  8110. if (!sysTrayEnabled) {
  8111. trayIcon->hide();
  8112. } else {
  8113. trayIcon->show();
  8114. if (firstStarted && (sysTrayWhenStarted || opt_minimize_tray)) {
  8115. EnablePreviewDisplay(false);
  8116. #ifdef __APPLE__
  8117. EnableOSXDockIcon(false);
  8118. #endif
  8119. opt_minimize_tray = false;
  8120. }
  8121. }
  8122. if (isVisible())
  8123. showHide->setText(QTStr("Basic.SystemTray.Hide"));
  8124. else
  8125. showHide->setText(QTStr("Basic.SystemTray.Show"));
  8126. }
  8127. bool OBSBasic::sysTrayMinimizeToTray()
  8128. {
  8129. return config_get_bool(GetGlobalConfig(), "BasicWindow",
  8130. "SysTrayMinimizeToTray");
  8131. }
  8132. void OBSBasic::on_actionMainUndo_triggered()
  8133. {
  8134. undo_s.undo();
  8135. }
  8136. void OBSBasic::on_actionMainRedo_triggered()
  8137. {
  8138. undo_s.redo();
  8139. }
  8140. void OBSBasic::on_actionCopySource_triggered()
  8141. {
  8142. clipboard.clear();
  8143. for (auto &selectedSource : GetAllSelectedSourceItems()) {
  8144. OBSSceneItem item = ui->sources->Get(selectedSource.row());
  8145. if (!item)
  8146. continue;
  8147. OBSSource source = obs_sceneitem_get_source(item);
  8148. SourceCopyInfo copyInfo;
  8149. copyInfo.weak_source = OBSGetWeakRef(source);
  8150. obs_sceneitem_get_info(item, &copyInfo.transform);
  8151. obs_sceneitem_get_crop(item, &copyInfo.crop);
  8152. copyInfo.blend_method = obs_sceneitem_get_blending_method(item);
  8153. copyInfo.blend_mode = obs_sceneitem_get_blending_mode(item);
  8154. copyInfo.visible = obs_sceneitem_visible(item);
  8155. clipboard.push_back(copyInfo);
  8156. }
  8157. UpdateEditMenu();
  8158. }
  8159. void OBSBasic::on_actionPasteRef_triggered()
  8160. {
  8161. OBSSource scene_source = GetCurrentSceneSource();
  8162. OBSData undo_data = BackupScene(scene_source);
  8163. OBSScene scene = GetCurrentScene();
  8164. undo_s.push_disabled();
  8165. for (size_t i = clipboard.size(); i > 0; i--) {
  8166. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8167. OBSSource source = OBSGetStrongRef(copyInfo.weak_source);
  8168. if (!source)
  8169. continue;
  8170. const char *name = obs_source_get_name(source);
  8171. /* do not allow duplicate refs of the same group in the same
  8172. * scene */
  8173. if (!!obs_scene_get_group(scene, name)) {
  8174. continue;
  8175. }
  8176. OBSBasicSourceSelect::SourcePaste(copyInfo, false);
  8177. }
  8178. undo_s.pop_disabled();
  8179. QString action_name = QTStr("Undo.PasteSourceRef");
  8180. const char *scene_name = obs_source_get_name(scene_source);
  8181. OBSData redo_data = BackupScene(scene_source);
  8182. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8183. redo_data);
  8184. }
  8185. void OBSBasic::on_actionPasteDup_triggered()
  8186. {
  8187. OBSSource scene_source = GetCurrentSceneSource();
  8188. OBSData undo_data = BackupScene(scene_source);
  8189. undo_s.push_disabled();
  8190. for (size_t i = clipboard.size(); i > 0; i--) {
  8191. SourceCopyInfo &copyInfo = clipboard[i - 1];
  8192. OBSBasicSourceSelect::SourcePaste(copyInfo, true);
  8193. }
  8194. undo_s.pop_disabled();
  8195. QString action_name = QTStr("Undo.PasteSource");
  8196. const char *scene_name = obs_source_get_name(scene_source);
  8197. OBSData redo_data = BackupScene(scene_source);
  8198. CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data,
  8199. redo_data);
  8200. }
  8201. void OBSBasic::AudioMixerCopyFilters()
  8202. {
  8203. QAction *action = reinterpret_cast<QAction *>(sender());
  8204. VolControl *vol = action->property("volControl").value<VolControl *>();
  8205. obs_source_t *source = vol->GetSource();
  8206. copyFiltersSource = obs_source_get_weak_source(source);
  8207. }
  8208. void OBSBasic::AudioMixerPasteFilters()
  8209. {
  8210. QAction *action = reinterpret_cast<QAction *>(sender());
  8211. VolControl *vol = action->property("volControl").value<VolControl *>();
  8212. obs_source_t *dstSource = vol->GetSource();
  8213. OBSSourceAutoRelease source =
  8214. obs_weak_source_get_source(copyFiltersSource);
  8215. if (source == dstSource)
  8216. return;
  8217. obs_source_copy_filters(dstSource, source);
  8218. }
  8219. void OBSBasic::SceneCopyFilters()
  8220. {
  8221. copyFiltersSource = obs_source_get_weak_source(GetCurrentSceneSource());
  8222. }
  8223. void OBSBasic::ScenePasteFilters()
  8224. {
  8225. OBSSourceAutoRelease source =
  8226. obs_weak_source_get_source(copyFiltersSource);
  8227. OBSSource dstSource = GetCurrentSceneSource();
  8228. if (source == dstSource)
  8229. return;
  8230. obs_source_copy_filters(dstSource, source);
  8231. }
  8232. void OBSBasic::on_actionCopyFilters_triggered()
  8233. {
  8234. OBSSceneItem item = GetCurrentSceneItem();
  8235. if (!item)
  8236. return;
  8237. OBSSource source = obs_sceneitem_get_source(item);
  8238. copyFiltersSource = obs_source_get_weak_source(source);
  8239. ui->actionPasteFilters->setEnabled(true);
  8240. }
  8241. void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text,
  8242. obs_source_t *source,
  8243. obs_data_array_t *undo_array,
  8244. obs_data_array_t *redo_array)
  8245. {
  8246. auto undo_redo = [this](const std::string &json) {
  8247. OBSDataAutoRelease data =
  8248. obs_data_create_from_json(json.c_str());
  8249. OBSDataArrayAutoRelease array =
  8250. obs_data_get_array(data, "array");
  8251. OBSSourceAutoRelease source = obs_get_source_by_uuid(
  8252. obs_data_get_string(data, "uuid"));
  8253. obs_source_restore_filters(source, array);
  8254. if (filters)
  8255. filters->UpdateSource(source);
  8256. };
  8257. const char *uuid = obs_source_get_uuid(source);
  8258. OBSDataAutoRelease undo_data = obs_data_create();
  8259. OBSDataAutoRelease redo_data = obs_data_create();
  8260. obs_data_set_array(undo_data, "array", undo_array);
  8261. obs_data_set_array(redo_data, "array", redo_array);
  8262. obs_data_set_string(undo_data, "uuid", uuid);
  8263. obs_data_set_string(redo_data, "uuid", uuid);
  8264. undo_s.add_action(text, undo_redo, undo_redo,
  8265. obs_data_get_json(undo_data),
  8266. obs_data_get_json(redo_data));
  8267. }
  8268. void OBSBasic::on_actionPasteFilters_triggered()
  8269. {
  8270. OBSSourceAutoRelease source =
  8271. obs_weak_source_get_source(copyFiltersSource);
  8272. OBSSceneItem sceneItem = GetCurrentSceneItem();
  8273. OBSSource dstSource = obs_sceneitem_get_source(sceneItem);
  8274. if (source == dstSource)
  8275. return;
  8276. OBSDataArrayAutoRelease undo_array =
  8277. obs_source_backup_filters(dstSource);
  8278. obs_source_copy_filters(dstSource, source);
  8279. OBSDataArrayAutoRelease redo_array =
  8280. obs_source_backup_filters(dstSource);
  8281. const char *srcName = obs_source_get_name(source);
  8282. const char *dstName = obs_source_get_name(dstSource);
  8283. QString text =
  8284. QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName);
  8285. CreateFilterPasteUndoRedoAction(text, dstSource, undo_array,
  8286. redo_array);
  8287. }
  8288. static void ConfirmColor(SourceTree *sources, const QColor &color,
  8289. QModelIndexList selectedItems)
  8290. {
  8291. for (int x = 0; x < selectedItems.count(); x++) {
  8292. SourceTreeItem *treeItem =
  8293. sources->GetItemWidget(selectedItems[x].row());
  8294. treeItem->setStyleSheet("background: " +
  8295. color.name(QColor::HexArgb));
  8296. treeItem->style()->unpolish(treeItem);
  8297. treeItem->style()->polish(treeItem);
  8298. OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
  8299. OBSDataAutoRelease privData =
  8300. obs_sceneitem_get_private_settings(sceneItem);
  8301. obs_data_set_int(privData, "color-preset", 1);
  8302. obs_data_set_string(privData, "color",
  8303. QT_TO_UTF8(color.name(QColor::HexArgb)));
  8304. }
  8305. }
  8306. void OBSBasic::ColorChange()
  8307. {
  8308. QModelIndexList selectedItems =
  8309. ui->sources->selectionModel()->selectedIndexes();
  8310. QAction *action = qobject_cast<QAction *>(sender());
  8311. QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
  8312. if (selectedItems.count() == 0)
  8313. return;
  8314. if (colorButton) {
  8315. int preset = colorButton->property("bgColor").value<int>();
  8316. for (int x = 0; x < selectedItems.count(); x++) {
  8317. SourceTreeItem *treeItem = ui->sources->GetItemWidget(
  8318. selectedItems[x].row());
  8319. treeItem->setStyleSheet("");
  8320. treeItem->setProperty("bgColor", preset);
  8321. treeItem->style()->unpolish(treeItem);
  8322. treeItem->style()->polish(treeItem);
  8323. OBSSceneItem sceneItem =
  8324. ui->sources->Get(selectedItems[x].row());
  8325. OBSDataAutoRelease privData =
  8326. obs_sceneitem_get_private_settings(sceneItem);
  8327. obs_data_set_int(privData, "color-preset", preset + 1);
  8328. obs_data_set_string(privData, "color", "");
  8329. }
  8330. for (int i = 1; i < 9; i++) {
  8331. stringstream button;
  8332. button << "preset" << i;
  8333. QPushButton *cButton =
  8334. colorButton->parentWidget()
  8335. ->findChild<QPushButton *>(
  8336. button.str().c_str());
  8337. cButton->setStyleSheet("border: 1px solid black");
  8338. }
  8339. colorButton->setStyleSheet("border: 2px solid black");
  8340. } else if (action) {
  8341. int preset = action->property("bgColor").value<int>();
  8342. if (preset == 1) {
  8343. OBSSceneItem curSceneItem = GetCurrentSceneItem();
  8344. SourceTreeItem *curTreeItem =
  8345. GetItemWidgetFromSceneItem(curSceneItem);
  8346. OBSDataAutoRelease curPrivData =
  8347. obs_sceneitem_get_private_settings(
  8348. curSceneItem);
  8349. int oldPreset =
  8350. obs_data_get_int(curPrivData, "color-preset");
  8351. const QString oldSheet = curTreeItem->styleSheet();
  8352. auto liveChangeColor = [=](const QColor &color) {
  8353. if (color.isValid()) {
  8354. curTreeItem->setStyleSheet(
  8355. "background: " +
  8356. color.name(QColor::HexArgb));
  8357. }
  8358. };
  8359. auto changedColor = [=](const QColor &color) {
  8360. if (color.isValid()) {
  8361. ConfirmColor(ui->sources, color,
  8362. selectedItems);
  8363. }
  8364. };
  8365. auto rejected = [=]() {
  8366. if (oldPreset == 1) {
  8367. curTreeItem->setStyleSheet(oldSheet);
  8368. curTreeItem->setProperty("bgColor", 0);
  8369. } else if (oldPreset == 0) {
  8370. curTreeItem->setStyleSheet(
  8371. "background: none");
  8372. curTreeItem->setProperty("bgColor", 0);
  8373. } else {
  8374. curTreeItem->setStyleSheet("");
  8375. curTreeItem->setProperty("bgColor",
  8376. oldPreset - 1);
  8377. }
  8378. curTreeItem->style()->unpolish(curTreeItem);
  8379. curTreeItem->style()->polish(curTreeItem);
  8380. };
  8381. QColorDialog::ColorDialogOptions options =
  8382. QColorDialog::ShowAlphaChannel;
  8383. const char *oldColor =
  8384. obs_data_get_string(curPrivData, "color");
  8385. const char *customColor = *oldColor != 0 ? oldColor
  8386. : "#55FF0000";
  8387. #ifdef __linux__
  8388. // TODO: Revisit hang on Ubuntu with native dialog
  8389. options |= QColorDialog::DontUseNativeDialog;
  8390. #endif
  8391. QColorDialog *colorDialog = new QColorDialog(this);
  8392. colorDialog->setOptions(options);
  8393. colorDialog->setCurrentColor(QColor(customColor));
  8394. connect(colorDialog, &QColorDialog::currentColorChanged,
  8395. liveChangeColor);
  8396. connect(colorDialog, &QColorDialog::colorSelected,
  8397. changedColor);
  8398. connect(colorDialog, &QColorDialog::rejected, rejected);
  8399. colorDialog->open();
  8400. } else {
  8401. for (int x = 0; x < selectedItems.count(); x++) {
  8402. SourceTreeItem *treeItem =
  8403. ui->sources->GetItemWidget(
  8404. selectedItems[x].row());
  8405. treeItem->setStyleSheet("background: none");
  8406. treeItem->setProperty("bgColor", preset);
  8407. treeItem->style()->unpolish(treeItem);
  8408. treeItem->style()->polish(treeItem);
  8409. OBSSceneItem sceneItem = ui->sources->Get(
  8410. selectedItems[x].row());
  8411. OBSDataAutoRelease privData =
  8412. obs_sceneitem_get_private_settings(
  8413. sceneItem);
  8414. obs_data_set_int(privData, "color-preset",
  8415. preset);
  8416. obs_data_set_string(privData, "color", "");
  8417. }
  8418. }
  8419. }
  8420. }
  8421. SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
  8422. {
  8423. int i = 0;
  8424. SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
  8425. OBSSceneItem item = ui->sources->Get(i);
  8426. int64_t id = obs_sceneitem_get_id(sceneItem);
  8427. while (treeItem && obs_sceneitem_get_id(item) != id) {
  8428. i++;
  8429. treeItem = ui->sources->GetItemWidget(i);
  8430. item = ui->sources->Get(i);
  8431. }
  8432. if (treeItem)
  8433. return treeItem;
  8434. return nullptr;
  8435. }
  8436. void OBSBasic::on_autoConfigure_triggered()
  8437. {
  8438. AutoConfig test(this);
  8439. test.setModal(true);
  8440. test.show();
  8441. test.exec();
  8442. }
  8443. void OBSBasic::on_stats_triggered()
  8444. {
  8445. if (!stats.isNull()) {
  8446. stats->show();
  8447. stats->raise();
  8448. return;
  8449. }
  8450. OBSBasicStats *statsDlg;
  8451. statsDlg = new OBSBasicStats(nullptr);
  8452. statsDlg->show();
  8453. stats = statsDlg;
  8454. }
  8455. void OBSBasic::on_actionShowAbout_triggered()
  8456. {
  8457. if (about)
  8458. about->close();
  8459. about = new OBSAbout(this);
  8460. about->show();
  8461. about->setAttribute(Qt::WA_DeleteOnClose, true);
  8462. }
  8463. void OBSBasic::ResizeOutputSizeOfSource()
  8464. {
  8465. if (obs_video_active())
  8466. return;
  8467. QMessageBox resize_output(this);
  8468. resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
  8469. QTStr("ResizeOutputSizeOfSource.Continue"));
  8470. QAbstractButton *Yes =
  8471. resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
  8472. resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
  8473. resize_output.setIcon(QMessageBox::Warning);
  8474. resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
  8475. resize_output.exec();
  8476. if (resize_output.clickedButton() != Yes)
  8477. return;
  8478. OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());
  8479. int width = obs_source_get_width(source);
  8480. int height = obs_source_get_height(source);
  8481. config_set_uint(basicConfig, "Video", "BaseCX", width);
  8482. config_set_uint(basicConfig, "Video", "BaseCY", height);
  8483. config_set_uint(basicConfig, "Video", "OutputCX", width);
  8484. config_set_uint(basicConfig, "Video", "OutputCY", height);
  8485. ResetVideo();
  8486. ResetOutputs();
  8487. config_save_safe(basicConfig, "tmp", nullptr);
  8488. on_actionFitToScreen_triggered();
  8489. }
  8490. QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
  8491. {
  8492. // Prevent the object name from being changed
  8493. connect(dock, &QObject::objectNameChanged, this,
  8494. &OBSBasic::RepairOldExtraDockName);
  8495. #ifdef BROWSER_AVAILABLE
  8496. QAction *action = new QAction(dock->windowTitle(), ui->menuDocks);
  8497. if (!extraBrowserMenuDocksSeparator.isNull())
  8498. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8499. action);
  8500. else
  8501. ui->menuDocks->addAction(action);
  8502. #else
  8503. QAction *action = ui->menuDocks->addAction(dock->windowTitle());
  8504. #endif
  8505. action->setCheckable(true);
  8506. assignDockToggle(dock, action);
  8507. oldExtraDocks.push_back(dock);
  8508. oldExtraDockNames.push_back(dock->objectName());
  8509. bool lock = ui->lockDocks->isChecked();
  8510. QDockWidget::DockWidgetFeatures features =
  8511. lock ? QDockWidget::NoDockWidgetFeatures
  8512. : (QDockWidget::DockWidgetClosable |
  8513. QDockWidget::DockWidgetMovable |
  8514. QDockWidget::DockWidgetFloatable);
  8515. dock->setFeatures(features);
  8516. /* prune deleted docks */
  8517. for (int i = oldExtraDocks.size() - 1; i >= 0; i--) {
  8518. if (!oldExtraDocks[i]) {
  8519. oldExtraDocks.removeAt(i);
  8520. oldExtraDockNames.removeAt(i);
  8521. }
  8522. }
  8523. return action;
  8524. }
  8525. void OBSBasic::RepairOldExtraDockName()
  8526. {
  8527. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8528. int idx = oldExtraDocks.indexOf(dock);
  8529. QSignalBlocker block(dock);
  8530. if (idx == -1) {
  8531. blog(LOG_WARNING, "A dock got its object name changed");
  8532. return;
  8533. }
  8534. blog(LOG_WARNING, "The dock '%s' got its object name restored",
  8535. QT_TO_UTF8(oldExtraDockNames[idx]));
  8536. dock->setObjectName(oldExtraDockNames[idx]);
  8537. }
  8538. void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area,
  8539. bool extraBrowser)
  8540. {
  8541. if (dock->objectName().isEmpty())
  8542. return;
  8543. bool lock = ui->lockDocks->isChecked();
  8544. QDockWidget::DockWidgetFeatures features =
  8545. lock ? QDockWidget::NoDockWidgetFeatures
  8546. : (QDockWidget::DockWidgetClosable |
  8547. QDockWidget::DockWidgetMovable |
  8548. QDockWidget::DockWidgetFloatable);
  8549. setupDockAction(dock);
  8550. dock->setFeatures(features);
  8551. addDockWidget(area, dock);
  8552. #ifdef BROWSER_AVAILABLE
  8553. if (extraBrowser && extraBrowserMenuDocksSeparator.isNull())
  8554. extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator();
  8555. if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull())
  8556. ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator,
  8557. dock->toggleViewAction());
  8558. else
  8559. ui->menuDocks->addAction(dock->toggleViewAction());
  8560. if (extraBrowser)
  8561. return;
  8562. #else
  8563. UNUSED_PARAMETER(extraBrowser);
  8564. ui->menuDocks->addAction(dock->toggleViewAction());
  8565. #endif
  8566. extraDockNames.push_back(dock->objectName());
  8567. extraDocks.push_back(QSharedPointer<QDockWidget>(dock));
  8568. }
  8569. void OBSBasic::RemoveDockWidget(const QString &name)
  8570. {
  8571. if (extraDockNames.contains(name)) {
  8572. int idx = extraDockNames.indexOf(name);
  8573. extraDockNames.removeAt(idx);
  8574. extraDocks[idx].clear();
  8575. extraDocks.removeAt(idx);
  8576. } else if (extraCustomDockNames.contains(name)) {
  8577. int idx = extraCustomDockNames.indexOf(name);
  8578. extraCustomDockNames.removeAt(idx);
  8579. removeDockWidget(extraCustomDocks[idx]);
  8580. extraCustomDocks.removeAt(idx);
  8581. }
  8582. }
  8583. bool OBSBasic::IsDockObjectNameUsed(const QString &name)
  8584. {
  8585. QStringList list;
  8586. list << "scenesDock"
  8587. << "sourcesDock"
  8588. << "mixerDock"
  8589. << "transitionsDock"
  8590. << "controlsDock"
  8591. << "statsDock";
  8592. list << oldExtraDockNames;
  8593. list << extraDockNames;
  8594. list << extraCustomDockNames;
  8595. return list.contains(name);
  8596. }
  8597. void OBSBasic::AddCustomDockWidget(QDockWidget *dock)
  8598. {
  8599. // Prevent the object name from being changed
  8600. connect(dock, &QObject::objectNameChanged, this,
  8601. &OBSBasic::RepairCustomExtraDockName);
  8602. bool lock = ui->lockDocks->isChecked();
  8603. QDockWidget::DockWidgetFeatures features =
  8604. lock ? QDockWidget::NoDockWidgetFeatures
  8605. : (QDockWidget::DockWidgetClosable |
  8606. QDockWidget::DockWidgetMovable |
  8607. QDockWidget::DockWidgetFloatable);
  8608. dock->setFeatures(features);
  8609. addDockWidget(Qt::RightDockWidgetArea, dock);
  8610. extraCustomDockNames.push_back(dock->objectName());
  8611. extraCustomDocks.push_back(dock);
  8612. }
  8613. void OBSBasic::RepairCustomExtraDockName()
  8614. {
  8615. QDockWidget *dock = reinterpret_cast<QDockWidget *>(sender());
  8616. int idx = extraCustomDocks.indexOf(dock);
  8617. QSignalBlocker block(dock);
  8618. if (idx == -1) {
  8619. blog(LOG_WARNING, "A custom dock got its object name changed");
  8620. return;
  8621. }
  8622. blog(LOG_WARNING, "The custom dock '%s' got its object name restored",
  8623. QT_TO_UTF8(extraCustomDockNames[idx]));
  8624. dock->setObjectName(extraCustomDockNames[idx]);
  8625. }
  8626. OBSBasic *OBSBasic::Get()
  8627. {
  8628. return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  8629. }
  8630. bool OBSBasic::StreamingActive()
  8631. {
  8632. if (!outputHandler)
  8633. return false;
  8634. return outputHandler->StreamingActive();
  8635. }
  8636. bool OBSBasic::RecordingActive()
  8637. {
  8638. if (!outputHandler)
  8639. return false;
  8640. return outputHandler->RecordingActive();
  8641. }
  8642. bool OBSBasic::ReplayBufferActive()
  8643. {
  8644. if (!outputHandler)
  8645. return false;
  8646. return outputHandler->ReplayBufferActive();
  8647. }
  8648. bool OBSBasic::VirtualCamActive()
  8649. {
  8650. if (!outputHandler)
  8651. return false;
  8652. return outputHandler->VirtualCamActive();
  8653. }
  8654. SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
  8655. : QStyledItemDelegate(parent)
  8656. {
  8657. }
  8658. void SceneRenameDelegate::setEditorData(QWidget *editor,
  8659. const QModelIndex &index) const
  8660. {
  8661. QStyledItemDelegate::setEditorData(editor, index);
  8662. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8663. if (lineEdit)
  8664. lineEdit->selectAll();
  8665. }
  8666. bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
  8667. {
  8668. if (event->type() == QEvent::KeyPress) {
  8669. QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
  8670. if (keyEvent->key() == Qt::Key_Escape) {
  8671. QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
  8672. if (lineEdit)
  8673. lineEdit->undo();
  8674. }
  8675. }
  8676. return QStyledItemDelegate::eventFilter(editor, event);
  8677. }
  8678. void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
  8679. {
  8680. if (!error.isEmpty())
  8681. return;
  8682. patronJson = QT_TO_UTF8(text);
  8683. }
  8684. void OBSBasic::PauseRecording()
  8685. {
  8686. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8687. os_atomic_load_bool(&recording_paused))
  8688. return;
  8689. obs_output_t *output = outputHandler->fileOutput;
  8690. if (obs_output_pause(output, true)) {
  8691. pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
  8692. pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
  8693. pause->blockSignals(true);
  8694. pause->setChecked(true);
  8695. pause->blockSignals(false);
  8696. ui->statusbar->RecordingPaused();
  8697. TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused);
  8698. if (trayIcon && trayIcon->isVisible()) {
  8699. #ifdef __APPLE__
  8700. QIcon trayIconFile =
  8701. QIcon(":/res/images/obs_paused_macos.svg");
  8702. trayIconFile.setIsMask(true);
  8703. #else
  8704. QIcon trayIconFile =
  8705. QIcon(":/res/images/obs_paused.png");
  8706. #endif
  8707. trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused",
  8708. trayIconFile));
  8709. }
  8710. os_atomic_set_bool(&recording_paused, true);
  8711. auto replay = replayBufferButton ? replayBufferButton->second()
  8712. : nullptr;
  8713. if (replay)
  8714. replay->setEnabled(false);
  8715. if (api)
  8716. api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);
  8717. if (os_atomic_load_bool(&replaybuf_active))
  8718. ShowReplayBufferPauseWarning();
  8719. }
  8720. }
  8721. void OBSBasic::UnpauseRecording()
  8722. {
  8723. if (!pause || !outputHandler || !outputHandler->fileOutput ||
  8724. !os_atomic_load_bool(&recording_paused))
  8725. return;
  8726. obs_output_t *output = outputHandler->fileOutput;
  8727. if (obs_output_pause(output, false)) {
  8728. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8729. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8730. pause->blockSignals(true);
  8731. pause->setChecked(false);
  8732. pause->blockSignals(false);
  8733. ui->statusbar->RecordingUnpaused();
  8734. TaskbarOverlaySetStatus(TaskbarOverlayStatusActive);
  8735. if (trayIcon && trayIcon->isVisible()) {
  8736. #ifdef __APPLE__
  8737. QIcon trayIconFile =
  8738. QIcon(":/res/images/tray_active_macos.svg");
  8739. trayIconFile.setIsMask(true);
  8740. #else
  8741. QIcon trayIconFile =
  8742. QIcon(":/res/images/tray_active.png");
  8743. #endif
  8744. trayIcon->setIcon(QIcon::fromTheme("obs-tray-active",
  8745. trayIconFile));
  8746. }
  8747. os_atomic_set_bool(&recording_paused, false);
  8748. auto replay = replayBufferButton ? replayBufferButton->second()
  8749. : nullptr;
  8750. if (replay)
  8751. replay->setEnabled(true);
  8752. if (api)
  8753. api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
  8754. }
  8755. }
  8756. void OBSBasic::PauseToggled()
  8757. {
  8758. if (!pause || !outputHandler || !outputHandler->fileOutput)
  8759. return;
  8760. obs_output_t *output = outputHandler->fileOutput;
  8761. bool enable = !obs_output_paused(output);
  8762. if (enable)
  8763. PauseRecording();
  8764. else
  8765. UnpauseRecording();
  8766. }
  8767. void OBSBasic::UpdatePause(bool activate)
  8768. {
  8769. if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
  8770. pause.reset();
  8771. return;
  8772. }
  8773. const char *mode = config_get_string(basicConfig, "Output", "Mode");
  8774. bool adv = astrcmpi(mode, "Advanced") == 0;
  8775. bool shared;
  8776. if (adv) {
  8777. const char *recType =
  8778. config_get_string(basicConfig, "AdvOut", "RecType");
  8779. if (astrcmpi(recType, "FFmpeg") == 0) {
  8780. shared = config_get_bool(basicConfig, "AdvOut",
  8781. "FFOutputToFile");
  8782. } else {
  8783. const char *recordEncoder = config_get_string(
  8784. basicConfig, "AdvOut", "RecEncoder");
  8785. shared = astrcmpi(recordEncoder, "none") == 0;
  8786. }
  8787. } else {
  8788. const char *quality = config_get_string(
  8789. basicConfig, "SimpleOutput", "RecQuality");
  8790. shared = strcmp(quality, "Stream") == 0;
  8791. }
  8792. if (!shared) {
  8793. pause.reset(new QPushButton());
  8794. pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
  8795. pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
  8796. pause->setCheckable(true);
  8797. pause->setChecked(false);
  8798. pause->setProperty("themeID",
  8799. QVariant(QStringLiteral("pauseIconSmall")));
  8800. QSizePolicy sp;
  8801. sp.setHeightForWidth(true);
  8802. pause->setSizePolicy(sp);
  8803. connect(pause.data(), &QAbstractButton::clicked, this,
  8804. &OBSBasic::PauseToggled);
  8805. ui->recordingLayout->addWidget(pause.data());
  8806. } else {
  8807. pause.reset();
  8808. }
  8809. }
  8810. void OBSBasic::UpdateReplayBuffer(bool activate)
  8811. {
  8812. if (!activate || !outputHandler ||
  8813. !outputHandler->ReplayBufferActive()) {
  8814. replayBufferButton->removeIcon();
  8815. return;
  8816. }
  8817. replayBufferButton->addIcon(QTStr("Basic.Main.SaveReplay"),
  8818. QStringLiteral("replayIconSmall"),
  8819. &OBSBasic::ReplayBufferSave);
  8820. }
  8821. #define MBYTE (1024ULL * 1024ULL)
  8822. #define MBYTES_LEFT_STOP_REC 50ULL
  8823. #define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)
  8824. const char *OBSBasic::GetCurrentOutputPath()
  8825. {
  8826. const char *path = nullptr;
  8827. const char *mode = config_get_string(Config(), "Output", "Mode");
  8828. if (strcmp(mode, "Advanced") == 0) {
  8829. const char *advanced_mode =
  8830. config_get_string(Config(), "AdvOut", "RecType");
  8831. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8832. path = config_get_string(Config(), "AdvOut",
  8833. "FFFilePath");
  8834. } else {
  8835. path = config_get_string(Config(), "AdvOut",
  8836. "RecFilePath");
  8837. }
  8838. } else {
  8839. path = config_get_string(Config(), "SimpleOutput", "FilePath");
  8840. }
  8841. return path;
  8842. }
  8843. void OBSBasic::OutputPathInvalidMessage()
  8844. {
  8845. blog(LOG_ERROR, "Recording stopped because of bad output path");
  8846. OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
  8847. QTStr("Output.BadPath.Text"));
  8848. }
  8849. bool OBSBasic::OutputPathValid()
  8850. {
  8851. const char *mode = config_get_string(Config(), "Output", "Mode");
  8852. if (strcmp(mode, "Advanced") == 0) {
  8853. const char *advanced_mode =
  8854. config_get_string(Config(), "AdvOut", "RecType");
  8855. if (strcmp(advanced_mode, "FFmpeg") == 0) {
  8856. bool is_local = config_get_bool(Config(), "AdvOut",
  8857. "FFOutputToFile");
  8858. if (!is_local)
  8859. return true;
  8860. }
  8861. }
  8862. const char *path = GetCurrentOutputPath();
  8863. return path && *path && QDir(path).exists();
  8864. }
  8865. void OBSBasic::DiskSpaceMessage()
  8866. {
  8867. blog(LOG_ERROR, "Recording stopped because of low disk space");
  8868. OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
  8869. QTStr("Output.RecordNoSpace.Msg"));
  8870. }
  8871. bool OBSBasic::LowDiskSpace()
  8872. {
  8873. const char *path;
  8874. path = GetCurrentOutputPath();
  8875. if (!path)
  8876. return false;
  8877. uint64_t num_bytes = os_get_free_disk_space(path);
  8878. if (num_bytes < (MAX_BYTES_LEFT))
  8879. return true;
  8880. else
  8881. return false;
  8882. }
  8883. void OBSBasic::CheckDiskSpaceRemaining()
  8884. {
  8885. if (LowDiskSpace()) {
  8886. StopRecording();
  8887. StopReplayBuffer();
  8888. DiskSpaceMessage();
  8889. }
  8890. }
  8891. void OBSBasic::ResetStatsHotkey()
  8892. {
  8893. QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();
  8894. foreach(OBSBasicStats * s, list) s->Reset();
  8895. }
  8896. void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos)
  8897. {
  8898. QWidget *widget = childAt(pos);
  8899. const char *className = nullptr;
  8900. QString objName;
  8901. if (widget != nullptr) {
  8902. className = widget->metaObject()->className();
  8903. objName = widget->objectName();
  8904. }
  8905. QPoint globalPos = mapToGlobal(pos);
  8906. if (className && strstr(className, "Dock") != nullptr &&
  8907. !objName.isEmpty()) {
  8908. if (objName.compare("scenesDock") == 0) {
  8909. ui->scenes->customContextMenuRequested(globalPos);
  8910. } else if (objName.compare("sourcesDock") == 0) {
  8911. ui->sources->customContextMenuRequested(globalPos);
  8912. } else if (objName.compare("mixerDock") == 0) {
  8913. StackedMixerAreaContextMenuRequested();
  8914. }
  8915. } else if (!className) {
  8916. ui->menuDocks->exec(globalPos);
  8917. }
  8918. }
  8919. void OBSBasic::UpdateProjectorHideCursor()
  8920. {
  8921. for (size_t i = 0; i < projectors.size(); i++)
  8922. projectors[i]->SetHideCursor();
  8923. }
  8924. void OBSBasic::UpdateProjectorAlwaysOnTop(bool top)
  8925. {
  8926. for (size_t i = 0; i < projectors.size(); i++)
  8927. SetAlwaysOnTop(projectors[i], top);
  8928. }
  8929. void OBSBasic::ResetProjectors()
  8930. {
  8931. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  8932. ClearProjectors();
  8933. LoadSavedProjectors(savedProjectorList);
  8934. OpenSavedProjectors();
  8935. }
  8936. void OBSBasic::on_sourcePropertiesButton_clicked()
  8937. {
  8938. on_actionSourceProperties_triggered();
  8939. }
  8940. void OBSBasic::on_sourceFiltersButton_clicked()
  8941. {
  8942. OpenFilters();
  8943. }
  8944. void OBSBasic::on_actionSceneFilters_triggered()
  8945. {
  8946. OBSSource sceneSource = GetCurrentSceneSource();
  8947. if (sceneSource)
  8948. OpenFilters(sceneSource);
  8949. }
  8950. void OBSBasic::on_sourceInteractButton_clicked()
  8951. {
  8952. on_actionInteract_triggered();
  8953. }
  8954. void OBSBasic::ShowStatusBarMessage(const QString &message)
  8955. {
  8956. ui->statusbar->clearMessage();
  8957. ui->statusbar->showMessage(message, 10000);
  8958. }
  8959. void OBSBasic::UpdatePreviewSafeAreas()
  8960. {
  8961. drawSafeAreas = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8962. "ShowSafeAreas");
  8963. }
  8964. void OBSBasic::UpdatePreviewOverflowSettings()
  8965. {
  8966. bool hidden = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8967. "OverflowHidden");
  8968. bool select = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8969. "OverflowSelectionHidden");
  8970. bool always = config_get_bool(App()->GlobalConfig(), "BasicWindow",
  8971. "OverflowAlwaysVisible");
  8972. ui->preview->SetOverflowHidden(hidden);
  8973. ui->preview->SetOverflowSelectionHidden(select);
  8974. ui->preview->SetOverflowAlwaysVisible(always);
  8975. }
  8976. void OBSBasic::SetDisplayAffinity(QWindow *window)
  8977. {
  8978. if (!SetDisplayAffinitySupported())
  8979. return;
  8980. bool hideFromCapture = config_get_bool(App()->GlobalConfig(),
  8981. "BasicWindow",
  8982. "HideOBSWindowsFromCapture");
  8983. // Don't hide projectors, those are designed to be visible / captured
  8984. if (window->property("isOBSProjectorWindow") == true)
  8985. return;
  8986. #ifdef _WIN32
  8987. HWND hwnd = (HWND)window->winId();
  8988. DWORD curAffinity;
  8989. if (GetWindowDisplayAffinity(hwnd, &curAffinity)) {
  8990. if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE)
  8991. SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE);
  8992. else if (!hideFromCapture && curAffinity != WDA_NONE)
  8993. SetWindowDisplayAffinity(hwnd, WDA_NONE);
  8994. }
  8995. #else
  8996. // TODO: Implement for other platforms if possible. Don't forget to
  8997. // implement SetDisplayAffinitySupported too!
  8998. UNUSED_PARAMETER(hideFromCapture);
  8999. #endif
  9000. }
  9001. static inline QColor color_from_int(long long val)
  9002. {
  9003. return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  9004. (val >> 24) & 0xff);
  9005. }
  9006. QColor OBSBasic::GetSelectionColor() const
  9007. {
  9008. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9009. "OverrideColors")) {
  9010. return color_from_int(config_get_int(
  9011. GetGlobalConfig(), "Accessibility", "SelectRed"));
  9012. } else {
  9013. return QColor::fromRgb(255, 0, 0);
  9014. }
  9015. }
  9016. QColor OBSBasic::GetCropColor() const
  9017. {
  9018. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9019. "OverrideColors")) {
  9020. return color_from_int(config_get_int(
  9021. GetGlobalConfig(), "Accessibility", "SelectGreen"));
  9022. } else {
  9023. return QColor::fromRgb(0, 255, 0);
  9024. }
  9025. }
  9026. QColor OBSBasic::GetHoverColor() const
  9027. {
  9028. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  9029. "OverrideColors")) {
  9030. return color_from_int(config_get_int(
  9031. GetGlobalConfig(), "Accessibility", "SelectBlue"));
  9032. } else {
  9033. return QColor::fromRgb(0, 127, 255);
  9034. }
  9035. }
  9036. void OBSBasic::UpdatePreviewSpacingHelpers()
  9037. {
  9038. drawSpacingHelpers = config_get_bool(
  9039. App()->GlobalConfig(), "BasicWindow", "SpacingHelpersEnabled");
  9040. }
  9041. float OBSBasic::GetDevicePixelRatio()
  9042. {
  9043. return dpi;
  9044. }
  9045. void OBSBasic::ThemeChanged()
  9046. {
  9047. /* Since volume/media sliders are using QProxyStyle, they are not
  9048. * updated when themes are changed, so re-initialize them. */
  9049. vector<OBSSource> sources;
  9050. for (size_t i = 0; i != volumes.size(); i++)
  9051. sources.emplace_back(volumes[i]->GetSource());
  9052. ClearVolumeControls();
  9053. for (const auto &source : sources)
  9054. ActivateAudioSource(source);
  9055. UpdateContextBar(true);
  9056. if (api)
  9057. api->on_event(OBS_FRONTEND_EVENT_THEME_CHANGED);
  9058. }