Compare commits

..

17 Commits

Author SHA1 Message Date
20afe92371 Bump version to 6.4.2 2025-02-14 06:06:01 +07:00
5738412f71 Fix crashing in LoadingScreen 2025-02-14 06:05:46 +07:00
d2ee3d2122 Bump version to 6.4.1 2025-02-08 20:21:20 +07:00
a65fd8233b Upgrade bun 2025-02-08 20:20:58 +07:00
1375fb115d Highlight "Bypass region" row in unsupported regions 2025-02-08 20:11:48 +07:00
bedf82d363 Minify shaders 2025-02-08 11:05:52 +07:00
b463e4f014 Define types for Patcher 2025-02-08 09:57:42 +07:00
2f8c776133 Stop using MutationObserver in root-dialog 2025-02-07 22:02:58 +07:00
585ee82776 Only call useEffect on mounted 2025-02-07 21:32:18 +07:00
3c2549178b Patch createPortal 2025-02-07 21:31:01 +07:00
2fb2cfb004 Fix starting StreamStats multiple times 2025-02-07 18:21:07 +07:00
ac20cc51cc Stop using MutationObserver in stream-ui 2025-02-07 17:31:30 +07:00
85339f09da Simplify Patcher's logs 2025-02-07 17:10:18 +07:00
4b06d9fcff useEffect() for Error page 2025-02-07 17:01:03 +07:00
d4c1e8cce3 Bug fixes 2025-02-07 09:00:22 +07:00
cf1f656ecf Stop using MutationObserver to track StreamHud's expanded status 2025-02-07 08:43:06 +07:00
2fd482bb7b Use a better method to show the Better xCloud button ASAP 2025-02-06 21:23:56 +07:00
29 changed files with 649 additions and 1031 deletions

View File

