From d4c1e8cce31b42e782d8731db497518f5c9803dc Mon Sep 17 00:00:00 2001 From: redphx <96280+redphx@users.noreply.github.com> Date: Fri, 7 Feb 2025 09:00:22 +0700 Subject: [PATCH] Bug fixes --- dist/better-xcloud.pretty.user.js | 23 ++++++++--------------- dist/better-xcloud.user.js | 6 +++--- src/modules/patcher/patcher.ts | 6 +++--- src/modules/settings-manager.ts | 5 +++-- src/modules/stream/stream-stats.ts | 20 ++++++-------------- 5 files changed, 23 insertions(+), 37 deletions(-) diff --git a/dist/better-xcloud.pretty.user.js b/dist/better-xcloud.pretty.user.js index c4759ad..63def54 100644 --- a/dist/better-xcloud.pretty.user.js +++ b/dist/better-xcloud.pretty.user.js @@ -3094,7 +3094,7 @@ class StreamStats { $container; boundOnStreamHudStateChanged; constructor() { - BxLogger.info(this.LOG_TAG, "constructor()"), this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this), this.render(); + BxLogger.info(this.LOG_TAG, "constructor()"), this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this), BxEventBus.Stream.on("ui.streamHud.expanded", this.boundOnStreamHudStateChanged), this.render(); } async start(glancing = !1) { if (!this.isHidden() || glancing && this.isGlancing()) return; @@ -3109,21 +3109,15 @@ class StreamStats { else this.isHidden() ? await this.start() : await this.stop(); } destroy() { - this.stop(), this.quickGlanceStop(), this.hideSettingsUi(); + this.stop(), this.hideSettingsUi(); } isHidden = () => this.$container.classList.contains("bx-gone"); isGlancing = () => this.$container.dataset.display === "glancing"; onStreamHudStateChanged({ state }) { + if (!getStreamPref("stats.quickGlance.enabled")) return; if (state === "expanded") this.isHidden() && this.start(!0); else this.stop(!0); } - quickGlanceSetup() { - if (!STATES.isPlaying) return; - BxEventBus.Stream.on("ui.streamHud.expanded", this.boundOnStreamHudStateChanged); - } - quickGlanceStop() { - BxEventBus.Stream.off("ui.streamHud.expanded", this.boundOnStreamHudStateChanged); - } update = async (forceUpdate = !1) => { if (!forceUpdate && this.isHidden() || !STATES.currentStream.peerConnection) { this.destroy(); @@ -3164,7 +3158,7 @@ class StreamStats { BxEventBus.Stream.on("state.playing", () => { let PREF_STATS_QUICK_GLANCE = getStreamPref("stats.quickGlance.enabled"), PREF_STATS_SHOW_WHEN_PLAYING = getStreamPref("stats.showWhenPlaying"), streamStats = StreamStats.getInstance(); if (PREF_STATS_SHOW_WHEN_PLAYING) streamStats.start(); - else if (PREF_STATS_QUICK_GLANCE) streamStats.quickGlanceSetup(), !PREF_STATS_SHOW_WHEN_PLAYING && streamStats.start(!0); + else if (PREF_STATS_QUICK_GLANCE) !PREF_STATS_SHOW_WHEN_PLAYING && streamStats.start(!0); }); } static refreshStyles() { @@ -4509,8 +4503,7 @@ class SettingsManager { }, "stats.quickGlance.enabled": { onChange: () => { - let value = getStreamPref("stats.quickGlance.enabled"), streamStats = StreamStats.getInstance(); - value ? streamStats.quickGlanceSetup() : streamStats.quickGlanceStop(); + if (!getStreamPref("stats.quickGlance.enabled")) StreamStats.getInstance().stop(!0); } }, "stats.position": { @@ -5389,11 +5382,11 @@ if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFak return str = str.replace(text, "this.useCombinedAudioVideoStream=true"), str; }, patchStreamHud(str) { - let text = "let{onCollapse"; - if (!str.includes(text)) return !1; + let index = str.indexOf("let{onCollapse"); + if (index < 0) return !1; let newCode = streamhud_default; if (getGlobalPref("touchController.mode") === "off") newCode += "options.canShowTakHUD = false;"; - return str = str.replace(text, newCode + text), str; + return str = PatcherUtils.insertAt(str, index, newCode), str; }, broadcastPollingMode(str) { let text = ".setPollingMode=e=>{"; diff --git a/dist/better-xcloud.user.js b/dist/better-xcloud.user.js index d7486a3..907b080 100755 --- a/dist/better-xcloud.user.js +++ b/dist/better-xcloud.user.js @@ -162,7 +162,7 @@ function isPlainObject(input) {return typeof input === "object" && input !== nul class SoundShortcut {static adjustGainNodeVolume(amount) {if (!getGlobalPref("audio.volume.booster.enabled")) return 0;let currentValue = getStreamPref("audio.volume"), nearestValue;if (amount > 0) nearestValue = ceilToNearest(currentValue, amount);else nearestValue = floorToNearest(currentValue, -1 * amount);let newValue;if (currentValue !== nearestValue) newValue = nearestValue;else newValue = currentValue + amount;return newValue = setStreamPref("audio.volume", newValue, "direct"), SoundShortcut.setGainNodeVolume(newValue), Toast.show(`${t("stream")} ❯ ${t("volume")}`, newValue + "%", { instant: !0 }), newValue;}static setGainNodeVolume(value) {STATES.currentStream.audioGainNode && (STATES.currentStream.audioGainNode.gain.value = value / 100);}static muteUnmute() {if (getGlobalPref("audio.volume.booster.enabled") && STATES.currentStream.audioGainNode) {let gainValue = STATES.currentStream.audioGainNode.gain.value, settingValue = getStreamPref("audio.volume"), targetValue;if (settingValue === 0) targetValue = 100, setStreamPref("audio.volume", targetValue, "direct");else if (gainValue === 0) targetValue = settingValue;else targetValue = 0;let status;if (targetValue === 0) status = t("muted");else status = targetValue + "%";SoundShortcut.setGainNodeVolume(targetValue), Toast.show(`${t("stream")} ❯ ${t("volume")}`, status, { instant: !0 }), BxEventBus.Stream.emit("speaker.state.changed", {state: targetValue === 0 ? 1 : 0});return;}let $media = document.querySelector("div[data-testid=media-container] audio") ?? document.querySelector("div[data-testid=media-container] video");if ($media) {$media.muted = !$media.muted;let status = $media.muted ? t("muted") : t("unmuted");Toast.show(`${t("stream")} ❯ ${t("volume")}`, status, { instant: !0 }), BxEventBus.Stream.emit("speaker.state.changed", {state: $media.muted ? 1 : 0});}}} class StreamUiShortcut {static showHideStreamMenu() {window.BX_EXPOSED.showStreamMenu && window.BX_EXPOSED.showStreamMenu();}} class StreamStatsCollector {static instance;static getInstance = () => StreamStatsCollector.instance ?? (StreamStatsCollector.instance = new StreamStatsCollector);LOG_TAG = "StreamStatsCollector";static INTERVAL_BACKGROUND = 60000;calculateGrade(value, grades) {return value > grades[2] ? "bad" : value > grades[1] ? "ok" : value > grades[0] ? "good" : "";}currentStats = {ping: {current: -1,grades: [40, 75, 100],toString() {return this.current === -1 ? "???" : this.current.toString().padStart(3);}},jit: {current: 0,grades: [30, 40, 60],toString() {return `${this.current.toFixed(1)}ms`.padStart(6);}},fps: {current: 0,toString() {let maxFps = getStreamPref("video.maxFps");return maxFps < 60 ? `${maxFps}/${this.current}`.padStart(5) : this.current.toString();}},btr: {current: 0,toString() {return `${this.current.toFixed(1)} Mbps`.padStart(9);}},fl: {received: 0,dropped: 0,toString() {let percentage = (this.dropped * 100 / (this.dropped + this.received || 1)).toFixed(1);return percentage.startsWith("0.") ? this.dropped.toString() : `${this.dropped} (${percentage}%)`;}},pl: {received: 0,dropped: 0,toString() {let percentage = (this.dropped * 100 / (this.dropped + this.received || 1)).toFixed(1);return percentage.startsWith("0.") ? this.dropped.toString() : `${this.dropped} (${percentage}%)`;}},dt: {current: 0,total: 0,grades: [6, 9, 12],toString() {return isNaN(this.current) ? "??ms" : `${this.current.toFixed(1)}ms`.padStart(6);}},dl: {total: 0,toString() {return humanFileSize(this.total).padStart(8);}},ul: {total: 0,toString() {return humanFileSize(this.total);}},play: {seconds: 0,startTime: 0,toString() {return secondsToHm(this.seconds);}},batt: {current: 100,start: 100,isCharging: !1,toString() {let text = `${this.current}%`;if (this.current !== this.start) {let diffLevel = Math.round(this.current - this.start), sign = diffLevel > 0 ? "+" : "";text += ` (${sign}${diffLevel}%)`;}return text;}},time: {toString() {return (new Date()).toLocaleTimeString([], {hour: "2-digit",minute: "2-digit",hour12: !1});}}};lastVideoStat;selectedCandidatePairId = null;constructor() {BxLogger.info(this.LOG_TAG, "constructor()");}async collect() {let stats = await STATES.currentStream.peerConnection?.getStats();if (!stats) return;if (!this.selectedCandidatePairId) {let found = !1;stats.forEach((stat) => {if (found || stat.type !== "transport") return;if (stat = stat, stat.iceState === "connected" && stat.selectedCandidatePairId) this.selectedCandidatePairId = stat.selectedCandidatePairId, found = !0;});}stats.forEach((stat) => {if (stat.type === "inbound-rtp" && stat.kind === "video") {let fps = this.currentStats["fps"];fps.current = stat.framesPerSecond || 0;let pl = this.currentStats["pl"];pl.dropped = Math.max(0, stat.packetsLost), pl.received = stat.packetsReceived;let fl = this.currentStats["fl"];if (fl.dropped = stat.framesDropped, fl.received = stat.framesReceived, !this.lastVideoStat) {this.lastVideoStat = stat;return;}let lastStat = this.lastVideoStat, jit = this.currentStats["jit"], bufferDelayDiff = stat.jitterBufferDelay - lastStat.jitterBufferDelay, emittedCountDiff = stat.jitterBufferEmittedCount - lastStat.jitterBufferEmittedCount;if (emittedCountDiff > 0) jit.current = bufferDelayDiff / emittedCountDiff * 1000;let btr = this.currentStats["btr"], timeDiff = stat.timestamp - lastStat.timestamp;btr.current = 8 * (stat.bytesReceived - lastStat.bytesReceived) / timeDiff / 1000;let dt = this.currentStats["dt"];dt.total = stat.totalDecodeTime - lastStat.totalDecodeTime;let framesDecodedDiff = stat.framesDecoded - lastStat.framesDecoded;dt.current = dt.total / framesDecodedDiff * 1000, this.lastVideoStat = stat;} else if (this.selectedCandidatePairId && stat.type === "candidate-pair" && stat.id === this.selectedCandidatePairId) {let ping = this.currentStats["ping"];ping.current = stat.currentRoundTripTime ? stat.currentRoundTripTime * 1000 : -1;let dl = this.currentStats["dl"];dl.total = stat.bytesReceived;let ul = this.currentStats["ul"];ul.total = stat.bytesSent;}});let batteryLevel = 100, isCharging = !1;if (STATES.browser.capabilities.batteryApi) try {let bm = await navigator.getBattery();isCharging = bm.charging, batteryLevel = Math.round(bm.level * 100);} catch (e) {}let battery = this.currentStats["batt"];battery.current = batteryLevel, battery.isCharging = isCharging;let playTime = this.currentStats["play"], now = +new Date;playTime.seconds = Math.ceil((now - playTime.startTime) / 1000);}getStat(kind) {return this.currentStats[kind];}reset() {let playTime = this.currentStats["play"];playTime.seconds = 0, playTime.startTime = +new Date;try {STATES.browser.capabilities.batteryApi && navigator.getBattery().then((bm) => {this.currentStats["batt"].start = Math.round(bm.level * 100);});} catch (e) {}}static setupEvents() {BxEventBus.Stream.on("state.playing", () => {StreamStatsCollector.getInstance().reset();});}} -class StreamStats {static instance;static getInstance = () => StreamStats.instance ?? (StreamStats.instance = new StreamStats);LOG_TAG = "StreamStats";intervalId;REFRESH_INTERVAL = 1000;stats = {time: {name: t("clock"),$element: CE("span")},play: {name: t("playtime"),$element: CE("span")},batt: {name: t("battery"),$element: CE("span")},ping: {name: t("stat-ping"),$element: CE("span")},jit: {name: t("jitter"),$element: CE("span")},fps: {name: t("stat-fps"),$element: CE("span")},btr: {name: t("stat-bitrate"),$element: CE("span")},dt: {name: t("stat-decode-time"),$element: CE("span")},pl: {name: t("stat-packets-lost"),$element: CE("span")},fl: {name: t("stat-frames-lost"),$element: CE("span")},dl: {name: t("downloaded"),$element: CE("span")},ul: {name: t("uploaded"),$element: CE("span")}};$container;boundOnStreamHudStateChanged;constructor() {BxLogger.info(this.LOG_TAG, "constructor()"), this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this), this.render();}async start(glancing = !1) {if (!this.isHidden() || glancing && this.isGlancing()) return;this.intervalId && clearInterval(this.intervalId), await this.update(!0), this.$container.classList.remove("bx-gone"), this.$container.dataset.display = glancing ? "glancing" : "fixed", this.intervalId = window.setInterval(this.update, this.REFRESH_INTERVAL);}async stop(glancing = !1) {if (glancing && !this.isGlancing()) return;this.intervalId && clearInterval(this.intervalId), this.intervalId = null, this.$container.removeAttribute("data-display"), this.$container.classList.add("bx-gone");}async toggle() {if (this.isGlancing()) this.$container && (this.$container.dataset.display = "fixed");else this.isHidden() ? await this.start() : await this.stop();}destroy() {this.stop(), this.quickGlanceStop(), this.hideSettingsUi();}isHidden = () => this.$container.classList.contains("bx-gone");isGlancing = () => this.$container.dataset.display === "glancing";onStreamHudStateChanged({ state }) {if (state === "expanded") this.isHidden() && this.start(!0);else this.stop(!0);}quickGlanceSetup() {if (!STATES.isPlaying) return;BxEventBus.Stream.on("ui.streamHud.expanded", this.boundOnStreamHudStateChanged);}quickGlanceStop() {BxEventBus.Stream.off("ui.streamHud.expanded", this.boundOnStreamHudStateChanged);}update = async (forceUpdate = !1) => {if (!forceUpdate && this.isHidden() || !STATES.currentStream.peerConnection) {this.destroy();return;}let PREF_STATS_CONDITIONAL_FORMATTING = getStreamPref("stats.colors"), grade = "", statsCollector = StreamStatsCollector.getInstance();await statsCollector.collect();let statKey;for (statKey in this.stats) {grade = "";let stat = this.stats[statKey], value = statsCollector.getStat(statKey), $element = stat.$element;if ($element.textContent = value.toString(), PREF_STATS_CONDITIONAL_FORMATTING && "grades" in value) grade = statsCollector.calculateGrade(value.current, value.grades);if ($element.dataset.grade !== grade) $element.dataset.grade = grade;}};refreshStyles() {let PREF_ITEMS = getStreamPref("stats.items"), PREF_OPACITY_BG = getStreamPref("stats.opacity.background"), $container = this.$container;if ($container.dataset.stats = "[" + PREF_ITEMS.join("][") + "]", $container.dataset.position = getStreamPref("stats.position"), PREF_OPACITY_BG === 0) $container.style.removeProperty("background-color"), $container.dataset.shadow = "true";else delete $container.dataset.shadow, $container.style.backgroundColor = `rgba(0, 0, 0, ${PREF_OPACITY_BG}%)`;$container.style.opacity = getStreamPref("stats.opacity.all") + "%", $container.style.fontSize = getStreamPref("stats.textSize");}hideSettingsUi() {if (this.isGlancing() && !getStreamPref("stats.quickGlance.enabled")) this.stop();}async render() {this.$container = CE("div", { class: "bx-stats-bar bx-gone" });let statKey;for (statKey in this.stats) {let stat = this.stats[statKey], $div = CE("div", {class: `bx-stat-${statKey}`,title: stat.name}, CE("label", !1, statKey.toUpperCase()), stat.$element);this.$container.appendChild($div);}this.refreshStyles(), document.documentElement.appendChild(this.$container);}static setupEvents() {BxEventBus.Stream.on("state.playing", () => {let PREF_STATS_QUICK_GLANCE = getStreamPref("stats.quickGlance.enabled"), PREF_STATS_SHOW_WHEN_PLAYING = getStreamPref("stats.showWhenPlaying"), streamStats = StreamStats.getInstance();if (PREF_STATS_SHOW_WHEN_PLAYING) streamStats.start();else if (PREF_STATS_QUICK_GLANCE) streamStats.quickGlanceSetup(), !PREF_STATS_SHOW_WHEN_PLAYING && streamStats.start(!0);});}static refreshStyles() {StreamStats.getInstance().refreshStyles();}} +class StreamStats {static instance;static getInstance = () => StreamStats.instance ?? (StreamStats.instance = new StreamStats);LOG_TAG = "StreamStats";intervalId;REFRESH_INTERVAL = 1000;stats = {time: {name: t("clock"),$element: CE("span")},play: {name: t("playtime"),$element: CE("span")},batt: {name: t("battery"),$element: CE("span")},ping: {name: t("stat-ping"),$element: CE("span")},jit: {name: t("jitter"),$element: CE("span")},fps: {name: t("stat-fps"),$element: CE("span")},btr: {name: t("stat-bitrate"),$element: CE("span")},dt: {name: t("stat-decode-time"),$element: CE("span")},pl: {name: t("stat-packets-lost"),$element: CE("span")},fl: {name: t("stat-frames-lost"),$element: CE("span")},dl: {name: t("downloaded"),$element: CE("span")},ul: {name: t("uploaded"),$element: CE("span")}};$container;boundOnStreamHudStateChanged;constructor() {BxLogger.info(this.LOG_TAG, "constructor()"), this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this), BxEventBus.Stream.on("ui.streamHud.expanded", this.boundOnStreamHudStateChanged), this.render();}async start(glancing = !1) {if (!this.isHidden() || glancing && this.isGlancing()) return;this.intervalId && clearInterval(this.intervalId), await this.update(!0), this.$container.classList.remove("bx-gone"), this.$container.dataset.display = glancing ? "glancing" : "fixed", this.intervalId = window.setInterval(this.update, this.REFRESH_INTERVAL);}async stop(glancing = !1) {if (glancing && !this.isGlancing()) return;this.intervalId && clearInterval(this.intervalId), this.intervalId = null, this.$container.removeAttribute("data-display"), this.$container.classList.add("bx-gone");}async toggle() {if (this.isGlancing()) this.$container && (this.$container.dataset.display = "fixed");else this.isHidden() ? await this.start() : await this.stop();}destroy() {this.stop(), this.hideSettingsUi();}isHidden = () => this.$container.classList.contains("bx-gone");isGlancing = () => this.$container.dataset.display === "glancing";onStreamHudStateChanged({ state }) {if (!getStreamPref("stats.quickGlance.enabled")) return;if (state === "expanded") this.isHidden() && this.start(!0);else this.stop(!0);}update = async (forceUpdate = !1) => {if (!forceUpdate && this.isHidden() || !STATES.currentStream.peerConnection) {this.destroy();return;}let PREF_STATS_CONDITIONAL_FORMATTING = getStreamPref("stats.colors"), grade = "", statsCollector = StreamStatsCollector.getInstance();await statsCollector.collect();let statKey;for (statKey in this.stats) {grade = "";let stat = this.stats[statKey], value = statsCollector.getStat(statKey), $element = stat.$element;if ($element.textContent = value.toString(), PREF_STATS_CONDITIONAL_FORMATTING && "grades" in value) grade = statsCollector.calculateGrade(value.current, value.grades);if ($element.dataset.grade !== grade) $element.dataset.grade = grade;}};refreshStyles() {let PREF_ITEMS = getStreamPref("stats.items"), PREF_OPACITY_BG = getStreamPref("stats.opacity.background"), $container = this.$container;if ($container.dataset.stats = "[" + PREF_ITEMS.join("][") + "]", $container.dataset.position = getStreamPref("stats.position"), PREF_OPACITY_BG === 0) $container.style.removeProperty("background-color"), $container.dataset.shadow = "true";else delete $container.dataset.shadow, $container.style.backgroundColor = `rgba(0, 0, 0, ${PREF_OPACITY_BG}%)`;$container.style.opacity = getStreamPref("stats.opacity.all") + "%", $container.style.fontSize = getStreamPref("stats.textSize");}hideSettingsUi() {if (this.isGlancing() && !getStreamPref("stats.quickGlance.enabled")) this.stop();}async render() {this.$container = CE("div", { class: "bx-stats-bar bx-gone" });let statKey;for (statKey in this.stats) {let stat = this.stats[statKey], $div = CE("div", {class: `bx-stat-${statKey}`,title: stat.name}, CE("label", !1, statKey.toUpperCase()), stat.$element);this.$container.appendChild($div);}this.refreshStyles(), document.documentElement.appendChild(this.$container);}static setupEvents() {BxEventBus.Stream.on("state.playing", () => {let PREF_STATS_QUICK_GLANCE = getStreamPref("stats.quickGlance.enabled"), PREF_STATS_SHOW_WHEN_PLAYING = getStreamPref("stats.showWhenPlaying"), streamStats = StreamStats.getInstance();if (PREF_STATS_SHOW_WHEN_PLAYING) streamStats.start();else if (PREF_STATS_QUICK_GLANCE) !PREF_STATS_SHOW_WHEN_PLAYING && streamStats.start(!0);});}static refreshStyles() {StreamStats.getInstance().refreshStyles();}} class KeyHelper {static NON_PRINTABLE_KEYS = {Backquote: "`",Minus: "-",Equal: "=",BracketLeft: "[",BracketRight: "]",Backslash: "\\",Semicolon: ";",Quote: "'",Comma: ",",Period: ".",Slash: "/",NumpadMultiply: "Numpad *",NumpadAdd: "Numpad +",NumpadSubtract: "Numpad -",NumpadDecimal: "Numpad .",NumpadDivide: "Numpad /",NumpadEqual: "Numpad =",Mouse0: "Left Click",Mouse2: "Right Click",Mouse1: "Middle Click",ScrollUp: "Scroll Up",ScrollDown: "Scroll Down",ScrollLeft: "Scroll Left",ScrollRight: "Scroll Right"};static getKeyFromEvent(e) {let code = null, modifiers;if (e instanceof KeyboardEvent) code = e.code || e.key, modifiers = 0, modifiers ^= e.ctrlKey ? 1 : 0, modifiers ^= e.shiftKey ? 2 : 0, modifiers ^= e.altKey ? 4 : 0;else if (e instanceof WheelEvent) {if (e.deltaY < 0) code = "ScrollUp";else if (e.deltaY > 0) code = "ScrollDown";else if (e.deltaX < 0) code = "ScrollLeft";else if (e.deltaX > 0) code = "ScrollRight";} else if (e instanceof MouseEvent) code = "Mouse" + e.button;if (code) {let results = { code };if (modifiers) results.modifiers = modifiers;return results;}return null;}static getFullKeyCodeFromEvent(e) {let key = KeyHelper.getKeyFromEvent(e);return key ? `${key.code}:${key.modifiers || 0}` : "";}static parseFullKeyCode(str) {if (!str) return null;let tmp = str.split(":"), code = tmp[0], modifiers = parseInt(tmp[1]);return {code,modifiers};}static codeToKeyName(key) {let { code, modifiers } = key, text = [KeyHelper.NON_PRINTABLE_KEYS[code] || code.startsWith("Key") && code.substring(3) || code.startsWith("Digit") && code.substring(5) || code.startsWith("Numpad") && "Numpad " + code.substring(6) || code.startsWith("Arrow") && "Arrow " + code.substring(5) || code.endsWith("Lock") && code.replace("Lock", " Lock") || code.endsWith("Left") && "Left " + code.replace("Left", "") || code.endsWith("Right") && "Right " + code.replace("Right", "") || code];if (modifiers && modifiers !== 0) {if (!code.startsWith("Control") && !code.startsWith("Shift") && !code.startsWith("Alt")) {if (modifiers & 2) text.unshift("Shift");if (modifiers & 4) text.unshift("Alt");if (modifiers & 1) text.unshift("Ctrl");}}return text.join(" + ");}} class PointerClient {static instance;static getInstance = () => PointerClient.instance ?? (PointerClient.instance = new PointerClient);LOG_TAG = "PointerClient";REQUIRED_PROTOCOL_VERSION = 2;socket;mkbHandler;constructor() {BxLogger.info(this.LOG_TAG, "constructor()");}start(port, mkbHandler) {if (!port) throw new Error("PointerServer port is 0");this.mkbHandler = mkbHandler, this.socket = new WebSocket(`ws://localhost:${port}`), this.socket.binaryType = "arraybuffer", this.socket.addEventListener("open", (event) => {BxLogger.info(this.LOG_TAG, "connected");}), this.socket.addEventListener("error", (event) => {BxLogger.error(this.LOG_TAG, event), Toast.show("Cannot setup mouse: " + event);}), this.socket.addEventListener("close", (event) => {this.socket = null;}), this.socket.addEventListener("message", (event) => {let dataView = new DataView(event.data), messageType = dataView.getInt8(0), offset = Int8Array.BYTES_PER_ELEMENT;switch (messageType) {case 127:let protocolVersion = this.onProtocolVersion(dataView, offset);if (BxLogger.info(this.LOG_TAG, "Protocol version", protocolVersion), protocolVersion !== this.REQUIRED_PROTOCOL_VERSION) alert("Required MKB protocol: " + protocolVersion), this.stop();break;case 1:this.onMove(dataView, offset);break;case 2:case 3:this.onPress(messageType, dataView, offset);break;case 4:this.onScroll(dataView, offset);break;case 5:this.onPointerCaptureChanged(dataView, offset);}});}onProtocolVersion(dataView, offset) {return dataView.getUint16(offset);}onMove(dataView, offset) {let x = dataView.getInt16(offset);offset += Int16Array.BYTES_PER_ELEMENT;let y = dataView.getInt16(offset);this.mkbHandler?.handleMouseMove({movementX: x,movementY: y});}onPress(messageType, dataView, offset) {let button = dataView.getUint8(offset);this.mkbHandler?.handleMouseClick({pointerButton: button,pressed: messageType === 2});}onScroll(dataView, offset) {let vScroll = dataView.getInt16(offset);offset += Int16Array.BYTES_PER_ELEMENT;let hScroll = dataView.getInt16(offset);this.mkbHandler?.handleMouseWheel({vertical: vScroll,horizontal: hScroll});}onPointerCaptureChanged(dataView, offset) {dataView.getInt8(offset) !== 1 && this.mkbHandler?.stop();}stop() {try {this.socket?.close();} catch (e) {}this.socket = null;}} class MouseDataProvider {mkbHandler;constructor(handler) {this.mkbHandler = handler;}init() {}destroy() {}} @@ -186,7 +186,7 @@ class BxNumberStepper extends HTMLInputElement {intervalId = null;isHolding;cont class SettingElement {static renderOptions(key, setting, currentValue, onChange) {let $control = CE("select", {tabindex: 0}), $parent;if (setting.optionsGroup) $parent = CE("optgroup", {label: setting.optionsGroup}), $control.appendChild($parent);else $parent = $control;for (let value in setting.options) {let label = setting.options[value], $option = CE("option", { value }, label);$parent.appendChild($option);}return $control.value = currentValue, onChange && $control.addEventListener("input", (e) => {let target = e.target, value = setting.type && setting.type === "number" ? parseInt(target.value) : target.value;!e.ignoreOnChange && onChange(e, value);}), $control.setValue = (value) => {$control.value = value;}, $control;}static renderMultipleOptions(key, setting, currentValue, onChange, params = {}) {let $control = CE("select", {multiple: !0,tabindex: 0}), totalOptions = Object.keys(setting.multipleOptions).length, size = params.size ? Math.min(params.size, totalOptions) : totalOptions;$control.setAttribute("size", size.toString());for (let value in setting.multipleOptions) {let label = setting.multipleOptions[value], $option = CE("option", { value }, label);$option.selected = currentValue.indexOf(value) > -1, $option.addEventListener("mousedown", function(e) {e.preventDefault();let target = e.target;target.selected = !target.selected;let $parent = target.parentElement;$parent.focus(), BxEvent.dispatch($parent, "input");}), $control.appendChild($option);}return $control.addEventListener("mousedown", function(e) {let self = this, orgScrollTop = self.scrollTop;window.setTimeout(() => self.scrollTop = orgScrollTop, 0);}), $control.addEventListener("mousemove", (e) => e.preventDefault()), onChange && $control.addEventListener("input", (e) => {let target = e.target, values = Array.from(target.selectedOptions).map((i) => i.value);!e.ignoreOnChange && onChange(e, values);}), Object.defineProperty($control, "value", {get() {return Array.from($control.options).filter((option) => option.selected).map((option) => option.value);},set(value) {let values = value.split(",");Array.from($control.options).forEach((option) => {option.selected = values.includes(option.value);});}}), $control;}static renderCheckbox(key, setting, currentValue, onChange) {let $control = CE("input", { type: "checkbox", tabindex: 0 });return $control.checked = currentValue, onChange && $control.addEventListener("input", (e) => {!e.ignoreOnChange && onChange(e, e.target.checked);}), $control.setValue = (value) => {$control.checked = !!value;}, $control;}static renderNumberStepper(key, setting, value, onChange, options = {}) {return BxNumberStepper.create(key, value, setting.min, setting.max, options, onChange);}static METHOD_MAP = {options: SettingElement.renderOptions,"multiple-options": SettingElement.renderMultipleOptions,"number-stepper": SettingElement.renderNumberStepper,checkbox: SettingElement.renderCheckbox};static render(type, key, setting, currentValue, onChange, options) {let method = SettingElement.METHOD_MAP[type], $control = method(...Array.from(arguments).slice(1));if (type !== "number-stepper") $control.id = `bx_setting_${escapeCssSelector(key)}`;if (type === "options" || type === "multiple-options") $control.name = $control.id;return $control;}static fromPref(key, onChange, overrideParams = {}) {let { definition, storage } = getPrefInfo(key);if (!definition) return null;let currentValue = storage.getSetting(key), type;if ("options" in definition) type = "options";else if ("multipleOptions" in definition) type = "multiple-options";else if (typeof definition.default === "number") type = "number-stepper";else type = "checkbox";let params = {};if ("params" in definition) params = Object.assign(overrideParams, definition.params || {});if (params.disabled) currentValue = definition.default;return SettingElement.render(type, key, definition, currentValue, (e, value) => {if (isGlobalPref(key)) setGlobalPref(key, value, "ui");else {let id = SettingsManager.getInstance().getTargetGameId();setGamePref(id, key, value, "ui");}onChange && onChange(e, value);}, params);}} class BxSelectElement extends HTMLSelectElement {isControllerFriendly;optionsList;indicatorsList;$indicators;visibleIndex;isMultiple;$select;$btnNext;$btnPrev;$label;$checkBox;static create($select, forceFriendly = !1) {let isControllerFriendly = forceFriendly || getGlobalPref("ui.controllerFriendly");if ($select.multiple && !isControllerFriendly) return $select.classList.add("bx-select"), $select;$select.removeAttribute("tabindex");let $wrapper = CE("div", {class: "bx-select",_dataset: {controllerFriendly: isControllerFriendly}});if ($select.classList.contains("bx-full-width")) $wrapper.classList.add("bx-full-width");let $content, self = $wrapper;self.isControllerFriendly = isControllerFriendly, self.isMultiple = $select.multiple, self.visibleIndex = $select.selectedIndex, self.$select = $select, self.optionsList = Array.from($select.querySelectorAll("option")), self.$indicators = CE("div", { class: "bx-select-indicators" }), self.indicatorsList = [];let $btnPrev, $btnNext;if (isControllerFriendly) {$btnPrev = createButton({label: "<",style: 64}), $btnNext = createButton({label: ">",style: 64}), setNearby($wrapper, {orientation: "horizontal",focus: $btnNext}), self.$btnNext = $btnNext, self.$btnPrev = $btnPrev;let boundOnPrevNext = BxSelectElement.onPrevNext.bind(self);$btnPrev.addEventListener("click", boundOnPrevNext), $btnNext.addEventListener("click", boundOnPrevNext);} else $select.addEventListener("change", (e) => {self.visibleIndex = $select.selectedIndex, BxSelectElement.resetIndicators.call(self), BxSelectElement.render.call(self);});if (self.isMultiple) $content = CE("button", {class: "bx-select-value bx-focusable",tabindex: 0}, CE("div", !1, self.$checkBox = CE("input", { type: "checkbox" }), self.$label = CE("span", !1, "")), self.$indicators), $content.addEventListener("click", (e) => {self.$checkBox.click();}), self.$checkBox.addEventListener("input", (e) => {let $option = BxSelectElement.getOptionAtIndex.call(self, self.visibleIndex);$option && ($option.selected = e.target.checked), BxEvent.dispatch($select, "input");});else $content = CE("div", !1, self.$label = CE("label", { for: $select.id + "_checkbox" }, ""), self.$indicators);return $select.addEventListener("input", BxSelectElement.render.bind(self)), new MutationObserver((mutationList, observer2) => {mutationList.forEach((mutation) => {if (mutation.type === "childList" || mutation.type === "attributes") self.visibleIndex = $select.selectedIndex, self.optionsList = Array.from($select.querySelectorAll("option")), BxSelectElement.resetIndicators.call(self), BxSelectElement.render.call(self);});}).observe($select, {subtree: !0,childList: !0,attributes: !0}), self.append($select, $btnPrev || "", $content, $btnNext || ""), BxSelectElement.resetIndicators.call(self), BxSelectElement.render.call(self), Object.defineProperty(self, "value", {get() {return $select.value;},set(value) {self.optionsList = Array.from($select.querySelectorAll("option")), $select.value = value, self.visibleIndex = $select.selectedIndex, BxSelectElement.resetIndicators.call(self), BxSelectElement.render.call(self);}}), Object.defineProperty(self, "disabled", {get() {return $select.disabled;},set(value) {$select.disabled = value;}}), self.addEventListener = function() {$select.addEventListener.apply($select, arguments);}, self.removeEventListener = function() {$select.removeEventListener.apply($select, arguments);}, self.dispatchEvent = function() {return $select.dispatchEvent.apply($select, arguments);}, self.appendChild = function(node) {return $select.appendChild(node), node;}, self;}static resetIndicators() {let {optionsList,indicatorsList,$indicators} = this, targetSize = optionsList.length;if (indicatorsList.length > targetSize) while (indicatorsList.length > targetSize)indicatorsList.pop()?.remove();else if (indicatorsList.length < targetSize) while (indicatorsList.length < targetSize) {let $indicator = CE("span", {});indicatorsList.push($indicator), $indicators.appendChild($indicator);}for (let $indicator of indicatorsList)clearDataSet($indicator);$indicators.classList.toggle("bx-invisible", targetSize <= 1);}static getOptionAtIndex(index) {return this.optionsList[index];}static render(e) {let {$label,$btnNext,$btnPrev,$checkBox,optionsList,indicatorsList} = this;if (e && e.manualTrigger) this.visibleIndex = this.$select.selectedIndex;this.visibleIndex = BxSelectElement.normalizeIndex.call(this, this.visibleIndex);let $option = BxSelectElement.getOptionAtIndex.call(this, this.visibleIndex), content = "";if ($option) {let $parent = $option.parentElement, hasLabel = $parent instanceof HTMLOptGroupElement || this.$select.querySelector("optgroup");if (content = $option.dataset.label || $option.textContent || "", content && hasLabel) {let groupLabel = $parent instanceof HTMLOptGroupElement ? $parent.label : " ";$label.innerHTML = "";let fragment = document.createDocumentFragment();fragment.appendChild(CE("span", !1, groupLabel)), fragment.appendChild(document.createTextNode(content)), $label.appendChild(fragment);} else $label.textContent = content;} else $label.textContent = content;if ($label.classList.toggle("bx-line-through", $option && $option.disabled), this.isMultiple) $checkBox.checked = $option?.selected || !1, $checkBox.classList.toggle("bx-gone", !content);let disableButtons = optionsList.length <= 1;$btnPrev?.classList.toggle("bx-gone", disableButtons), $btnNext?.classList.toggle("bx-gone", disableButtons);for (let i = 0;i < optionsList.length; i++) {let $option2 = optionsList[i], $indicator = indicatorsList[i];if (!$option2 || !$indicator) continue;if (clearDataSet($indicator), $option2.selected) $indicator.dataset.selected = "true";if ($option2.index === this.visibleIndex) $indicator.dataset.highlighted = "true";}}static normalizeIndex(index) {return Math.min(Math.max(index, 0), this.optionsList.length - 1);}static onPrevNext(e) {if (!e.target) return;let {$btnNext,$select,isMultiple,visibleIndex: currentIndex} = this, newIndex = e.target.closest("button") === $btnNext ? currentIndex + 1 : currentIndex - 1;if (newIndex > this.optionsList.length - 1) newIndex = 0;else if (newIndex < 0) newIndex = this.optionsList.length - 1;if (newIndex = BxSelectElement.normalizeIndex.call(this, newIndex), this.visibleIndex = newIndex, !isMultiple && newIndex !== currentIndex) $select.selectedIndex = newIndex;if (isMultiple) BxSelectElement.render.call(this);else BxEvent.dispatch($select, "input");}} class XboxApi {static CACHED_TITLES = {};static async getProductTitle(xboxTitleId) {if (xboxTitleId = xboxTitleId.toString(), XboxApi.CACHED_TITLES[xboxTitleId]) return XboxApi.CACHED_TITLES[xboxTitleId];let title;try {let url = `https://displaycatalog.mp.microsoft.com/v7.0/products/lookup?market=US&languages=en&value=${xboxTitleId}&alternateId=XboxTitleId&fieldsTemplate=browse`;title = (await (await NATIVE_FETCH(url)).json()).Products[0].LocalizedProperties[0].ProductTitle;} catch (e) {title = "Unknown Game #" + xboxTitleId;}return XboxApi.CACHED_TITLES[xboxTitleId] = title, title;}} -class SettingsManager {static instance;static getInstance = () => SettingsManager.instance ?? (SettingsManager.instance = new SettingsManager);$streamSettingsSelection;$tips;playingGameId = -1;targetGameId = -1;SETTINGS = {"localCoOp.enabled": {onChange: () => {BxExposed.toggleLocalCoOp(getStreamPref("localCoOp.enabled"));}},"deviceVibration.mode": {onChange: StreamSettings.refreshControllerSettings},"deviceVibration.intensity": {onChange: StreamSettings.refreshControllerSettings},"controller.pollingRate": {onChange: StreamSettings.refreshControllerSettings},"controller.settings": {onChange: StreamSettings.refreshControllerSettings},"nativeMkb.scroll.sensitivityX": {onChange: () => {let value = getStreamPref("nativeMkb.scroll.sensitivityX");NativeMkbHandler.getInstance()?.setHorizontalScrollMultiplier(value / 100);}},"nativeMkb.scroll.sensitivityY": {onChange: () => {let value = getStreamPref("nativeMkb.scroll.sensitivityY");NativeMkbHandler.getInstance()?.setVerticalScrollMultiplier(value / 100);}},"video.player.type": {onChange: updateVideoPlayer,onChangeUi: onChangeVideoPlayerType},"video.player.powerPreference": {onChange: () => {if (!STATES.currentStream.streamPlayerManager) return;updateVideoPlayer();}},"video.processing": {onChange: updateVideoPlayer},"video.processing.sharpness": {onChange: updateVideoPlayer},"video.maxFps": {onChange: () => {let value = getStreamPref("video.maxFps");limitVideoPlayerFps(value);}},"video.ratio": {onChange: updateVideoPlayer},"video.brightness": {onChange: updateVideoPlayer},"video.contrast": {onChange: updateVideoPlayer},"video.saturation": {onChange: updateVideoPlayer},"video.position": {onChange: updateVideoPlayer},"audio.volume": {onChange: () => {let value = getStreamPref("audio.volume");SoundShortcut.setGainNodeVolume(value);}},"stats.items": {onChange: StreamStats.refreshStyles},"stats.quickGlance.enabled": {onChange: () => {let value = getStreamPref("stats.quickGlance.enabled"), streamStats = StreamStats.getInstance();value ? streamStats.quickGlanceSetup() : streamStats.quickGlanceStop();}},"stats.position": {onChange: StreamStats.refreshStyles},"stats.textSize": {onChange: StreamStats.refreshStyles},"stats.opacity.all": {onChange: StreamStats.refreshStyles},"stats.opacity.background": {onChange: StreamStats.refreshStyles},"stats.colors": {onChange: StreamStats.refreshStyles},"mkb.p1.preset.mappingId": {onChange: StreamSettings.refreshMkbSettings},"mkb.p1.slot": {onChange: () => {EmulatedMkbHandler.getInstance()?.resetXcloudGamepads();}},"keyboardShortcuts.preset.inGameId": {onChange: StreamSettings.refreshKeyboardShortcuts}};constructor() {BxEventBus.Stream.on("setting.changed", (data) => {if (isStreamPref(data.settingKey)) this.updateStreamElement(data.settingKey);}), BxEventBus.Stream.on("gameSettings.switched", ({ id }) => {this.switchGameSettings(id);}), this.renderStreamSettingsSelection();}updateStreamElement(key, onChanges, onChangeUis) {let info = this.SETTINGS[key];if (info.onChangeUi) if (onChangeUis) onChangeUis.add(info.onChangeUi);else info.onChangeUi();if (info.onChange && STATES.isPlaying) if (onChanges) onChanges.add(info.onChange);else info.onChange();let $elm = info.$element;if (!$elm) return;let value = getGamePref(this.targetGameId, key, !0);if ("setValue" in $elm) $elm.setValue(value);else $elm.value = value.toString();this.updateDataset($elm, key);}switchGameSettings(id) {if (setGameIdPref(id), this.targetGameId === id) return;let onChanges = new Set, onChangeUis = new Set, oldGameId = this.targetGameId;this.targetGameId = id;let key;for (key in this.SETTINGS) {if (!isStreamPref(key)) continue;let oldValue = getGamePref(oldGameId, key, !0), newValue = getGamePref(this.targetGameId, key, !0);if (oldValue === newValue) continue;this.updateStreamElement(key, onChanges, onChangeUis);}onChangeUis.forEach((fn) => fn && fn()), onChanges.forEach((fn) => fn && fn()), this.$tips.classList.toggle("bx-gone", id < 0);}setElement(pref, $elm) {if (!this.SETTINGS[pref]) this.SETTINGS[pref] = {};this.updateDataset($elm, pref), this.SETTINGS[pref].$element = $elm;}getElement(pref, params) {if (!this.SETTINGS[pref]) this.SETTINGS[pref] = {};let $elm = this.SETTINGS[pref].$element;if (!$elm) $elm = SettingElement.fromPref(pref, null, params), this.SETTINGS[pref].$element = $elm;return this.updateDataset($elm, pref), $elm;}hasElement(pref) {return !!this.SETTINGS[pref]?.$element;}updateDataset($elm, pref) {if (this.targetGameId === this.playingGameId && hasGamePref(this.playingGameId, pref)) $elm.dataset.override = "true";else delete $elm.dataset.override;}renderStreamSettingsSelection() {this.$tips = CE("p", { class: "bx-gone" }, `⇐ Q ⟶: ${t("reset-highlighted-setting")}`);let $select = BxSelectElement.create(CE("select", !1, CE("optgroup", { label: t("settings-for") }, CE("option", { value: -1 }, t("all-games")))), !0);$select.addEventListener("input", (e) => {let id = parseInt($select.value);BxEventBus.Stream.emit("gameSettings.switched", { id });}), this.$streamSettingsSelection = CE("div", {class: "bx-stream-settings-selection bx-gone",_nearby: { orientation: "vertical" }}, CE("div", !1, $select), this.$tips), BxEventBus.Stream.on("xboxTitleId.changed", async ({ id }) => {this.playingGameId = id;let gameSettings = STORAGE.Stream.getGameSettings(id), selectedId = gameSettings && !gameSettings.isEmpty() ? id : -1;setGameIdPref(selectedId);let $optGroup = $select.querySelector("optgroup");while ($optGroup.childElementCount > 1)$optGroup.lastElementChild?.remove();if (id >= 0) {let title = id === 0 ? "Xbox" : await XboxApi.getProductTitle(id);$optGroup.appendChild(CE("option", {value: id}, title));}$select.value = selectedId.toString(), BxEventBus.Stream.emit("gameSettings.switched", { id: selectedId });});}getStreamSettingsSelection() {return this.$streamSettingsSelection;}getTargetGameId() {return this.targetGameId;}} +class SettingsManager {static instance;static getInstance = () => SettingsManager.instance ?? (SettingsManager.instance = new SettingsManager);$streamSettingsSelection;$tips;playingGameId = -1;targetGameId = -1;SETTINGS = {"localCoOp.enabled": {onChange: () => {BxExposed.toggleLocalCoOp(getStreamPref("localCoOp.enabled"));}},"deviceVibration.mode": {onChange: StreamSettings.refreshControllerSettings},"deviceVibration.intensity": {onChange: StreamSettings.refreshControllerSettings},"controller.pollingRate": {onChange: StreamSettings.refreshControllerSettings},"controller.settings": {onChange: StreamSettings.refreshControllerSettings},"nativeMkb.scroll.sensitivityX": {onChange: () => {let value = getStreamPref("nativeMkb.scroll.sensitivityX");NativeMkbHandler.getInstance()?.setHorizontalScrollMultiplier(value / 100);}},"nativeMkb.scroll.sensitivityY": {onChange: () => {let value = getStreamPref("nativeMkb.scroll.sensitivityY");NativeMkbHandler.getInstance()?.setVerticalScrollMultiplier(value / 100);}},"video.player.type": {onChange: updateVideoPlayer,onChangeUi: onChangeVideoPlayerType},"video.player.powerPreference": {onChange: () => {if (!STATES.currentStream.streamPlayerManager) return;updateVideoPlayer();}},"video.processing": {onChange: updateVideoPlayer},"video.processing.sharpness": {onChange: updateVideoPlayer},"video.maxFps": {onChange: () => {let value = getStreamPref("video.maxFps");limitVideoPlayerFps(value);}},"video.ratio": {onChange: updateVideoPlayer},"video.brightness": {onChange: updateVideoPlayer},"video.contrast": {onChange: updateVideoPlayer},"video.saturation": {onChange: updateVideoPlayer},"video.position": {onChange: updateVideoPlayer},"audio.volume": {onChange: () => {let value = getStreamPref("audio.volume");SoundShortcut.setGainNodeVolume(value);}},"stats.items": {onChange: StreamStats.refreshStyles},"stats.quickGlance.enabled": {onChange: () => {if (!getStreamPref("stats.quickGlance.enabled")) StreamStats.getInstance().stop(!0);}},"stats.position": {onChange: StreamStats.refreshStyles},"stats.textSize": {onChange: StreamStats.refreshStyles},"stats.opacity.all": {onChange: StreamStats.refreshStyles},"stats.opacity.background": {onChange: StreamStats.refreshStyles},"stats.colors": {onChange: StreamStats.refreshStyles},"mkb.p1.preset.mappingId": {onChange: StreamSettings.refreshMkbSettings},"mkb.p1.slot": {onChange: () => {EmulatedMkbHandler.getInstance()?.resetXcloudGamepads();}},"keyboardShortcuts.preset.inGameId": {onChange: StreamSettings.refreshKeyboardShortcuts}};constructor() {BxEventBus.Stream.on("setting.changed", (data) => {if (isStreamPref(data.settingKey)) this.updateStreamElement(data.settingKey);}), BxEventBus.Stream.on("gameSettings.switched", ({ id }) => {this.switchGameSettings(id);}), this.renderStreamSettingsSelection();}updateStreamElement(key, onChanges, onChangeUis) {let info = this.SETTINGS[key];if (info.onChangeUi) if (onChangeUis) onChangeUis.add(info.onChangeUi);else info.onChangeUi();if (info.onChange && STATES.isPlaying) if (onChanges) onChanges.add(info.onChange);else info.onChange();let $elm = info.$element;if (!$elm) return;let value = getGamePref(this.targetGameId, key, !0);if ("setValue" in $elm) $elm.setValue(value);else $elm.value = value.toString();this.updateDataset($elm, key);}switchGameSettings(id) {if (setGameIdPref(id), this.targetGameId === id) return;let onChanges = new Set, onChangeUis = new Set, oldGameId = this.targetGameId;this.targetGameId = id;let key;for (key in this.SETTINGS) {if (!isStreamPref(key)) continue;let oldValue = getGamePref(oldGameId, key, !0), newValue = getGamePref(this.targetGameId, key, !0);if (oldValue === newValue) continue;this.updateStreamElement(key, onChanges, onChangeUis);}onChangeUis.forEach((fn) => fn && fn()), onChanges.forEach((fn) => fn && fn()), this.$tips.classList.toggle("bx-gone", id < 0);}setElement(pref, $elm) {if (!this.SETTINGS[pref]) this.SETTINGS[pref] = {};this.updateDataset($elm, pref), this.SETTINGS[pref].$element = $elm;}getElement(pref, params) {if (!this.SETTINGS[pref]) this.SETTINGS[pref] = {};let $elm = this.SETTINGS[pref].$element;if (!$elm) $elm = SettingElement.fromPref(pref, null, params), this.SETTINGS[pref].$element = $elm;return this.updateDataset($elm, pref), $elm;}hasElement(pref) {return !!this.SETTINGS[pref]?.$element;}updateDataset($elm, pref) {if (this.targetGameId === this.playingGameId && hasGamePref(this.playingGameId, pref)) $elm.dataset.override = "true";else delete $elm.dataset.override;}renderStreamSettingsSelection() {this.$tips = CE("p", { class: "bx-gone" }, `⇐ Q ⟶: ${t("reset-highlighted-setting")}`);let $select = BxSelectElement.create(CE("select", !1, CE("optgroup", { label: t("settings-for") }, CE("option", { value: -1 }, t("all-games")))), !0);$select.addEventListener("input", (e) => {let id = parseInt($select.value);BxEventBus.Stream.emit("gameSettings.switched", { id });}), this.$streamSettingsSelection = CE("div", {class: "bx-stream-settings-selection bx-gone",_nearby: { orientation: "vertical" }}, CE("div", !1, $select), this.$tips), BxEventBus.Stream.on("xboxTitleId.changed", async ({ id }) => {this.playingGameId = id;let gameSettings = STORAGE.Stream.getGameSettings(id), selectedId = gameSettings && !gameSettings.isEmpty() ? id : -1;setGameIdPref(selectedId);let $optGroup = $select.querySelector("optgroup");while ($optGroup.childElementCount > 1)$optGroup.lastElementChild?.remove();if (id >= 0) {let title = id === 0 ? "Xbox" : await XboxApi.getProductTitle(id);$optGroup.appendChild(CE("option", {value: id}, title));}$select.value = selectedId.toString(), BxEventBus.Stream.emit("gameSettings.switched", { id: selectedId });});}getStreamSettingsSelection() {return this.$streamSettingsSelection;}getTargetGameId() {return this.targetGameId;}} function onChangeVideoPlayerType() {let playerType = getStreamPref("video.player.type"), settingsManager = SettingsManager.getInstance();if (!settingsManager.hasElement("video.processing")) return;let isDisabled = !1, $videoProcessing = settingsManager.getElement("video.processing"), $videoSharpness = settingsManager.getElement("video.processing.sharpness"), $videoPowerPreference = settingsManager.getElement("video.player.powerPreference"), $videoMaxFps = settingsManager.getElement("video.maxFps"), $optCas = $videoProcessing.querySelector(`option[value=${"cas"}]`);if (playerType === "default") {if ($videoProcessing.value = "usm", setStreamPref("video.processing", "usm", "direct"), $optCas && ($optCas.disabled = !0), UserAgent.isSafari()) isDisabled = !0;} else $optCas && ($optCas.disabled = !1);$videoProcessing.disabled = isDisabled, $videoSharpness.dataset.disabled = isDisabled.toString(), $videoPowerPreference.closest(".bx-settings-row").classList.toggle("bx-gone", playerType !== "webgl2"), $videoMaxFps.closest(".bx-settings-row").classList.toggle("bx-gone", playerType === "default");} function limitVideoPlayerFps(targetFps) {STATES.currentStream.streamPlayerManager?.getCanvasPlayer()?.setTargetFps(targetFps);} function updateVideoPlayer() {let streamPlayerManager = STATES.currentStream.streamPlayerManager;if (!streamPlayerManager) return;let options = {processing: getStreamPref("video.processing"),sharpness: getStreamPref("video.processing.sharpness"),saturation: getStreamPref("video.saturation"),contrast: getStreamPref("video.contrast"),brightness: getStreamPref("video.brightness")};streamPlayerManager.switchPlayerType(getStreamPref("video.player.type")), limitVideoPlayerFps(getStreamPref("video.maxFps")), streamPlayerManager.updateOptions(options), streamPlayerManager.refreshPlayer();} @@ -225,7 +225,7 @@ if (gamepadFound) {return;} ${autoOffCode} const titleInfo = window.BX_EXPOSED.getTitleInfo(); if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFakeTouchSupport) {return;} -`;return str = str.replace(text, newCode + text), str;},streamCombineSources(str) {let text = "this.useCombinedAudioVideoStream=!!this.deviceInformation.isTizen";if (!str.includes(text)) return !1;return str = str.replace(text, "this.useCombinedAudioVideoStream=true"), str;},patchStreamHud(str) {let text = "let{onCollapse";if (!str.includes(text)) return !1;let newCode = streamhud_default;if (getGlobalPref("touchController.mode") === "off") newCode += "options.canShowTakHUD = false;";return str = str.replace(text, newCode + text), str;},broadcastPollingMode(str) {let text = ".setPollingMode=e=>{";if (!str.includes(text)) return !1;let newCode = ` +`;return str = str.replace(text, newCode + text), str;},streamCombineSources(str) {let text = "this.useCombinedAudioVideoStream=!!this.deviceInformation.isTizen";if (!str.includes(text)) return !1;return str = str.replace(text, "this.useCombinedAudioVideoStream=true"), str;},patchStreamHud(str) {let index = str.indexOf("let{onCollapse");if (index < 0) return !1;let newCode = streamhud_default;if (getGlobalPref("touchController.mode") === "off") newCode += "options.canShowTakHUD = false;";return str = PatcherUtils.insertAt(str, index, newCode), str;},broadcastPollingMode(str) {let text = ".setPollingMode=e=>{";if (!str.includes(text)) return !1;let newCode = ` window.BX_STREAM_SETTINGS.xCloudPollingMode = e.toLowerCase(); BxEvent.dispatch(window, BxEvent.XCLOUD_POLLING_MODE_CHANGED); `;return str = str.replace(text, text + newCode), str;},patchGamepadPolling(str) {let index = str.indexOf(".shouldHandleGamepadInput)())return void");if (index < 0) return !1;return index = str.indexOf("{", index - 20) + 1, str = str.substring(0, index) + "if (window.BX_EXPOSED.disableGamepadPolling) return;" + str.substring(index), str;},patchXcloudTitleInfo(str) {let text = "async cloudConnect", index = str.indexOf(text);if (index < 0) return !1;let backetIndex = str.indexOf("{", index), params = str.substring(index, backetIndex).match(/\(([^)]+)\)/)[1];if (!params) return !1;let titleInfoVar = params.split(",")[0], newCode = ` diff --git a/src/modules/patcher/patcher.ts b/src/modules/patcher/patcher.ts index 88824eb..5d3f402 100755 --- a/src/modules/patcher/patcher.ts +++ b/src/modules/patcher/patcher.ts @@ -422,8 +422,8 @@ 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; } @@ -434,7 +434,7 @@ if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFak newCode += 'options.canShowTakHUD = false;'; } - str = str.replace(text, newCode + text); + str = PatcherUtils.insertAt(str, index, newCode); return str; }, diff --git a/src/modules/settings-manager.ts b/src/modules/settings-manager.ts index 50a4d99..8545a6f 100644 --- a/src/modules/settings-manager.ts +++ b/src/modules/settings-manager.ts @@ -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]: { diff --git a/src/modules/stream/stream-stats.ts b/src/modules/stream/stream-stats.ts index b61bddc..ee5b34b 100755 --- a/src/modules/stream/stream-stats.ts +++ b/src/modules/stream/stream-stats.ts @@ -75,6 +75,8 @@ export class StreamStats { BxLogger.info(this.LOG_TAG, 'constructor()'); this.boundOnStreamHudStateChanged = this.onStreamHudStateChanged.bind(this); + BxEventBus.Stream.on('ui.streamHud.expanded', this.boundOnStreamHudStateChanged); + this.render(); } @@ -114,7 +116,6 @@ export class StreamStats { destroy() { this.stop(); - this.quickGlanceStop(); this.hideSettingsUi(); } @@ -122,6 +123,10 @@ export class StreamStats { isGlancing = () => this.$container.dataset.display === 'glancing'; onStreamHudStateChanged({ state }: { state: string }) { + if (!getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED)) { + return; + } + if (state === 'expanded') { this.isHidden() && this.start(true); } else { @@ -129,18 +134,6 @@ export class StreamStats { } } - quickGlanceSetup() { - if (!STATES.isPlaying) { - return; - } - - BxEventBus.Stream.on('ui.streamHud.expanded', this.boundOnStreamHudStateChanged); - } - - quickGlanceStop() { - BxEventBus.Stream.off('ui.streamHud.expanded', this.boundOnStreamHudStateChanged); - } - private update = async (forceUpdate=false) => { if ((!forceUpdate && this.isHidden()) || !STATES.currentStream.peerConnection) { this.destroy(); @@ -232,7 +225,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); }