window-basic-main.cpp 301 KB

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