@ -25,11 +25,11 @@
"@eslint/config-array": ["@eslint/config-array@0.19.0", "", { "dependencies": { "@eslint/object-schema": "^2.1.4", "debug": "^4.3.1", "minimatch": "^3.1.2" } }, "sha512-zdHg2FPIFNKPdcHWtiNT+jEFCHYVplAXRDlQDyqy0zGx/q2parwh7brGJSiTxRk/TSMkbM//zt/f5CHgyTyaSQ=="],
"@eslint/core": ["@eslint/core@0.10.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw=="],
"@eslint/core": ["@eslint/core@0.11.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-DWUB2pksgNEb6Bz2fggIy1wh6fGgZP4Xyy/Mt0QZPiloKKXerbqq9D3SBQTlCRYOrcRPu4vuz+CGjwdfqxnoWA=="],
"@eslint/eslintrc": ["@eslint/eslintrc@3.2.0", "", { "dependencies": { "ajv": "^6.12.4", "debug": "^4.3.2", "espree": "^10.0.1", "globals": "^14.0.0", "ignore": "^5.2.0", "import-fresh": "^3.2.1", "js-yaml": "^4.1.0", "minimatch": "^3.1.2", "strip-json-comments": "^3.1.1" } }, "sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w=="],
"@eslint/js": ["@eslint/js@9.19.0", "", {}, "sha512-rbq9/g38qjfqFLOVPvwjIvFFdNziEC5S65jmjPw5r6A//QH+W91akh9irMwjDN8zKUTak6W9EsAv4m/7Wnw0UQ=="],
"@eslint/js": ["@eslint/js@9.20.0", "", {}, "sha512-iZA07H9io9Wn836aVTytRaNqh00Sad+EamwOVJT12GTLw1VGMFV/4JaME+JjLtr9fiGaoWgYnS54wrfWsSs4oQ=="],
"@eslint/object-schema": ["@eslint/object-schema@2.1.4", "", {}, "sha512-BsWiH1yFGjXXS2yvrf5LyuoSIIbPrGUWob917o+BTKuZ7qJdxX8aJLRxs1fS9n6r7vESrq1OUqb68dANcFXuQQ=="],
@ -49,19 +49,19 @@
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@types/bun": ["@types/bun@1.2.0", "", { "dependencies": { "bun-types": "1.2.0" } }, "sha512-5N1JqdahfpBlAv4wy6svEYcd/YfO2GNrbL95JOmFx8nkE6dbK4R0oSE5SpBA4vBRqgrOUAXF8Dpiz+gi7r80SA=="],
"@types/bun": ["@types/bun@1.2.2", "", { "dependencies": { "bun-types": "1.2.2" } }, "sha512-tr74gdku+AEDN5ergNiBnplr7hpDp3V1h7fqI2GcR/rsUaM39jpSeKH0TFibRvU0KwniRx5POgaYnaXbk0hU+w=="],
"@types/estree": ["@types/estree@1.0.6", "", {}, "sha512-AYnb1nQyY49te+VRAVgmzfcgjYS91mY5P0TKUDCLEM+gNnA+3T6rWITXRLYCpahpqSQbN5cE+gHpnPyXjHWxcw=="],
"@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],
"@types/node": ["@types/node@22.10.10", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-X47y/mPNzxviAGY5TcYPtYL8JsY3kAq2n8fMmKoRCxq/c4v4pyGNCzM2R6+M5/umG4ZfHuT+sgqDYqWc9rJ6ww=="],
"@types/node": ["@types/node@22.13.1", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-jK8uzQlrvXqEU91UxiK5J7pKHyzgnI1Qnl0QDHIgVGuolJhRb9EEl28Cj9b3rGR8B2lhFCtvIm5os8lFnO/1Ew=="],
"@types/stylus": ["@types/stylus@0.48.43", "", { "dependencies": { "@types/node": "*" } }, "sha512-72dv/zdhuyXWVHUXG2VTPEQdOG+oen95/DNFx2aMFFaY6LoITI6PwEqf5x31JF49kp2w9hvUzkNfTGBIeg61LQ=="],
"@types/ws": ["@types/ws@8.5.10", "", { "dependencies": { "@types/node": "*" } }, "sha512-vmQSUcfalpIq0R9q7uTo2lXs6eGIpt9wtnLdMv9LVpIjCA/+ufZRozlVoVelIYixx1ugCBKDhn89vnsEGOCx9A=="],
"@webgpu/types": ["@webgpu/types@0.1.53", "", {}, "sha512-x+BLw/opaz9LiVyrMsP75nO1Rg0QfrACUYIbVSfGwY/w0DiWIPYYrpte6us//KZXinxFAOJl0+C17L1Vi2vmDw=="],
"@webgpu/types": ["@webgpu/types@0.1.54", "", {}, "sha512-81oaalC8LFrXjhsczomEQ0u3jG+TqE6V9QHLA8GNZq/Rnot0KDugu3LhSYSlie8tSdooAN1Hov05asrUUp9qgg=="],
"acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="],
@ -83,7 +83,7 @@
"browserslist": ["browserslist@4.24.3", "", { "dependencies": { "caniuse-lite": "^1.0.30001688", "electron-to-chromium": "^1.5.73", "node-releases": "^2.0.19", "update-browserslist-db": "^1.1.1" }, "bin": { "browserslist": "cli.js" } }, "sha512-1CPmv8iobE2fyRMV97dAcMVegvvWKxmq94hkLiAkUGwKVTyDLw33K+ZxiFrREKmmps4rIw6grcCFCnTMSZ/YiA=="],
"bun-types": ["bun-types@1.2.0", "", { "dependencies": { "@types/node": "*", "@types/ws": "~8.5.10" } }, "sha512-KEaJxyZfbV/c4eyG0vyehDpYmBGreNiQbZIqvVHJwZ4BmeuWlNZ7EAzMN2Zcd7ailmS/tGVW0BgYbGf+lGEpWw=="],
"bun-types": ["bun-types@1.2.2", "", { "dependencies": { "@types/node": "*", "@types/ws": "~8.5.10" } }, "sha512-RCbMH5elr9gjgDGDhkTTugA21XtJAy/9jkKe/G3WR2q17VPGhcquf9Sir6uay9iW+7P/BV0CAHA1XlHXMAVKHg=="],
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
@ -113,7 +113,7 @@
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"eslint": ["eslint@9.19.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.0", "@eslint/core": "^0.10.0", "@eslint/eslintrc": "^3.2.0", "@eslint/js": "9.19.0", "@eslint/plugin-kit": "^0.2.5", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.1", "@types/estree": "^1.0.6", "@types/json-schema": "^7.0.15", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.2.0", "eslint-visitor-keys": "^4.2.0", "espree": "^10.3.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-ug92j0LepKlbbEv6hD911THhoRHmbdXt2gX+VDABAW/Ir7D3nqKdv5Pf5vtlyY6HQMTEP2skXY43ueqTCWssEA=="],
"eslint": ["eslint@9.20.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.0", "@eslint/core": "^0.11.0", "@eslint/eslintrc": "^3.2.0", "@eslint/js": "9.20.0", "@eslint/plugin-kit": "^0.2.5", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.1", "@types/estree": "^1.0.6", "@types/json-schema": "^7.0.15", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", "eslint-scope": "^8.2.0", "eslint-visitor-keys": "^4.2.0", "espree": "^10.3.0", "esquery": "^1.5.0", "esutils": "^2.0.2", "fast-deep-equal": "^3.1.3", "file-entry-cache": "^8.0.0", "find-up": "^5.0.0", "glob-parent": "^6.0.2", "ignore": "^5.2.0", "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", "lodash.merge": "^4.6.2", "minimatch": "^3.1.2", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, "peerDependencies": { "jiti": "*" }, "optionalPeers": ["jiti"], "bin": { "eslint": "bin/eslint.js" } }, "sha512-aL4F8167Hg4IvsW89ejnpTwx+B/UQRzJPGgbIOl+4XqffWsahVVsLEWoZvnrVuwpWmnRd7XeXmQI1zlKcFDteA=="],
"eslint-plugin-compat": ["eslint-plugin-compat@6.0.2", "", { "dependencies": { "@mdn/browser-compat-data": "^5.5.35", "ast-metadata-inferer": "^0.8.1", "browserslist": "^4.24.2", "caniuse-lite": "^1.0.30001687", "find-up": "^5.0.0", "globals": "^15.7.0", "lodash.memoize": "^4.1.2", "semver": "^7.6.2" }, "peerDependencies": { "eslint": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0" } }, "sha512-1ME+YfJjmOz1blH0nPZpHgjMGK4kjgEeoYqGCqoBPQ/mGu/dJzdoP0f1C8H2jcWZjzhZjAMccbM/VdXhPORIfA=="],
@ -275,6 +275,8 @@
"@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
"@eslint/plugin-kit/@eslint/core": ["@eslint/core@0.10.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw=="],
"@humanfs/node/@humanwhocodes/retry": ["@humanwhocodes/retry@0.3.1", "", {}, "sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA=="],
"@types/stylus/@types/node": ["@types/node@22.5.5", "", { "dependencies": { "undici-types": "~6.19.2" } }, "sha512-Xjs4y5UPO/CLdzpgR6GirZJx36yScjh73+2NlLlkFRSoQN8B0DpfXPdZGnvVmLRLOsqDpOfTNv7D9trgGhmOIA=="],

View File

@ -1,5 +1,5 @@
// ==UserScript==
// @name Better xCloud
// @namespace https://github.com/redphx
// @version 6.4.0
// @version 6.4.2
// ==/UserScript==

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -10,11 +10,11 @@
"build": "build.ts"
},
"devDependencies": {
"@types/bun": "^1.2.0",
"@types/node": "^22.10.10",
"@types/bun": "^1.2.2",
"@types/node": "^22.13.1",
"@types/stylus": "^0.48.43",
"@webgpu/types": "^0.1.53",
"eslint": "^9.19.0",
"@webgpu/types": "^0.1.54",
"eslint": "^9.20.0",
"eslint-plugin-compat": "^6.0.2",
"stylus": "^0.64.0"
},

View File

@ -202,6 +202,10 @@
}
}
}
&.bx-settings-important-row {
background: #733b00;
}
}
.bx-settings-dialog-note {

View File

@ -33,12 +33,9 @@ import { GameTile } from "./modules/ui/game-tile";
import { ProductDetailsPage } from "./modules/ui/product-details";
import { NavigationDialogManager } from "./modules/ui/dialog/navigation-dialog";
import { GlobalPref, StreamPref } from "./enums/pref-keys";
import { SettingsDialog } from "./modules/ui/dialog/settings-dialog";
import { StreamUiHandler } from "./modules/stream/stream-ui";
import { UserAgent } from "./utils/user-agent";
import { XboxApi } from "./utils/xbox-api";
import { StreamStatsCollector } from "./utils/stream-stats-collector";
import { RootDialogObserver } from "./utils/root-dialog-observer";
import { StreamSettings } from "./utils/stream-settings";
import { KeyboardShortcutHandler } from "./modules/mkb/keyboard-shortcut-handler";
import { GhPagesUtils } from "./utils/gh-pages";
@ -48,6 +45,8 @@ import { getGlobalPref, getStreamPref } from "./utils/pref-utils";
import { SettingsManager } from "./modules/settings-manager";
import { Toast } from "./utils/toast";
import { WebGPUPlayer } from "./modules/player/webgpu/webgpu-player";
import { StreamUiHandler } from "./modules/stream/stream-ui";
import { TrueAchievements } from "./utils/true-achievements";
SettingsManager.getInstance();
@ -174,7 +173,7 @@ document.addEventListener('readystatechange', e => {
}
} else {
// Show Settings button in the header when not signed in
window.setTimeout(HeaderSection.watchHeader, 2000);
// window.setTimeout(HeaderSection.watchHeader, 2000);
}
// Hide "Play with Friends" skeleton section
@ -198,26 +197,14 @@ window.addEventListener('popstate', onHistoryChanged);
window.history.pushState = patchHistoryMethod('pushState');
window.history.replaceState = patchHistoryMethod('replaceState');
BxEventBus.Script.once('xcloud.server.unavailable', () => {
STATES.supportedRegion = false;
window.setTimeout(HeaderSection.watchHeader, 2000);
// Open Settings dialog on Unsupported page
const $unsupportedPage = document.querySelector<HTMLElement>('div[class^=UnsupportedMarketPage-module__container]');
if ($unsupportedPage) {
SettingsDialog.getInstance().show();
}
});
BxEventBus.Script.on('xcloud.server.ready', () => {
STATES.isSignedIn = true;
window.setTimeout(HeaderSection.watchHeader, 2000);
BxEventBus.Script.on('ui.header.rendered', () => {
HeaderSection.getInstance().checkHeader();
});
BxEventBus.Stream.on('state.loading', () => {
// Get title ID for screenshot's name
if (window.location.pathname.includes('/launch/') && STATES.currentStream.titleInfo) {
STATES.currentStream.titleSlug = productTitleToSlug(STATES.currentStream.titleInfo.product.title);
STATES.currentStream.titleSlug = productTitleToSlug(STATES.currentStream.titleInfo.productInfo.title);
} else {
STATES.currentStream.titleSlug = 'remote-play';
}
@ -247,7 +234,6 @@ BxEventBus.Stream.on('state.playing', payload => {
}
STATES.isPlaying = true;
StreamUiHandler.observe();
if (isFullVersion()) {
const gameBar = GameBar.getInstance();
@ -274,10 +260,39 @@ BxEventBus.Stream.on('state.playing', payload => {
updateVideoPlayer();
});
BxEventBus.Stream.on('state.error', () => {
BxEventBus.Script.on('ui.error.rendered', () => {
BxEventBus.Stream.emit('state.stopped', {});
});
BxEventBus.Script.on('ui.guideHome.rendered', () => {
const $root = document.querySelector<HTMLElement>('#gamepass-dialog-root div[role=dialog] div[role=tabpanel] div[class*=HomeLandingPage]');
$root && GuideMenu.getInstance().injectHome($root, STATES.isPlaying);
});
BxEventBus.Script.on('ui.guideAchievementProgress.rendered', () => {
const $elm = document.querySelector('#gamepass-dialog-root button[class*=AchievementsButton-module__progressBarContainer]');
if ($elm) {
TrueAchievements.getInstance().injectAchievementsProgress($elm as HTMLElement);
}
});
BxEventBus.Script.on('ui.guideAchievementDetail.rendered', () => {
const $elm = document.querySelector('#gamepass-dialog-root div[class^=AchievementDetailPage-module]');
if ($elm) {
TrueAchievements.getInstance().injectAchievementDetailPage($elm as HTMLElement);
}
});
BxEventBus.Stream.on('ui.streamMenu.rendered', async () => {
await StreamUiHandler.handleStreamMenu();
});
BxEventBus.Stream.on('ui.streamHud.rendered', async () => {
const $elm = document.querySelector<HTMLElement>('#StreamHud');
$elm && StreamUiHandler.handleSystemMenu($elm);
});
isFullVersion() && window.addEventListener(BxEvent.XCLOUD_RENDERING_COMPONENT, e => {
const component = (e as any).component;
if (component === 'product-detail') {
@ -337,6 +352,7 @@ function unload() {
return;
}
BxLogger.warning('Unloading');
if (isFullVersion()) {
KeyboardShortcutHandler.getInstance().stop();
@ -406,12 +422,9 @@ function main() {
disableAdobeAudienceManager();
}
RootDialogObserver.waitForRootDialog();
// Setup UI
addCss();
GuideMenu.getInstance().addEventListeners();
StreamStatsCollector.setupEvents();
StreamBadges.setupEvents();
StreamStats.setupEvents();

View File

@ -25,3 +25,17 @@ export const renderStylus = async () => {
export const compressCss = (css: string) => {
return (stylus(css, {}).set('compress', true)).render();
};
export const compressCode = (code: string): string => {
return code.split('\n') // Split into lines
.map(line => line.startsWith('#') || line.startsWith('@') ? line + '\n' : line.trim()) // Trim spaces, with exceptions for shader files
.filter(line => line && !line.startsWith('//')) // Remove empty and commented lines
.join(''); // Join into a single line
};
export const compressCodeFile = async (path: string) => {
const file = Bun.file(path);
const code = await file.text();
return compressCode(code);
};

View File

@ -35,7 +35,9 @@ export class LoadingScreen {
LoadingScreen.$bgStyle = $bgStyle;
}
LoadingScreen.setBackground(titleInfo.product.heroImageUrl || titleInfo.product.titledHeroImageUrl || titleInfo.product.tileImageUrl);
if (titleInfo.productInfo) {
LoadingScreen.setBackground(titleInfo.productInfo.heroImageUrl || titleInfo.productInfo.titledHeroImageUrl || titleInfo.productInfo.tileImageUrl);
}
if (getGlobalPref(GlobalPref.LOADING_SCREEN_ROCKET) === LoadingScreenRocket.HIDE) {
LoadingScreen.hideRocket();

View File

@ -1,3 +1,4 @@
import type { ScriptEvents, StreamEvents } from "@/utils/bx-event-bus";
import type { PatchArray, PatchName, PatchPage } from "./patcher";
export class PatcherUtils {
@ -35,7 +36,7 @@ export class PatcherUtils {
return txt.substring(0, index) + toString + txt.substring(index + fromString.length);
}
static filterPatches(patches: Array<string | false>): PatchArray {
static filterPatches(patches: Array<PatchName | false>): PatchArray {
return patches.filter((item): item is PatchName => !!item);
}
@ -96,4 +97,11 @@ export class PatcherUtils {
return str.substring(start, end);
}
static injectUseEffect<T extends 'Stream' | 'Script'>(str: string, index: number, group: T, eventName: T extends 'Stream' ? keyof StreamEvents : keyof ScriptEvents) {
const newCode = `window.BX_EXPOSED.reactUseEffect(() => window.BxEventBus.${group}.emit('${eventName}', {}), []);`;
str = PatcherUtils.insertAt(str, index, newCode);
return str;
}
}

View File

@ -11,6 +11,8 @@ import codeGameCardIcons from "./patches/game-card-icons.js" with { type: "text"
import codeLocalCoOpEnable from "./patches/local-co-op-enable.js" with { type: "text" };
import codeRemotePlayKeepAlive from "./patches/remote-play-keep-alive.js" with { type: "text" };
import codeVibrationAdjust from "./patches/vibration-adjust.js" with { type: "text" };
import codeStreamHud from "./patches/stream-hud.js" with { type: "text" };
import codeCreatePortal from "./patches/create-portal.js" with { type: "text" };
import { GlobalPref, StorageKey } from "@/enums/pref-keys.js";
import { getGlobalPref } from "@/utils/pref-utils.js";
import { GamePassCloudGallery } from "@/enums/game-pass-gallery";
@ -21,6 +23,7 @@ import { PatcherUtils } from "./patcher-utils.js";
export type PatchName = keyof typeof PATCHES;
export type PatchArray = PatchName[];
export type PatchPage = 'home' | 'stream' | 'product-detail';
type PatchFunction = (str: string) => string | false;
const LOG_TAG = 'Patcher';
@ -29,11 +32,7 @@ const PATCHES = {
disableAiTrack(str: string) {
let text = '.track=function(';
const index = str.indexOf(text);
if (index < 0) {
return false;
}
if (PatcherUtils.indexOf(str, '"AppInsightsCore', index, 200) < 0) {
if (index < 0 || PatcherUtils.indexOf(str, '"AppInsightsCore', index, 200) < 0) {
return false;
}
@ -421,24 +420,19 @@ if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFak
},
patchStreamHud(str: string) {
let text = 'let{onCollapse';
if (!str.includes(text)) {
let index = str.indexOf('let{onCollapse');
if (index < 0) {
return false;
}
let newCode = `
// Expose onShowStreamMenu
window.BX_EXPOSED.showStreamMenu = e.onShowStreamMenu;
// Restore the "..." button
e.guideUI = null;
`;
let newCode = codeStreamHud;
// Remove the TAK Edit button when the touch controller is disabled
if (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF) {
newCode += 'e.canShowTakHUD = false;';
newCode += 'options.canShowTakHUD = false;';
}
str = str.replace(text, newCode + text);
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
@ -1029,9 +1023,14 @@ ${subsVar} = subs;
return false;
}
const newCode = 'window.BX_EXPOSED.reactCreateElement=';
str = PatcherUtils.insertAt(str, index - 1, newCode);
str = PatcherUtils.insertAt(str, index - 1, 'window.BX_EXPOSED.reactCreateElement=');
index = PatcherUtils.indexOf(str, '.useEffect=', index);
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index - 1, 'window.BX_EXPOSED.reactUseEffect=');
return str;
},
@ -1130,55 +1129,167 @@ ${subsVar} = subs;
str = PatcherUtils.insertAt(str, index, `&q=${getGlobalPref(GlobalPref.UI_IMAGE_QUALITY)}`);
return str;
}
};
},
injectHeaderUseEffect(str: string) {
let index = str.indexOf('"EdgewaterHeader-module__spaceBetween');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 300));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Script', 'ui.header.rendered');
},
injectErrorPageUseEffect(str: string) {
let index = str.indexOf('"PureErrorPage-module__container');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 200));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Script', 'ui.error.rendered');
},
injectStreamMenuUseEffect(str: string) {
let index = str.indexOf('"StreamMenu-module__container');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 200));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Stream', 'ui.streamMenu.rendered');
},
injectGuideHomeUseEffect(str: string) {
let index = str.indexOf('"HomeLandingPage-module__authenticatedContentContainer');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 200));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Script', 'ui.guideHome.rendered');
},
injectCreatePortal(str: string) {
let index = str.indexOf('.createPortal=function');
index > -1 && (index = PatcherUtils.indexOf(str, '{', index, 50, true));
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index, codeCreatePortal);
return str;
},
injectAchievementsProgressUseEffect(str: string) {
let index = str.indexOf('"AchievementsButton-module__progressBarContainer');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 200));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Script', 'ui.guideAchievementProgress.rendered');
},
injectAchievementsDetailUseEffect(str: string) {
let index = str.indexOf('GuideAchievementDetail.useParams()');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'const', index, 200));
if (index < 0) {
return false;
}
return PatcherUtils.injectUseEffect(str, index, 'Script', 'ui.guideAchievementDetail.rendered');
},
/*
patchBasicGameInfo(str: string) {
let index = str.indexOf('.ChildXboxTitleIds,offerings');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return{', index, 1000));
if (index < 0) {
return false;
}
const varName = PatcherUtils.getVariableNameBefore(str, PatcherUtils.lastIndexOf(str, '=>{', index));
if (!varName) {
return false;
}
const newCode = `
const info = ${varName};
if (info.ProductTitle.includes('Xbox One')) {
return {};
}
`;
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
*/
} as const satisfies { [key: string]: PatchFunction };
let PATCH_ORDERS = PatcherUtils.filterPatches([
...(AppInterface && getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
'enableNativeMkb',
'disableAbsoluteMouse',
] : []),
] : []) as PatchArray,
'exposeReactCreateComponent',
'gameCardCustomIcons',
// 'gameCardPassTitle',
...(getGlobalPref(GlobalPref.UI_IMAGE_QUALITY) < 90 ? [
'setImageQuality',
] : []),
'injectCreatePortal',
'modifyPreloadedState',
'broadcastPollingMode',
getGlobalPref(GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME) && 'patchSetCurrentFocus',
'patchGamepadPolling',
'optimizeGameSlugGenerator',
'detectBrowserRouterReady',
'patchRequestInfoCrash',
'modifyPreloadedState',
'disableStreamGate',
'broadcastPollingMode',
'patchGamepadPolling',
'detectBrowserRouterReady',
'exposeStreamSession',
'supportLocalCoOp',
'disableStreamGate',
'exposeDialogRoutes',
'homePageBeforeLoad',
'productDetailPageBeforeLoad',
...(getGlobalPref(GlobalPref.UI_IMAGE_QUALITY) < 90 ? [
'setImageQuality',
] : []) as PatchArray,
'patchRequestInfoCrash',
'injectErrorPageUseEffect',
'streamPageBeforeLoad',
'injectGuideHomeUseEffect',
'injectAchievementsProgressUseEffect',
'injectAchievementsDetailUseEffect',
'guideAchievementsDefaultLocked',
'injectHeaderUseEffect',
'homePageBeforeLoad',
'gameCardCustomIcons',
// 'gameCardPassTitle',
'productDetailPageBeforeLoad',
'enableTvRoutes',
'supportLocalCoOp',
'overrideStorageGetSettings',
getGlobalPref(GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME) && 'patchSetCurrentFocus',
getGlobalPref(GlobalPref.UI_LAYOUT) !== UiLayout.DEFAULT && 'websiteLayout',
getGlobalPref(GlobalPref.GAME_FORTNITE_FORCE_CONSOLE) && 'forceFortniteConsole',
...(STATES.userAgent.capabilities.touch ? [
'disableTouchContextMenu',
] : []),
] : []) as PatchArray,
...(getGlobalPref(GlobalPref.BLOCK_TRACKING) ? [
'disableAiTrack',
@ -1188,41 +1299,41 @@ let PATCH_ORDERS = PatcherUtils.filterPatches([
'disableIndexDbLogging',
'disableTelemetryProvider',
] : []),
] : []) as PatchArray,
...(getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED) ? [
'remotePlayKeepAlive',
'remotePlayDirectConnectUrl',
'remotePlayKeepAlive',
'remotePlayWebTitle',
'remotePlayDisableAchievementToast',
'remotePlayRecentlyUsedTitleIds',
'remotePlayWebTitle',
STATES.userAgent.capabilities.touch && 'patchUpdateInputConfigurationAsync',
] : []),
] : []) as PatchArray,
...(BX_FLAGS.EnableXcloudLogging ? [
'enableConsoleLogging',
'enableXcloudLogger',
] : []),
] : []) as PatchArray,
]);
const hideSections = getGlobalPref(GlobalPref.UI_HIDE_SECTIONS);
let HOME_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
hideSections.includes(UiSection.NEWS) && 'ignoreNewsSection',
(getGlobalPref(GlobalPref.BLOCK_FEATURES).includes(BlockFeature.FRIENDS) || hideSections.includes(UiSection.FRIENDS)) && 'ignorePlayWithFriendsSection',
hideSections.includes(UiSection.ALL_GAMES) && 'ignoreAllGamesSection',
hideSections.includes(UiSection.GENRES) && 'ignoreGenresSection',
!getGlobalPref(GlobalPref.BLOCK_FEATURES).includes(BlockFeature.BYOG) && hideSections.includes(UiSection.BOYG) && 'ignoreByogSection',
STATES.browser.capabilities.touch && hideSections.includes(UiSection.TOUCH) && 'ignorePlayWithTouchSection',
getGlobalPref(GlobalPref.UI_IMAGE_QUALITY) < 90 && 'setBackgroundImageQuality',
hideSections.some(value => [UiSection.NATIVE_MKB, UiSection.MOST_POPULAR].includes(value)) && 'ignoreSiglSections',
...(getGlobalPref(GlobalPref.UI_IMAGE_QUALITY) < 90 ? [
'setBackgroundImageQuality',
] : []),
hideSections.includes(UiSection.NEWS) && 'ignoreNewsSection',
(getGlobalPref(GlobalPref.BLOCK_FEATURES).includes(BlockFeature.FRIENDS) || hideSections.includes(UiSection.FRIENDS)) && 'ignorePlayWithFriendsSection',
hideSections.includes(UiSection.ALL_GAMES) && 'ignoreAllGamesSection',
...(blockSomeNotifications() ? [
'changeNotificationsSubscription',
] : []),
] : []) as PatchArray,
]);
// Only when playing
@ -1236,6 +1347,8 @@ let STREAM_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
'alwaysShowStreamHud',
'injectStreamMenuUseEffect',
// 'exposeEventTarget',
// Patch volume control for normal stream
@ -1252,7 +1365,7 @@ let STREAM_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
(getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF || getGlobalPref(GlobalPref.TOUCH_CONTROLLER_AUTO_OFF)) && 'disableTakRenderer',
getGlobalPref(GlobalPref.TOUCH_CONTROLLER_DEFAULT_OPACITY) !== 100 && 'patchTouchControlDefaultOpacity',
(getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) !== TouchControllerMode.OFF && (getGlobalPref(GlobalPref.MKB_ENABLED) || getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON)) && 'patchBabylonRendererClass',
] : []),
] : []) as PatchArray,
BX_FLAGS.EnableXcloudLogging && 'enableConsoleLogging',
@ -1263,13 +1376,13 @@ let STREAM_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
...(getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED) ? [
'patchRemotePlayMkb',
'remotePlayConnectMode',
] : []),
] : []) as PatchArray,
// Native MKB
...(AppInterface && getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
'patchMouseAndKeyboardEnabled',
'disableNativeRequestPointerLock',
] : []),
] : []) as PatchArray,
]);
let PRODUCT_DETAIL_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
@ -1364,6 +1477,7 @@ export class Patcher {
let patchedFuncStr = funcStr;
let modified = false;
const chunkAppliedPatches = [];
for (let patchIndex = 0; patchIndex < patchesToCheck.length; patchIndex++) {
const patchName = patchesToCheck[patchIndex];
@ -1386,18 +1500,20 @@ export class Patcher {
modified = true;
patchedFuncStr = tmpStr;
BxLogger.info(LOG_TAG, `${patchName}`);
appliedPatches.push(patchName);
chunkAppliedPatches.push(patchName);
// Remove patch
patchesToCheck.splice(patchIndex, 1);
patchIndex--;
PATCH_ORDERS = PATCH_ORDERS.filter(item => item != patchName);
BxLogger.info(LOG_TAG, 'Remaining patches', PATCH_ORDERS);
}
// Apply patched functions
if (modified) {
BxLogger.info(LOG_TAG, `✅ [${chunkId}] ${chunkAppliedPatches.join(', ')}`);
PATCH_ORDERS.length && BxLogger.info(LOG_TAG, 'Remaining patches', PATCH_ORDERS);
BX_FLAGS.Debug && console.time(LOG_TAG);
try {
chunkData[chunkId] = eval(patchedFuncStr);

View File

@ -0,0 +1,13 @@
// @ts-ignore
declare const arguments: any;
const $dom = arguments[1];
if ($dom && $dom instanceof HTMLElement && $dom.id === 'gamepass-dialog-root') {
let showing = false;
const $child = $dom.firstElementChild;
const $dialog = $child?.firstElementChild;
if ($dialog) {
showing = !$dialog.className.includes('pageChangeExit');
}
window.BxEventBus.Script.emit(showing ? 'dialog.shown' : 'dialog.dismissed', {});
}

View File

@ -0,0 +1,13 @@
// @ts-ignore
declare const arguments: any;
const options = arguments[0];
// Expose onShowStreamMenu
window.BX_EXPOSED.showStreamMenu = options.onShowStreamMenu;
// Restore the "..." button
options.guideUI = null;
window.BX_EXPOSED.reactUseEffect(() => {
window.BxEventBus.Stream.emit('ui.streamHud.rendered', { expanded: options.offset.x === 0 });
});

View File

@ -1,5 +1,5 @@
import vertClarityBoost from "./shaders/clarity-boost.vert" with { type: "text" };
import fsClarityBoost from "./shaders/clarity-boost.fs" with { type: "text" };
import { compressCodeFile } from "@macros/build" with { type: "macro" };
import { StreamPref } from "@/enums/pref-keys";
import { getStreamPref } from "@/utils/pref-utils";
import { BaseCanvasPlayer } from "../base-canvas-player";
@ -53,11 +53,11 @@ export class WebGL2Player extends BaseCanvasPlayer {
// Vertex shader: Identity map
const vShader = gl.createShader(gl.VERTEX_SHADER)!;
gl.shaderSource(vShader, vertClarityBoost);
gl.shaderSource(vShader, compressCodeFile('./src/modules/player/webgl2/shaders/clarity-boost.vert') as any as string);
gl.compileShader(vShader);
const fShader = gl.createShader(gl.FRAGMENT_SHADER)!;
gl.shaderSource(fShader, fsClarityBoost);
gl.shaderSource(fShader, compressCodeFile('./src/modules/player/webgl2/shaders/clarity-boost.fs') as any as string);
gl.compileShader(fShader);
// Create and link program

View File

@ -1,4 +1,5 @@
import wgslClarityBoost from "./shaders/clarity-boost.wgsl" with { type: "text" };
import { compressCodeFile } from "@macros/build" with { type: "macro" };
import { BaseCanvasPlayer } from "../base-canvas-player";
import { StreamPlayerType } from "@/enums/pref-values";
import { BxEventBus } from "@/utils/bx-event-bus";
@ -70,7 +71,7 @@ export class WebGPUPlayer extends BaseCanvasPlayer {
]);
this.vertexBuffer.unmap();
const shaderModule = WebGPUPlayer.device.createShaderModule({ code: wgslClarityBoost });
const shaderModule = WebGPUPlayer.device.createShaderModule({ code: compressCodeFile('./src/modules/player/webgpu/shaders/clarity-boost.wgsl') as any as string });
this.pipeline = WebGPUPlayer.device.createRenderPipeline({
layout: 'auto',
vertex: {

View File

@ -120,8 +120,9 @@ export class SettingsManager {
[StreamPref.STATS_QUICK_GLANCE_ENABLED]: {
onChange: () => {
const value = getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED);
const streamStats = StreamStats.getInstance();
value ? streamStats.quickGlanceSetup() : streamStats.quickGlanceStop();
if (!value) {
StreamStats.getInstance().stop(true);
}
},
},
[StreamPref.STATS_POSITION]: {

View File

@ -14,6 +14,7 @@ export class StreamStats {
public static getInstance = () => StreamStats.instance ?? (StreamStats.instance = new StreamStats());
private readonly LOG_TAG = 'StreamStats';
private isRunning = false;
private intervalId?: number | null;
private readonly REFRESH_INTERVAL = 1 * 1000;
@ -69,19 +70,23 @@ export class StreamStats {
};
private $container!: HTMLElement;
quickGlanceObserver?: MutationObserver | null;
private boundOnStreamHudStateChanged: typeof this.onStreamHudStateChanged;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this);
BxEventBus.Stream.on('ui.streamHud.rendered', this.boundOnStreamHudStateChanged);
this.render();
}
async start(glancing=false) {
if (!this.isHidden() || (glancing && this.isGlancing())) {
if (this.isRunning || !this.isHidden() || (glancing && this.isGlancing())) {
return;
}
this.isRunning = true;
this.intervalId && clearInterval(this.intervalId);
await this.update(true);
@ -96,6 +101,7 @@ export class StreamStats {
return;
}
this.isRunning = false;
this.intervalId && clearInterval(this.intervalId);
this.intervalId = null;
@ -113,49 +119,22 @@ export class StreamStats {
destroy() {
this.stop();
this.quickGlanceStop();
this.hideSettingsUi();
}
isHidden = () => this.$container.classList.contains('bx-gone');
isGlancing = () => this.$container.dataset.display === 'glancing';
quickGlanceSetup() {
if (!STATES.isPlaying || this.quickGlanceObserver) {
onStreamHudStateChanged({ expanded }: { expanded: boolean }) {
if (!getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED)) {
return;
}
const $uiContainer = document.querySelector('div[data-testid=ui-container]')!;
if (!$uiContainer) {
return;
if (expanded) {
this.isHidden() && this.start(true);
} else {
this.stop(true);
}
this.quickGlanceObserver = new MutationObserver((mutationList, observer) => {
for (const record of mutationList) {
const $target = record.target as HTMLElement;
if (!$target.className || !$target.className.startsWith('GripHandle')) {
continue;
}
const expanded = (record.target as HTMLElement).ariaExpanded;
if (expanded === 'true') {
this.isHidden() && this.start(true);
} else {
this.stop(true);
}
}
});
this.quickGlanceObserver.observe($uiContainer, {
attributes: true,
attributeFilter: ['aria-expanded'],
subtree: true,
});
}
quickGlanceStop() {
this.quickGlanceObserver && this.quickGlanceObserver.disconnect();
this.quickGlanceObserver = null;
}
private update = async (forceUpdate=false) => {
@ -249,7 +228,6 @@ export class StreamStats {
if (PREF_STATS_SHOW_WHEN_PLAYING) {
streamStats.start();
} else if (PREF_STATS_QUICK_GLANCE) {
streamStats.quickGlanceSetup();
// Show stats bar
!PREF_STATS_SHOW_WHEN_PLAYING && streamStats.start(true);
}

View File

@ -5,7 +5,6 @@ import { t } from "@utils/translation.ts";
import { StreamBadges } from "./stream-badges.ts";
import { StreamStats } from "./stream-stats.ts";
import { SettingsDialog } from "../ui/dialog/settings-dialog.ts";
import { BxEventBus } from "@/utils/bx-event-bus.ts";
export class StreamUiHandler {
@ -13,7 +12,6 @@ export class StreamUiHandler {
private static $btnStreamStats: HTMLElement | null | undefined;
private static $btnRefresh: HTMLElement | null | undefined;
private static $btnHome: HTMLElement | null | undefined;
private static observer: MutationObserver | undefined;
private static cloneStreamHudButton($btnOrg: HTMLElement, label: string, svgIcon: BxIconRaw): HTMLElement | null {
if (!$btnOrg) {
@ -101,7 +99,7 @@ export class StreamUiHandler {
return $btn;
}
private static async handleStreamMenu() {
static async handleStreamMenu() {
const $btnCloseHud = document.querySelector<HTMLElement>('button[class*=StreamMenu-module__backButton]');
if (!$btnCloseHud) {
return;
@ -134,13 +132,17 @@ export class StreamUiHandler {
$menu?.appendChild(await StreamBadges.getInstance().render());
}
private static handleSystemMenu($streamHud: HTMLElement) {
static handleSystemMenu($streamHud: HTMLElement) {
// Get the last button
const $orgButton = $streamHud.querySelector<HTMLElement>('div[class^=HUDButton]');
if (!$orgButton) {
return;
}
if (StreamUiHandler.$btnStreamSettings && $streamHud.contains(StreamUiHandler.$btnStreamSettings)) {
return;
}
const hideGripHandle = () => {
// Grip handle
const $gripHandle = document.querySelector<HTMLElement>('#StreamHud button[class^=GripHandle]');
@ -207,67 +209,5 @@ export class StreamUiHandler {
StreamUiHandler.$btnStreamStats = undefined;
StreamUiHandler.$btnRefresh = undefined;
StreamUiHandler.$btnHome = undefined;
StreamUiHandler.observer && StreamUiHandler.observer.disconnect();
StreamUiHandler.observer = undefined;
}
static observe() {
StreamUiHandler.reset();
const $screen = document.querySelector('#PageContent section[class*=PureScreens]');
if (!$screen) {
return;
}
const observer = new MutationObserver(mutationList => {
let item: MutationRecord;
for (item of mutationList) {
if (item.type !== 'childList') {
continue;
}
item.addedNodes.forEach(async $node => {
if (!$node || $node.nodeType !== Node.ELEMENT_NODE) {
return;
}
let $elm: HTMLElement | null = $node as HTMLElement;
// Ignore non-HTML elements
if (!($elm instanceof HTMLElement)) {
return;
}
const className = $elm.className || '';
// Error Page: .PureErrorPage.ErrorScreen
if (className.includes('PureErrorPage')) {
BxEventBus.Stream.emit('state.error', {});
return;
}
// Render badges
if (className.startsWith('StreamMenu-module__container')) {
StreamUiHandler.handleStreamMenu();
return;
}
if (className.startsWith('Overlay-module_') || className.startsWith('InProgressScreen')) {
$elm = $elm.querySelector('#StreamHud');
}
if (!$elm || ($elm.id || '') !== 'StreamHud') {
return;
}
// Handle System Menu bar
StreamUiHandler.handleSystemMenu($elm);
});
};
});
observer.observe($screen, { subtree: true, childList: true });
StreamUiHandler.observer = observer;
}
}

View File

@ -949,6 +949,11 @@ export class SettingsDialog extends NavigationDialog {
}
$row.dataset.type = settingTabContent.group;
// Highlight "Bypass region" row
if (!STATES.supportedRegion && setting.pref === GlobalPref.SERVER_BYPASS_RESTRICTION) {
$row.classList.add('bx-settings-important-row');
}
$tabContent.appendChild($row);
!prefDefinition?.unsupported && setting.onCreated && setting.onCreated(setting, $control);
}

View File

@ -1,11 +1,7 @@
import { isFullVersion } from "@macros/build" with { type: "macro" };
import { BxEvent } from "@/utils/bx-event";
import { AppInterface, STATES } from "@/utils/global";
import { createButton, ButtonStyle, CE } from "@/utils/html";
import { t } from "@/utils/translation";
import { SettingsDialog } from "./dialog/settings-dialog";
import { TrueAchievements } from "@/utils/true-achievements";
import { BxIcon } from "@/utils/bx-icon";
import { BxEventBus } from "@/utils/bx-event-bus";
import { getGlobalPref } from "@/utils/pref-utils";
@ -141,11 +137,9 @@ export class GuideMenu {
}
injectHome($root: HTMLElement, isPlaying = false) {
if (isFullVersion()) {
const $achievementsProgress = $root.querySelector('button[class*=AchievementsButton-module__progressBarContainer]');
if ($achievementsProgress) {
TrueAchievements.getInstance().injectAchievementsProgress($achievementsProgress as HTMLElement);
}
const $buttons = this.renderButtons();
if ($root.contains($buttons)) {
return;
}
// Find the element to add buttons to
@ -169,67 +163,7 @@ export class GuideMenu {
return false;
}
const $buttons = this.renderButtons();
$buttons.dataset.isPlaying = isPlaying.toString();
$target.insertAdjacentElement('afterend', $buttons);
}
private onShown = async (e: Event) => {
const where = (e as any).where as GuideMenuTab;
if (where === GuideMenuTab.HOME) {
const $root = document.querySelector<HTMLElement>('#gamepass-dialog-root div[role=dialog] div[role=tabpanel] div[class*=HomeLandingPage]');
$root && this.injectHome($root, STATES.isPlaying);
}
}
addEventListeners() {
window.addEventListener(BxEvent.XCLOUD_GUIDE_MENU_SHOWN, this.onShown);
}
observe($addedElm: HTMLElement) {
let className = $addedElm.className;
// Fix custom buttons disappearing in Guide Menu (#551)
if (!className) {
className = $addedElm.firstElementChild?.className ?? '';
}
if (!className || className.startsWith('bx-')) {
return;
}
// TrueAchievements
if (isFullVersion() && className.includes('AchievementsButton-module__progressBarContainer')) {
TrueAchievements.getInstance().injectAchievementsProgress($addedElm);
return;
}
if (!className.startsWith('NavigationAnimation') &&
!className.startsWith('DialogRoutes') &&
!className.startsWith('Dialog-module__container')) {
return;
}
// Achievement Details page
if (isFullVersion()) {
const $achievDetailPage = $addedElm.querySelector('div[class*=AchievementDetailPage]');
if ($achievDetailPage) {
TrueAchievements.getInstance().injectAchievementDetailPage($achievDetailPage as HTMLElement);
return;
}
}
// Find navigation bar
const $selectedTab = $addedElm.querySelector('div[class^=NavigationMenu] button[aria-selected=true');
if ($selectedTab) {
let $elm: Element | null = $selectedTab;
let index;
for (index = 0; ($elm = $elm?.previousElementSibling); index++);
if (index === 0) {
BxEvent.dispatch(window, BxEvent.XCLOUD_GUIDE_MENU_SHOWN, { where: GuideMenuTab.HOME });
}
}
}
}

View File

@ -1,7 +1,7 @@
import { isFullVersion } from "@macros/build" with { type: "macro" };
import { SCRIPT_VERSION } from "@utils/global";
import { createButton, ButtonStyle, CE, isElementVisible } from "@utils/html";
import { SCRIPT_VERSION, STATES } from "@utils/global";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BxIcon } from "@utils/bx-icon";
import { getPreferredServerRegion } from "@utils/region";
import { RemotePlayManager } from "@/modules/remote-play-manager";
@ -10,6 +10,7 @@ import { SettingsDialog } from "./dialog/settings-dialog";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { BxLogger } from "@/utils/bx-logger";
import { BxEventBus } from "@/utils/bx-event-bus";
export class HeaderSection {
private static instance: HeaderSection;
@ -20,9 +21,6 @@ export class HeaderSection {
private $btnSettings: HTMLElement;
private $buttonsWrapper: HTMLElement;
private observer?: MutationObserver;
private timeoutId?: number | null;
constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
@ -38,9 +36,9 @@ export class HeaderSection {
this.$btnRemotePlay = null;
}
this.$btnSettings = createButton({
classes: ['bx-header-settings-button'],
label: '???',
let $btnSettings = this.$btnSettings = createButton({
classes: ['bx-header-settings-button', 'bx-gone'],
label: t('better-xcloud'),
style: ButtonStyle.FROSTED | ButtonStyle.DROP_SHADOW | ButtonStyle.FOCUSABLE | ButtonStyle.FULL_HEIGHT,
onClick: e => SettingsDialog.getInstance().show(),
});
@ -49,65 +47,47 @@ export class HeaderSection {
getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED) ? this.$btnRemotePlay : null,
this.$btnSettings,
);
BxEventBus.Script.on('xcloud.server', ({status}) => {
if (status === 'ready') {
STATES.isSignedIn = true;
// Show server name
$btnSettings.querySelector('span')!.textContent = getPreferredServerRegion(true) || t('better-xcloud');
const PREF_LATEST_VERSION = getGlobalPref(GlobalPref.VERSION_LATEST);
// Show new update status
if (!SCRIPT_VERSION.includes('beta') && PREF_LATEST_VERSION && PREF_LATEST_VERSION !== SCRIPT_VERSION) {
$btnSettings.setAttribute('data-update-available', 'true');
}
} else if (status === 'unavailable') {
STATES.supportedRegion = false;
// Open Settings dialog on Unsupported page
const $unsupportedPage = document.querySelector<HTMLElement>('div[class^=UnsupportedMarketPage-module__container]');
if ($unsupportedPage) {
SettingsDialog.getInstance().show();
}
}
$btnSettings.classList.remove('bx-gone');
});
}
private injectSettingsButton($parent?: HTMLElement) {
if (!$parent) {
return;
}
const PREF_LATEST_VERSION = getGlobalPref(GlobalPref.VERSION_LATEST);
// Setup Settings button
const $btnSettings = this.$btnSettings;
if (isElementVisible(this.$buttonsWrapper)) {
return;
}
$btnSettings.querySelector('span')!.textContent = getPreferredServerRegion(true) || t('better-xcloud');
// Show new update status
if (!SCRIPT_VERSION.includes('beta') && PREF_LATEST_VERSION && PREF_LATEST_VERSION !== SCRIPT_VERSION) {
$btnSettings.setAttribute('data-update-available', 'true');
}
// Add the Settings button to the web page
$parent.appendChild(this.$buttonsWrapper);
}
private checkHeader = () => {
checkHeader = () => {
let $target = document.querySelector('#PageContent div[class*=EdgewaterHeader-module__rightSectionSpacing]');
if (!$target) {
$target = document.querySelector('div[class^=UnsupportedMarketPage-module__buttons]');
}
$target && this.injectSettingsButton($target as HTMLElement);
}
// Add the Settings button to the web page
$target?.appendChild(this.$buttonsWrapper);
private watchHeader() {
const $root = document.querySelector('#PageContent header') || document.querySelector('#root');
if (!$root) {
return;
if (!STATES.isSignedIn) {
BxEventBus.Script.emit('xcloud.server', { status: 'signed-out' });
}
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = null;
this.observer && this.observer.disconnect();
this.observer = new MutationObserver(mutationList => {
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(this.checkHeader, 2000);
});
this.observer.observe($root, { subtree: true, childList: true });
this.checkHeader();
}
showRemotePlayButton() {
this.$btnRemotePlay?.classList.remove('bx-gone');
}
static watchHeader() {
HeaderSection.getInstance().watchHeader();
}
}

View File

@ -36,7 +36,7 @@ type XcloudTitleInfo = {
hasMkbSupport: boolean;
};
product: {
productInfo: {
title: string;
heroImageUrl: string;
titledHeroImageUrl: string;

View File

@ -7,9 +7,10 @@ import type { SpeakerState } from "@/modules/shortcuts/sound-shortcut";
type EventCallback<T = any> = (payload: T) => void;
type ScriptEvents = {
'xcloud.server.ready': {};
'xcloud.server.unavailable': {};
export type ScriptEvents = {
'xcloud.server': {
status: 'ready' | 'unavailable' | 'signed-out',
};
'dialog.shown': {};
'dialog.dismissed': {};
@ -34,14 +35,20 @@ type ScriptEvents = {
};
'webgpu.ready': {},
'ui.header.rendered': {},
'ui.error.rendered': {},
'ui.guideHome.rendered': {},
'ui.guideAchievementProgress.rendered': {},
'ui.guideAchievementDetail.rendered': {},
};
type StreamEvents = {
export type StreamEvents = {
'state.loading': {};
'state.starting': {};
'state.playing': { $video?: HTMLVideoElement };
'state.stopped': {};
'state.error': {};
'xboxTitleId.changed': {
id: number;
@ -65,6 +72,9 @@ type StreamEvents = {
// Inside patch
'microphone.state.changed': { state: MicrophoneState };
'ui.streamHud.rendered': { expanded: boolean },
'ui.streamMenu.rendered': {},
dataChannelCreated: { dataChannel: RTCDataChannel };
};

View File

@ -14,6 +14,7 @@ export namespace BxEvent {
export const TOUCH_LAYOUT_MANAGER_READY = 'bx-touch-layout-manager-ready';
// Inside app
// TODO: Use EventBus
export const REMOTE_PLAY_READY = 'bx-remote-play-ready';
export const REMOTE_PLAY_FAILED = 'bx-remote-play-failed';

View File

@ -242,6 +242,7 @@ export const BxExposed = {
localCoOpManager: isFullVersion() ? LocalCoOpManager.getInstance() : null,
reactCreateElement: function(...args: any[]) {},
reactUseEffect: function(...args: any[]) {},
createReactLocalCoOpIcon: isFullVersion() ? (attrs: any): any => {
const reactCE = window.BX_EXPOSED.reactCreateElement;

View File

@ -3,7 +3,6 @@ import { isFullVersion } from "@macros/build" with { type: "macro" };
import { BxEvent } from "@utils/bx-event";
import { LoadingScreen } from "@modules/loading-screen";
import { RemotePlayManager } from "@/modules/remote-play-manager";
import { HeaderSection } from "@/modules/ui/header";
import { BxEventBus } from "./bx-event-bus";
import { NavigationDialogManager } from "@/modules/ui/dialog/navigation-dialog";
@ -35,7 +34,5 @@ export function onHistoryChanged(e: PopStateEvent) {
NavigationDialogManager.getInstance().hide();
LoadingScreen.reset();
window.setTimeout(HeaderSection.watchHeader, 2000);
BxEventBus.Stream.emit('state.stopped', {});
}

View File

@ -1,112 +0,0 @@
import { GuideMenu } from "@/modules/ui/guide-menu";
import { BX_FLAGS } from "./bx-flags";
import { BxLogger } from "./bx-logger";
import { BxIcon } from "./bx-icon";
import { AppInterface } from "./global";
import { createButton, ButtonStyle } from "./html";
import { t } from "./translation";
import { parseDetailsPath } from "./utils";
import { BxEventBus } from "./bx-event-bus";
export class RootDialogObserver {
private static $btnShortcut = AppInterface && createButton({
icon: BxIcon.CREATE_SHORTCUT,
label: t('create-shortcut'),
style: ButtonStyle.FOCUSABLE | ButtonStyle.GHOST | ButtonStyle.FULL_WIDTH | ButtonStyle.NORMAL_CASE | ButtonStyle.NORMAL_LINK,
onClick: e => {
window.BX_EXPOSED.dialogRoutes?.closeAll();
const $btn = (e.target as HTMLElement).closest('button');
AppInterface.createShortcut($btn?.dataset.path);
},
});
private static $btnWallpaper = AppInterface && createButton({
icon: BxIcon.DOWNLOAD,
label: t('wallpaper'),
style: ButtonStyle.FOCUSABLE | ButtonStyle.GHOST | ButtonStyle.FULL_WIDTH | ButtonStyle.NORMAL_CASE | ButtonStyle.NORMAL_LINK,
onClick: e => {
window.BX_EXPOSED.dialogRoutes?.closeAll();
const $btn = (e.target as HTMLElement).closest('button');
const details = parseDetailsPath($btn!.dataset.path!);
details && AppInterface.downloadWallpapers(details.titleSlug, details.productId);
},
});
private static handleGameCardMenu($root: HTMLElement) {
const $detail = $root.querySelector('a[href^="/play/"]') as HTMLAnchorElement;
if (!$detail) {
return;
}
const path = $detail.getAttribute('href')!;
RootDialogObserver.$btnShortcut.dataset.path = path;
RootDialogObserver.$btnWallpaper.dataset.path = path;
$root.append(RootDialogObserver.$btnShortcut, RootDialogObserver.$btnWallpaper);
}
private static handleAddedElement($root: HTMLElement, $addedElm: HTMLElement): boolean {
if (AppInterface && $addedElm.className.startsWith('SlideSheet-module__container')) {
// Game card's context menu
const $gameCardMenu = $addedElm.querySelector<HTMLElement>('div[class^=MruContextMenu],div[class^=GameCardContextMenu]');
if ($gameCardMenu) {
RootDialogObserver.handleGameCardMenu($gameCardMenu);
return true;
}
} else if ($root.querySelector('div[class*=GuideDialog]')) {
// Guide menu
GuideMenu.getInstance().observe($addedElm);
return true;
}
return false;
}
private static observe($root: HTMLElement) {
let beingShown = false;
const observer = new MutationObserver(mutationList => {
for (const mutation of mutationList) {
if (mutation.type !== 'childList') {
continue;
}
BX_FLAGS.Debug && BxLogger.warning('RootDialog', 'added', mutation.addedNodes);
if (mutation.addedNodes.length === 1) {
const $addedElm = mutation.addedNodes[0];
if ($addedElm instanceof HTMLElement) {
RootDialogObserver.handleAddedElement($root, $addedElm);
}
}
const shown = !!($root.firstElementChild && $root.firstElementChild.childElementCount > 0);
if (shown !== beingShown) {
beingShown = shown;
BxEventBus.Script.emit(shown ? 'dialog.shown' : 'dialog.dismissed', {});
}
}
});
observer.observe($root, { subtree: true, childList: true });
}
public static waitForRootDialog() {
const observer = new MutationObserver(mutationList => {
for (const mutation of mutationList) {
if (mutation.type !== 'childList') {
continue;
}
const $target = mutation.target as HTMLElement;
if ($target.id && $target.id === 'gamepass-dialog-root') {
observer.disconnect();
RootDialogObserver.observe($target);
break;
}
};
});
observer.observe(document.documentElement, { subtree: true, childList: true });
}
}

View File

@ -14,7 +14,6 @@ import { ControllerCustomizationDefaultPresetId } from "../local-db/controller-c
import { ControllerShortcutDefaultId } from "../local-db/controller-shortcuts-table";
import { BxEventBus } from "../bx-event-bus";
import { WebGPUPlayer } from "@/modules/player/webgpu/webgpu-player";
import { BX_FLAGS } from "../bx-flags";
export class StreamSettingsStorage extends BaseSettingsStorage<StreamPref> {

View File

@ -52,7 +52,7 @@ export class XcloudInterceptor {
const response = await NATIVE_FETCH(request, init);
if (response.status !== 200) {
// Unsupported region
BxEventBus.Script.emit('xcloud.server.unavailable', {});
BxEventBus.Script.emit('xcloud.server', { status: 'unavailable' });
return response;
}
@ -92,8 +92,6 @@ export class XcloudInterceptor {
STATES.serverRegions[region.name] = Object.assign({}, region);
}
BxEventBus.Script.emit('xcloud.server.ready', {});
const preferredRegion = getPreferredServerRegion();
if (preferredRegion && preferredRegion in STATES.serverRegions) {
const tmp = Object.assign({}, STATES.serverRegions[preferredRegion]);
@ -104,6 +102,7 @@ export class XcloudInterceptor {
}
STATES.gsToken = obj.gsToken;
BxEventBus.Script.emit('xcloud.server', { status: 'ready' });
response.json = () => Promise.resolve(obj);
return response;