Compare commits

...

189 Commits

Author SHA1 Message Date
057adb62df Bump version to 6.4.8 2025-03-27 07:36:23 +07:00
98e8ff4783 Fix header's style in other pages 2025-03-27 07:26:05 +07:00
f5e1b0a9fa Upgrade bun 2025-03-27 07:19:50 +07:00
8ea3503dd3 Update header's style for small screens 2025-03-27 07:19:08 +07:00
b733d55e9e Bump version to 6.4.7 2025-03-21 06:37:13 +07:00
317ac9017b Fix custom input icons not showing in game card 2025-03-21 06:28:59 +07:00
b8c62a1f4d Fix Remote Play's achievement notification 2025-03-21 05:37:38 +07:00
7332528f72 Remove "enableConsoleLogging" patch from Stream page 2025-03-21 05:29:14 +07:00
d063500aae Fix not detecting new xCloud version correctly 2025-03-21 05:26:09 +07:00
29ff1bc09c Bump version to 6.4.6 2025-03-11 17:49:46 +07:00
8998daf14c Always check for new version 2025-03-11 17:49:15 +07:00
8bdad8b319 Add Czech translations 2025-03-11 17:43:49 +07:00
5dd3ebdea1 Fix unable to connect to console using Remote Play in some cases 2025-03-11 17:27:59 +07:00
55d7796f96 Bump version to 6.4.5 2025-02-21 07:17:23 +07:00
0b02a758db Fix custom touch control not working in Remote Play (#674) 2025-02-21 07:10:54 +07:00
3b2abbf6bb Fix video in detail page not playing (#679) 2025-02-21 06:55:55 +07:00
43a66db697 Fix patches 2025-02-21 06:46:29 +07:00
a3130101f4 Bump version to 6.4.4 2025-02-14 09:04:49 +07:00
3483672554 Fix Remote Play stopped working 2025-02-14 09:04:33 +07:00
75d7443e0f Bump version to 6.4.3 2025-02-14 06:25:04 +07:00
b5d2d0fdec Enable "1080p (HQ)" setting for Remote Play 2025-02-14 06:24:52 +07:00
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
63e5e90443 Bump version to 6.4.0 2025-02-05 20:25:15 +07:00
9034c173e7 Update translations 2025-02-05 20:22:39 +07:00
5949e1e411 Disable header & footer 2025-02-05 20:11:24 +07:00
5ce7ade574 Optimize CSS selectors 2025-02-05 17:29:21 +07:00
e45537adf0 Add EnableWebGPURenderer flag 2025-02-04 21:17:43 +07:00
f9c9dc9684 Remove "See All Games" 's background color in OLED theme 2025-02-04 21:07:04 +07:00
ff9a7962c5 Hide Friends section 2025-02-04 20:54:56 +07:00
d4f070f6bb Allow hiding BYOG section 2025-02-04 20:51:50 +07:00
66b1f92f4c Disable dropdown's animation 2025-02-04 20:24:46 +07:00
7a69e7f284 Add OLED theme (#658) 2025-02-04 20:20:48 +07:00
664e865b82 Hide WebGPU renderer behind EnableWebGPURenderer flag 2025-02-04 19:29:43 +07:00
7894dea5ff Allow hiding "Recently added, "Leaving soon" and "Genres" sections (#658) 2025-02-03 21:25:38 +07:00
fd665b6fcd Add WebGPU renderer (#648) 2025-02-02 21:37:21 +07:00
39ecef976c Optimize WebGL2 2025-02-02 21:12:21 +07:00
0d5fa0fc96 Optimize WebGPU 2025-02-02 17:57:46 +07:00
fccd84b7ef Optimize WebGPU 2025-02-02 12:18:00 +07:00
eb1c027c30 Optimize WebGPU 2025-02-01 20:56:33 +07:00
6a211db52e Test WebGPU 2025-02-01 17:14:31 +07:00
17dc7996b1 Replace alwaysTriggerOnChange with onChangeUi 2025-01-30 16:39:52 +07:00
fe418e6918 Automatically reset game setting's value if it has the same value as global's 2025-01-30 16:10:51 +07:00
96de61c301 Bump version to 6.3.1 2025-01-29 17:31:25 +07:00
54a3e144a6 Show "Unknown Game" when unable to get game's title 2025-01-29 15:47:29 +07:00
277a830d99 Fix unable to reset Virtual controller's preset & Keyboard shortcuts' preset 2025-01-29 15:28:04 +07:00
0ef8fe18ac Fix calling definition.ready() multiple times 2025-01-29 15:06:34 +07:00
706665713f Only switch to game settings if it's not empty (#652) 2025-01-29 11:15:51 +07:00
bf23943da8 Bump version to 6.3.0 2025-01-29 05:26:53 +07:00
6e31caa4fc Migrate Stream settings in Global storage to Stream storage 2025-01-28 19:22:48 +07:00
91f9d76c57 Increase title's font-size 2025-01-28 17:20:59 +07:00
f81627ac7a Update Toast's style 2025-01-28 16:04:53 +07:00
7c94afacc2 Delete lite.js 2025-01-28 15:34:19 +07:00
8f37263386 Build pretty.js 2025-01-28 15:15:19 +07:00
d281db5767 Don't store invalid keys in localStorage 2025-01-28 14:54:57 +07:00
d638700e03 Update dists 2025-01-28 11:29:42 +07:00
e3f971845f Game-specific settings (#623) 2025-01-28 11:28:26 +07:00
91c8172564 Update better-xcloud.user.js 2025-01-28 06:33:10 +07:00
ee4055e169 Update better-xcloud.user.js 2025-01-28 06:23:22 +07:00
84415de09f Update better-xcloud.user.js 2025-01-27 19:56:27 +07:00
d3ef988af7 Fix problem with controller in Settings dialog 2025-01-16 21:50:23 +07:00
0bf4c289db Bump version to 6.2.1 2025-01-16 20:37:00 +07:00
c8865bd8a0 Re-arrange patches 2025-01-16 20:26:15 +07:00
a2f062d9d5 Lite: remove LocalCoOpManager 2025-01-16 20:05:51 +07:00
b6d4c51ca9 Update dists 2025-01-16 16:49:08 +07:00
785df72972 Lite: hide unsupported features 2025-01-16 16:37:18 +07:00
48da8bc527 Update Remote Play dialog's styling 2025-01-16 07:14:52 +07:00
f9cf02b2da Fix the Y button in default MKB preset 2025-01-16 06:46:12 +07:00
77e0f2d8ba Lite: disable navigating using gamepad in Settings dialog 2025-01-16 06:45:12 +07:00
d05a68c470 Fix exception when viewing deviceCode page 2025-01-15 21:30:50 +07:00
153873e034 Reduce Virtual Controller's input latency 2025-01-08 21:16:07 +07:00
8d7fbf2804 Bump version to 6.2.0 2025-01-04 19:39:40 +07:00
488b0dfef2 Show local co-op icon in settings 2025-01-04 18:43:24 +07:00
b3697df8dc Set background image's quality 2025-01-04 18:30:53 +07:00
de21549e0d Hide image quality's slider 2025-01-04 13:14:51 +07:00
097164b92e Set image quality 2025-01-04 12:33:47 +07:00
3fe6d97133 Update dists 2025-01-04 10:31:45 +07:00
328fdf46ea Don't render controller icon in game card 2025-01-04 10:31:13 +07:00
e4dbdea9a5 await requestPointerLock 2025-01-03 20:43:21 +07:00
f13ce94cf2 Update dists 2025-01-03 20:04:25 +07:00
a6c19fec15 Use Set() for local co-op list 2025-01-03 20:03:56 +07:00
6448a00271 Show local co-op icon in details page 2025-01-03 19:49:40 +07:00
68b29ecb50 Fix not applying class names to local co-op icon 2025-01-03 17:01:51 +07:00
90f89a0244 Show local co-op icon in game card 2025-01-02 21:39:27 +07:00
9862f794cf Update button's styling 2024-12-31 06:57:22 +07:00
e109cdec6a Attempt to fix problem with unadjustedMovement (#628) 2024-12-31 06:52:50 +07:00
40d1878fb2 Add icon to Better xCloud button 2024-12-29 15:41:35 +07:00
95f842d9f6 Update 02-feature-request.yml 2024-12-29 08:35:21 +07:00
d691ea0cf6 Bump version to 6.1.1 2024-12-28 20:46:39 +07:00
3c05fdcb6d Update README.md 2024-12-28 20:42:51 +07:00
0cff0b3d3f Update README.md 2024-12-28 20:38:46 +07:00
6ea47aed48 Add logos 2024-12-28 20:36:56 +07:00
c8142e5079 Cleanup 2024-12-28 20:36:34 +07:00
ef85175a91 Update dists 2024-12-28 17:04:40 +07:00
116640eb32 Fix not releasing pointer lock after quitting the game 2024-12-28 17:04:17 +07:00
54e28ce350 Fix mouse wheel bug (contd) 2024-12-28 17:04:01 +07:00
0cd2c02ed6 Update dists 2024-12-28 16:33:25 +07:00
e585264e8c Fix mouse wheel bug (#600) 2024-12-28 16:33:10 +07:00
6a133186b8 Check MKB's protocol version 2024-12-28 16:32:52 +07:00
91b5434952 Update Bx icon 2024-12-27 19:45:37 +07:00
50e2187e6c Bump version to 6.1.0 2024-12-24 06:58:53 +07:00
fc1aac66c2 Update translations 2024-12-24 06:46:58 +07:00
907e595b1e Move BLANK_PRESET_DATA to Table class 2024-12-24 06:43:08 +07:00
c1786d3fba Only show FL/PL percentage when it's > 1% 2024-12-24 06:31:40 +07:00
57fb22b905 6.1.0-beta-2 2024-12-23 22:34:03 +07:00
8b5da5b928 Fix triggering Number Stepper's input event twice 2024-12-23 22:33:38 +07:00
fe9d9895e9 Render buttons in the correct order 2024-12-23 21:54:27 +07:00
0fd926eff4 Fix note 2024-12-23 21:49:03 +07:00
9864954c81 Fix showing incorrect settings when switching customization 2024-12-23 21:35:21 +07:00
6d1e06dbfe Render controller customization summary 2024-12-23 21:14:39 +07:00
68d9e7368c Re-arrange buttons 2024-12-23 09:31:18 +07:00
c0d61a46c6 Update screenshot's prompt glygh 2024-12-23 09:25:04 +07:00
b143083bdd Stop replacing toUppercCase() in build.ts 2024-12-23 06:36:27 +07:00
fc5219705c Add BxIconRaw tyoe 2024-12-23 06:26:16 +07:00
03b7c7358e Optimize CE() 2024-12-23 05:55:11 +07:00
560a4c309c Use PartialRecord type 2024-12-23 05:38:01 +07:00
7b60ba3a3e Controller customization feature 2024-12-22 17:17:03 +07:00
8ef5a95c88 Bump version to 6.0.7 2024-12-18 06:44:35 +07:00
94c742cbd6 Fix not adding custom controller IDs 2024-12-18 06:32:51 +07:00
070943e3de Fix "patchBabylonRendererClass" patch 2024-12-18 06:16:44 +07:00
91deba793c Fix "patchShowSensorControls" patch 2024-12-18 06:08:09 +07:00
06a9ca9db8 Update 01-bug-report.yml 2024-12-13 07:11:53 +07:00
b0511d0f7a Update 01-bug-report.yml 2024-12-13 07:09:23 +07:00
aa35f21763 Update 01-bug-report.yml 2024-12-13 07:08:14 +07:00
458928d615 Bump version to 6.0.6 2024-12-13 06:32:52 +07:00
20bf2b1ab6 Turn on "EnableTakControlResizing" flag 2024-12-13 06:32:32 +07:00
901f55c683 Show different colors for wait time 2024-12-13 06:23:58 +07:00
15bb18644f Fix wait time stopped showing in game tile (#597) 2024-12-13 05:56:02 +07:00
873f6546a4 Fix input slider not working with gamepad (#596) 2024-12-13 05:41:25 +07:00
1db7d4f8d7 Set unadjustedMovement for MKB 2024-12-12 21:37:41 +07:00
e0b04f306f Bump version to 6.0.5 2024-12-12 06:55:00 +07:00
a3c948b070 Fix problem with Smart TV profile and Guide menu (#594) 2024-12-12 06:53:25 +07:00
4e736175b4 Fix Bx button in Guide menu not working 2024-12-12 06:46:41 +07:00
cb66340177 Fix not showing Bx button in unsupported page 2024-12-12 06:35:07 +07:00
9f5f7b9d2e Bump version to 6.0.4 2024-12-11 20:37:10 +07:00
d04742bc25 Update translations 2024-12-11 20:36:51 +07:00
ed871bbe83 Update dists 2024-12-11 18:59:31 +07:00
dca8ab9cf6 Fix stats texts 2024-12-11 18:59:24 +07:00
1bf2f41813 Fix not getting the correct candidate pair 2024-12-11 18:55:28 +07:00
0fb3b7b7f7 Pad stats 2024-12-11 18:08:28 +07:00
7709cceff0 Add stat's background opacity 2024-12-11 17:50:04 +07:00
f8b8012f5c Add "ignoreNewsSection" patch 2024-12-11 17:21:20 +07:00
1d8517a997 Update <select multiple> CSS 2024-12-11 07:51:41 +07:00
c893bb2a5d Block notifications 2024-12-11 07:25:48 +07:00
46469e3949 Fix Guide CSS in TV layout 2024-12-11 06:12:15 +07:00
d8a085d43f Update suggestion's styles 2024-12-10 21:53:57 +07:00
b84c464066 Add "Disable features" setting 2024-12-10 21:30:21 +07:00
f0549b388a Update dists 2024-12-10 20:55:12 +07:00
9c3b1bd908 Change background color of selected options in <select multiple> 2024-12-10 20:54:53 +07:00
d671be21ee Also disable Friends feature when blocking social features 2024-12-10 20:53:43 +07:00
11aefb34d1 Fix overriding features not working 2024-12-10 20:51:27 +07:00
597cc9782d Always show error log 2024-12-10 20:51:00 +07:00
61cfd3f8db Alert new server 2024-12-10 20:50:42 +07:00
a3d5d6a819 Add note for local co-op feature 2024-12-10 20:50:27 +07:00
ca64b592c5 Bump version to 6.0.3 2024-12-09 20:08:59 +07:00
d0a8b894b9 Show indicator for current preset 2024-12-09 19:59:30 +07:00
3230b99a05 Show lock icon in Default preset 2024-12-09 19:36:52 +07:00
f0e4d4b8d0 Fix exception in app 2024-12-09 18:18:40 +07:00
d0b84d4591 Update dists 2024-12-09 17:44:24 +07:00
d292bef5e7 Only show unbind note on custom presets 2024-12-09 17:42:51 +07:00
5381575048 Add "Xbox button > Press" shortcut 2024-12-09 17:42:11 +07:00
7206c9e8bc Migrate more events to EventBus 2024-12-09 07:01:13 +07:00
5fb0dec9f2 Call methods inside app in EventBus 2024-12-08 22:20:46 +07:00
4ffc034076 Rename EventBus events 2024-12-08 21:57:29 +07:00
b11d465804 Migrate to EventBus 2024-12-08 21:06:42 +07:00
e1ba2344b7 Declare window.navigator typing 2024-12-08 20:52:13 +07:00
8c446ceec3 Refactor patches 2024-12-08 20:26:05 +07:00
7438375356 Fix disableAdobeAudienceManager() 2024-12-08 20:24:15 +07:00
741bc9a4e5 Rename EventBus to BxEventBus 2024-12-08 20:09:12 +07:00
de7bf3edc7 Refactor 2024-12-08 20:05:29 +07:00
79ebb1a817 EventBus (#590)
* Replace BxEvent.TITLE_INFO_READY with Event Bus

* Migrate more events

* Migrate stream events to event bus

* Migrate preset events

* Migrate more

* Fix dispatching "input" event twice in Number Stepper
2024-12-08 17:55:44 +07:00
160044c958 Add new domain to ignore 2024-12-08 11:36:35 +07:00
78c70b5d90 Change "Max FPS" to "Limit FPS" 2024-12-08 11:20:35 +07:00
9044a07c0b Add note for default presets 2024-12-08 10:49:09 +07:00
173 changed files with 18234 additions and 19277 deletions

View File

@ -4,6 +4,13 @@ title: "[Bug] "
labels:
- bug
body:
- type: markdown
attributes:
value: |
> [!note]
> - Use `Discussions` if you want to ask for question.
> - Non-English reports will be deleted. No exceptions.
- type: checkboxes
id: checklist
attributes:
@ -15,17 +22,37 @@ body:
required: true
- label: I will describe the problem with as much detail as possible.
required: true
- type: checkboxes
id: questions
- type: dropdown
id: question_01
attributes:
label: Questions
label: xCloud officially supports your country/region
options:
- label: xCloud officially supports my country/region.
required: false
- label: "The bug doesn't happen when I disable Better xCloud script."
required: false
- label: "The bug didn't happen in previous Better xCloud version (name which one)."
required: false
- "No"
- "Yes"
validations:
required: true
- type: dropdown
id: question_02
attributes:
label: "The bug doesn't happen when you disable Better xCloud script"
options:
- "No"
- "Yes"
validations:
required: true
- type: dropdown
id: question_03
attributes:
label: "Previous Better xCloud versions didn't have this bug (name which one)"
options:
- "No"
- "Yes"
validations:
required: true
- type: dropdown
id: device_type
attributes:
@ -40,6 +67,7 @@ body:
multiple: false
validations:
required: true
- type: input
id: device_name
attributes:
@ -48,6 +76,7 @@ body:
placeholder: "e.g., Google Pixel 8"
validations:
required: true
- type: input
id: os
attributes:
@ -56,6 +85,7 @@ body:
placeholder: "e.g., Android 14"
validations:
required: true
- type: input
id: browser_version
attributes:
@ -64,6 +94,7 @@ body:
placeholder: "e.g., Chrome 124.0, Android app 0.15.0"
validations:
required: true
- type: input
id: extension_version
attributes:
@ -72,6 +103,7 @@ body:
placeholder: "e.g., 3.5.0"
validations:
required: true
- type: input
id: game_list
attributes:
@ -80,6 +112,7 @@ body:
placeholder: "e.g., Halo"
validations:
required: false
- type: textarea
id: reproduction
attributes:
@ -93,6 +126,7 @@ body:
3. Error
validations:
required: true
- type: textarea
id: media
attributes:

View File

@ -13,7 +13,7 @@ body:
- type: dropdown
id: device_type
attributes:
label: Device
label: Device type
description: "Which device type is this feature for?"
options:
- All devices
@ -23,10 +23,20 @@ body:
multiple: false
validations:
required: true
- type: input
id: device_name
attributes:
label: "Device"
description: "Name of the device"
placeholder: "e.g., Google Pixel 8"
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: "Suggestion"
description: "What do you want to suggest?"
description: "What do you want to suggest? Include (mockup) screenshot if possible."
validations:
required: true

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
src/modules/patcher/patches/*.js
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
# Logs

View File

@ -1,5 +1,12 @@
{
"files.readonlyInclude": {
"dist/**/*": true
"dist/**/*": true,
"src/modules/patcher/patches/controller-customization.js": true,
"src/modules/patcher/patches/expose-stream-session.js": true,
"src/modules/patcher/patches/game-card-icons.js": true,
"src/modules/patcher/patches/local-co-op-enable.js": true,
"src/modules/patcher/patches/poll-gamepad.js": true,
"src/modules/patcher/patches/remote-play-keep-alive.js": true,
"src/modules/patcher/patches/vibration-adjust.js": true
}
}

View File

@ -1,10 +1,17 @@
# Better xCloud
Improve Xbox Cloud Gaming (xCloud) experience on [xbox.com/play](https://www.xbox.com/play). It also allows you to use Remote Play on the xCloud website.
<div align="center">
<img src="https://raw.githubusercontent.com/redphx/better-xcloud/refs/heads/typescript/resources/logos/better-xcloud.png" width="256"/>
<h1>Better xCloud</h1>
<!-- Latest Version Badge -->
<a href="https://github.com/redphx/better-xcloud/releases"><img src="https://img.shields.io/github/v/release/redphx/better-xcloud?label=latest" alt="Latest version" /></a>
<!-- Total Downloads Badge -->
<a href="https://github.com/redphx/better-xcloud/releases"><img src="https://img.shields.io/github/downloads/redphx/better-xcloud/total?color=%23e15f2c" alt="Total downloads" /></a>
<!-- Total Stars Badge -->
<a href="https://github.com/redphx/better-xcloud/stargazers"><img src="https://img.shields.io/github/stars/redphx/better-xcloud?color=%23cca400" alt="Total stars" /></a>
</div>
> [!TIP]
> The Android app is in development at [redphx/better-xcloud-android](https://github.com/redphx/better-xcloud-android)
### Improve Xbox Cloud Gaming (xCloud) experience on [xbox.com/play](https://www.xbox.com/play). It also allows you to use Remote Play on the xCloud website.
> [!IMPORTANT]
> [!IMPORTANT]
> I only accept pull requests for:
> - Custom touch controls
> - Bug fixes
@ -13,16 +20,12 @@ Improve Xbox Cloud Gaming (xCloud) experience on [xbox.com/play](https://www.xbo
- Windows
- macOS
- Linux, SteamOS (including Steam Deck)
- Android, Android TV (including Meta Quest VR Headsets)
- Android, Android TV (including Meta Quest VR Headsets): [redphx/better-xcloud-android](https://github.com/redphx/better-xcloud-android)
- iOS, iPadOS
This script makes me spend more time with xCloud, and I hope the same thing happens to you.
If you like this project please give it a 🌟. Thank you 🙏.
[![Latest version](https://img.shields.io/github/v/release/redphx/better-xcloud?label=latest)](https://github.com/redphx/better-xcloud/releases)
[![Total downloads](https://img.shields.io/github/downloads/redphx/better-xcloud/total?color=%23e15f2c)](https://github.com/redphx/better-xcloud/releases)
[![Total stars](https://img.shields.io/github/stars/redphx/better-xcloud?color=%23cca400)](https://github.com/redphx/better-xcloud/stargazers)
## How to install
Visit the [home page](https://better-xcloud.github.io) to know how to install Better xCloud on your device.

View File

@ -5,8 +5,9 @@ build_all () {
printf "\033c"
# Build all variants
bun build.ts --version $1 --variant full
bun build.ts --version $1 --variant lite
bun build.ts --version $1 --variant full --pretty
bun build.ts --version $1 --variant full --meta
# bun build.ts --version $1 --variant lite
# Wait for key
read -p ">> Press Enter to build again..."

117
build.ts
View File

@ -1,5 +1,5 @@
#!/usr/bin/env bun
import { readFile } from "node:fs/promises";
import { readFile, readdir } from "node:fs/promises";
import { parseArgs } from "node:util";
import { sys } from "typescript";
// @ts-ignore
@ -56,7 +56,23 @@ function minifyCodeImports(str: string): string {
return str;
}
const postProcess = (str: string): string => {
function minifyIfElse(str: string): string {
// Collapse if/else blocks without curly braces
return str.replaceAll(/((if \(.*?\)|else)\n\s+)/g, '$2 ');
}
function removeComments(str: string): string {
// Remove enum's inlining comments
str = str.replaceAll(/ \/\* [A-Z0-9_:]+ \*\//g, '');
str = str.replaceAll('/* @__PURE__ */ ', '');
// Remove comments from import
str = str.replaceAll(/\/\/ src.*\n/g, '');
return str;
}
function postProcess(str: string, pretty: boolean): string {
// Unescape unicode charaters
str = unescape((str.replace(/\\u/g, '%u')));
// Replace \x00 to normal character
@ -65,12 +81,7 @@ const postProcess = (str: string): string => {
// Replace "globalThis." with "var";
str = str.replaceAll('globalThis.', 'var ');
// Remove enum's inlining comments
str = str.replaceAll(/ \/\* [A-Z0-9_:]+ \*\//g, '');
str = str.replaceAll('/* @__PURE__ */ ', '');
// Remove comments from import
str = str.replaceAll(/\/\/ src.*\n/g, '');
str = removeComments(str);
// Add ADDITIONAL CODE block
str = str.replace('var DEFAULT_FLAGS', '\n/* ADDITIONAL CODE */\n\nvar DEFAULT_FLAGS');
@ -105,21 +116,28 @@ const postProcess = (str: string): string => {
str = str.replaceAll(/\\n\/\/.*?(?=\\n)/g, '');
// Replace ${"time".toUpperCase()} with "TIME"
str = str.replaceAll(/\$\{"([^"]+)"\.toUpperCase\(\)\}/g, (match, p1) => {
return p1.toUpperCase();
});
// str = str.replaceAll(/\$\{"([^"]+)"\.toUpperCase\(\)\}/g, (match, p1) => {
// return p1.toUpperCase();
// });
// Replace " (e) =>" to " e =>"
// str = str.replaceAll(/ \(([^\s,.$()]+)\) =>/g, ' $1 =>');
// Set indent to 1 space
if (MINIFY_SYNTAX) {
// Collapse if/else blocks without curly braces
str = str.replaceAll(/((if \(.*?\)|else)\n\s+)/g, '$2 ');
str = minifyIfElse(str);
str = str.replaceAll(/\n(\s+)/g, (match, p1) => {
const len = p1.length / 2;
return '\n' + ' '.repeat(len);
str = str.replaceAll(/\n(\s+|\})/g, (match, p1) => {
if (pretty) {
if (p1 === '}') {
return '\n}';
} else {
const len = p1.length / 2;
return '\n' + ' '.repeat(len);
}
} else {
return (p1 === '}') ? '}' : '';
}
});
}
@ -134,7 +152,49 @@ const postProcess = (str: string): string => {
return str;
}
const build = async (target: BuildTarget, version: string, variant: BuildVariant, config: any={}) => {
async function buildPatches() {
const inputDir = './src/modules/patcher/patches/src';
const outputDir = './src/modules/patcher/patches';
const files = await readdir(inputDir);
const tsFiles = files.filter(file => file.endsWith('.ts'));
tsFiles.forEach(async file => {
// You can perform any operation with each TypeScript file
console.log(`Building patch: ${file}`);
const filePath = `${inputDir}/${file}`;
await Bun.build({
entrypoints: [filePath],
outdir: outputDir,
target: 'browser',
format: 'esm',
minify: {
syntax: true,
whitespace: true,
},
});
const outputFile = `${outputDir}/${file.replace('.ts', '.js')}`;
let code = await readFile(outputFile, 'utf-8');
// Replace "$this$" to "this"
code = code.replaceAll('$this$', 'this');
// Minify code
code = removeComments(code);
code = minifyIfElse(code);
// Save
await Bun.write(outputFile, code);
console.log(`Patch built successfully: ${file}`)
});
}
async function build(target: BuildTarget, params: { version: string, variant: BuildVariant, pretty: boolean, meta: boolean }, config: any={}) {
const { version, variant, pretty, meta } = params;
console.log('-- Target:', target);
const startTime = performance.now();
@ -148,11 +208,16 @@ const build = async (target: BuildTarget, version: string, variant: BuildVariant
}
let outputMetaName = outputScriptName;
if (pretty) {
outputScriptName += '.pretty';
}
outputScriptName += '.user.js';
outputMetaName += '.meta.js';
const outDir = './dist';
await buildPatches();
let output = await Bun.build({
entrypoints: ['src/index.ts'],
outdir: outDir,
@ -174,7 +239,7 @@ const build = async (target: BuildTarget, version: string, variant: BuildVariant
const {path} = output.outputs[0];
// Get generated file
let result = postProcess(await readFile(path, 'utf-8'));
let result = postProcess(await readFile(path, 'utf-8'), pretty);
// Replace [[VERSION]] with real value
let scriptHeader: string;
@ -189,7 +254,7 @@ const build = async (target: BuildTarget, version: string, variant: BuildVariant
await Bun.write(path, scriptHeader + result);
// Create meta file (don't build if it's beta version)
if (!version.includes('beta') && variant === 'full') {
if (meta && !version.includes('beta') && variant === 'full') {
await Bun.write(outDir + '/' + outputMetaName, txtMetaHeader.replace('[[VERSION]]', version));
}
@ -222,6 +287,16 @@ const { values, positionals } = parseArgs({
type: 'string',
default: 'full',
},
pretty: {
type: 'boolean',
default: false,
},
meta: {
type: 'boolean',
default: false,
},
},
strict: true,
allowPositionals: true,
@ -229,6 +304,8 @@ const { values, positionals } = parseArgs({
values: {
version: string,
variant: BuildVariant,
pretty: boolean,
meta: boolean,
},
positionals: string[],
};
@ -247,7 +324,7 @@ async function main() {
const config = {};
console.log(`Building: VERSION=${values['version']}, VARIANT=${values['variant']}`);
for (const target of buildTargets) {
await build(target, values['version']!!, values['variant'], config);
await build(target, values, config);
}
console.log('')

316
bun.lock Normal file
View File

@ -0,0 +1,316 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"devDependencies": {
"@types/bun": "^1.2.5",
"@types/node": "^22.13.10",
"@types/stylus": "^0.48.43",
"@webgpu/types": "^0.1.57",
"eslint": "^9.22.0",
"eslint-plugin-compat": "^6.0.2",
"stylus": "^0.64.0",
},
"peerDependencies": {
"typescript": "^5.7.2",
},
},
},
"packages": {
"@adobe/css-tools": ["@adobe/css-tools@4.3.3", "", {}, "sha512-rE0Pygv0sEZ4vBWHlAgJLGDU7Pm8xoO6p3wsEceb7GYAjScrOHpEo8KK/eVkAcnSM+slAEtXjA2JpdjLp4fJQQ=="],
"@eslint-community/eslint-utils": ["@eslint-community/eslint-utils@4.4.0", "", { "dependencies": { "eslint-visitor-keys": "^3.3.0" }, "peerDependencies": { "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" } }, "sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA=="],
"@eslint-community/regexpp": ["@eslint-community/regexpp@4.12.1", "", {}, "sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ=="],
"@eslint/config-array": ["@eslint/config-array@0.19.2", "", { "dependencies": { "@eslint/object-schema": "^2.1.6", "debug": "^4.3.1", "minimatch": "^3.1.2" } }, "sha512-GNKqxfHG2ySmJOBSHg7LxeUx4xpuCoFjacmlCoYWEbaPXLwvfIjixRI12xCQZeULksQb23uiA8F40w5TojpV7w=="],
"@eslint/config-helpers": ["@eslint/config-helpers@0.2.0", "", {}, "sha512-yJLLmLexii32mGrhW29qvU3QBVTu0GUmEf/J4XsBtVhp4JkIUFN/BjWqTF63yRvGApIDpZm5fa97LtYtINmfeQ=="],
"@eslint/core": ["@eslint/core@0.12.0", "", { "dependencies": { "@types/json-schema": "^7.0.15" } }, "sha512-cmrR6pytBuSMTaBweKoGMwu3EiHiEC+DoyupPmlZ0HxBJBtIxwe+j/E4XPIKNx+Q74c8lXKPwYawBf5glsTkHg=="],
"@eslint/eslintrc": ["@eslint/eslintrc@3.3.1", "", { "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-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ=="],
"@eslint/js": ["@eslint/js@9.23.0", "", {}, "sha512-35MJ8vCPU0ZMxo7zfev2pypqTwWTofFZO6m4KAtdoFhRpLJUpHTZZ+KB3C7Hb1d7bULYwO4lJXGCi5Se+8OMbw=="],
"@eslint/object-schema": ["@eslint/object-schema@2.1.6", "", {}, "sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA=="],
"@eslint/plugin-kit": ["@eslint/plugin-kit@0.2.7", "", { "dependencies": { "@eslint/core": "^0.12.0", "levn": "^0.4.1" } }, "sha512-JubJ5B2pJ4k4yGxaNLdbjrnk9d/iDz6/q8wOilpIowd6PJPgaxCuHBnBszq7Ce2TyMrywm5r4PnKm6V3iiZF+g=="],
"@humanfs/core": ["@humanfs/core@0.19.1", "", {}, "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA=="],
"@humanfs/node": ["@humanfs/node@0.16.6", "", { "dependencies": { "@humanfs/core": "^0.19.1", "@humanwhocodes/retry": "^0.3.0" } }, "sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw=="],
"@humanwhocodes/module-importer": ["@humanwhocodes/module-importer@1.0.1", "", {}, "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA=="],
"@humanwhocodes/retry": ["@humanwhocodes/retry@0.4.2", "", {}, "sha512-xeO57FpIu4p1Ri3Jq/EXq4ClRm86dVF2z/+kvFnyqVYRavTZmaFaUBbWCOuuTh0o/g7DSsk6kc2vrS4Vl5oPOQ=="],
"@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="],
"@mdn/browser-compat-data": ["@mdn/browser-compat-data@5.5.42", "", {}, "sha512-qhHVgb2dxaFNT00Z1upHaDCstUEjjrgtIkrk4tr+YnDSGbTIKncbdydIpSed+RCXz0f6nb4UDD4eKEWokNom6g=="],
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
"@types/bun": ["@types/bun@1.2.6", "", { "dependencies": { "bun-types": "1.2.6" } }, "sha512-fY9CAmTdJH1Llx7rugB0FpgWK2RKuHCs3g2cFDYXUutIy1QGiPQxKkGY8owhfZ4MXWNfxwIbQLChgH5gDsY7vw=="],
"@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.13.13", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-ClsL5nMwKaBRwPcCvH8E7+nU4GxHVx1axNvMZTFHMEfNI7oahimt26P5zjVCRrjiIWj6YFXfE1v3dEp94wLcGQ=="],
"@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.59", "", {}, "sha512-jZJ6ipNli+rn++/GAPqsZXfsgjx951wlCW7vNAg+oGdp0ZYidTOkbVTVeK2frzowuD5ch7MRz7leOEX1PMv43A=="],
"acorn": ["acorn@8.14.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA=="],
"acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
"ajv": ["ajv@6.12.6", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g=="],
"ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="],
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"ast-metadata-inferer": ["ast-metadata-inferer@0.8.1", "", { "dependencies": { "@mdn/browser-compat-data": "^5.6.19" } }, "sha512-ht3Dm6Zr7SXv6t1Ra6gFo0+kLDglHGrEbYihTkcycrbHw7WCcuhBzPlJYHEsIpycaUwzsJHje+vUcxXUX4ztTA=="],
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"brace-expansion": ["brace-expansion@1.1.11", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA=="],
"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.6", "", { "dependencies": { "@types/node": "*", "@types/ws": "~8.5.10" } }, "sha512-FbCKyr5KDiPULUzN/nm5oqQs9nXCHD8dVc64BArxJadCvbNzAI6lUWGh9fSJZWeDIRD38ikceBU8Kj/Uh+53oQ=="],
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
"caniuse-lite": ["caniuse-lite@1.0.30001690", "", {}, "sha512-5ExiE3qQN6oF8Clf8ifIDcMRCRE/dMGcETG/XGMD8/XiXm6HXQgQTh1yZYLXXpSOsEUlJm1Xr7kGULZTuGtP/w=="],
"chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
"color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="],
"color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"debug": ["debug@4.3.5", "", { "dependencies": { "ms": "2.1.2" } }, "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg=="],
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
"eastasianwidth": ["eastasianwidth@0.2.0", "", {}, "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA=="],
"electron-to-chromium": ["electron-to-chromium@1.5.75", "", {}, "sha512-Lf3++DumRE/QmweGjU+ZcKqQ+3bKkU/qjaKYhIJKEOhgIO9Xs6IiAQFkfFoj+RhgDk4LUeNsLo6plExHqSyu6Q=="],
"emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"eslint": ["eslint@9.23.0", "", { "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.12.1", "@eslint/config-array": "^0.19.2", "@eslint/config-helpers": "^0.2.0", "@eslint/core": "^0.12.0", "@eslint/eslintrc": "^3.3.1", "@eslint/js": "9.23.0", "@eslint/plugin-kit": "^0.2.7", "@humanfs/node": "^0.16.6", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@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.3.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-jV7AbNoFPAY1EkFYpLq5bslU9NLNO8xnEeQXwErNibVryjk67wHVmddTBilc5srIttJDBrB0eMHKZBFbSIABCw=="],
"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=="],
"eslint-scope": ["eslint-scope@8.3.0", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^5.2.0" } }, "sha512-pUNxi75F8MJ/GdeKtVLSbYg4ZI34J6C0C7sbL4YOp2exGwen7ZsuBqKzUhXd0qMQ362yET3z+uPwKeg/0C2XCQ=="],
"eslint-visitor-keys": ["eslint-visitor-keys@4.2.0", "", {}, "sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw=="],
"espree": ["espree@10.3.0", "", { "dependencies": { "acorn": "^8.14.0", "acorn-jsx": "^5.3.2", "eslint-visitor-keys": "^4.2.0" } }, "sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg=="],
"esquery": ["esquery@1.6.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg=="],
"esrecurse": ["esrecurse@4.3.0", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
"estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
"esutils": ["esutils@2.0.3", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-json-stable-stringify": ["fast-json-stable-stringify@2.1.0", "", {}, "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw=="],
"fast-levenshtein": ["fast-levenshtein@2.0.6", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
"file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "^4.0.0" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
"find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "^6.0.0", "path-exists": "^4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
"flat-cache": ["flat-cache@4.0.1", "", { "dependencies": { "flatted": "^3.2.9", "keyv": "^4.5.4" } }, "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw=="],
"flatted": ["flatted@3.3.1", "", {}, "sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw=="],
"foreground-child": ["foreground-child@3.3.0", "", { "dependencies": { "cross-spawn": "^7.0.0", "signal-exit": "^4.0.1" } }, "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg=="],
"glob": ["glob@10.4.5", "", { "dependencies": { "foreground-child": "^3.1.0", "jackspeak": "^3.1.2", "minimatch": "^9.0.4", "minipass": "^7.1.2", "package-json-from-dist": "^1.0.0", "path-scurry": "^1.11.1" }, "bin": { "glob": "dist/esm/bin.mjs" } }, "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg=="],
"glob-parent": ["glob-parent@6.0.2", "", { "dependencies": { "is-glob": "^4.0.3" } }, "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A=="],
"globals": ["globals@15.8.0", "", {}, "sha512-VZAJ4cewHTExBWDHR6yptdIBlx9YSSZuwojj9Nt5mBRXQzrKakDsVKQ1J63sklLvzAJm0X5+RpO4i3Y2hcOnFw=="],
"has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="],
"ignore": ["ignore@5.3.1", "", {}, "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw=="],
"import-fresh": ["import-fresh@3.3.0", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw=="],
"imurmurhash": ["imurmurhash@0.1.4", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
"is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="],
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jackspeak": ["jackspeak@3.4.3", "", { "dependencies": { "@isaacs/cliui": "^8.0.2" }, "optionalDependencies": { "@pkgjs/parseargs": "^0.11.0" } }, "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw=="],
"js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
"json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"json-stable-stringify-without-jsonify": ["json-stable-stringify-without-jsonify@1.0.1", "", {}, "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw=="],
"keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
"levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "^1.2.1", "type-check": "~0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
"locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="],
"lodash.memoize": ["lodash.memoize@4.1.2", "", {}, "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag=="],
"lodash.merge": ["lodash.merge@4.6.2", "", {}, "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ=="],
"lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
"minimatch": ["minimatch@3.1.2", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw=="],
"minipass": ["minipass@7.1.2", "", {}, "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw=="],
"ms": ["ms@2.1.2", "", {}, "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="],
"natural-compare": ["natural-compare@1.4.0", "", {}, "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw=="],
"node-releases": ["node-releases@2.0.19", "", {}, "sha512-xxOWJsBKtzAq7DY0J+DTzuz58K8e7sJbdgwkbMWQe8UYB6ekmsQ45q0M/tJDsGaZmbC+l7n57UV8Hl5tHxO9uw=="],
"optionator": ["optionator@0.9.4", "", { "dependencies": { "deep-is": "^0.1.3", "fast-levenshtein": "^2.0.6", "levn": "^0.4.1", "prelude-ls": "^1.2.1", "type-check": "^0.4.0", "word-wrap": "^1.2.5" } }, "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g=="],
"p-limit": ["p-limit@3.1.0", "", { "dependencies": { "yocto-queue": "^0.1.0" } }, "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ=="],
"p-locate": ["p-locate@5.0.0", "", { "dependencies": { "p-limit": "^3.0.2" } }, "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw=="],
"package-json-from-dist": ["package-json-from-dist@1.0.1", "", {}, "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw=="],
"parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
"path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-scurry": ["path-scurry@1.11.1", "", { "dependencies": { "lru-cache": "^10.2.0", "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" } }, "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"prelude-ls": ["prelude-ls@1.2.1", "", {}, "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g=="],
"punycode": ["punycode@2.3.1", "", {}, "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg=="],
"resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
"sax": ["sax@1.4.1", "", {}, "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg=="],
"semver": ["semver@7.6.3", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
"source-map": ["source-map@0.7.4", "", {}, "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA=="],
"string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "^0.2.0", "emoji-regex": "^9.2.2", "strip-ansi": "^7.0.1" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="],
"string-width-cjs": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="],
"strip-ansi-cjs": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-json-comments": ["strip-json-comments@3.1.1", "", {}, "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="],
"stylus": ["stylus@0.64.0", "", { "dependencies": { "@adobe/css-tools": "~4.3.3", "debug": "^4.3.2", "glob": "^10.4.5", "sax": "~1.4.1", "source-map": "^0.7.3" }, "bin": { "stylus": "bin/stylus" } }, "sha512-ZIdT8eUv8tegmqy1tTIdJv9We2DumkNZFdCF5mz/Kpq3OcTaxSuCAYZge6HKK2CmNC02G1eJig2RV7XTw5hQrA=="],
"supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="],
"type-check": ["type-check@0.4.0", "", { "dependencies": { "prelude-ls": "^1.2.1" } }, "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew=="],
"typescript": ["typescript@5.7.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg=="],
"undici-types": ["undici-types@6.20.0", "", {}, "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg=="],
"update-browserslist-db": ["update-browserslist-db@1.1.1", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.0" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-R8UzCaa9Az+38REPiJ1tXlImTJXlVfgHZsglwBD/k6nj76ctsH1E3q4doGrukiLQd3sGQYu56r5+lo5r94l29A=="],
"uri-js": ["uri-js@4.4.1", "", { "dependencies": { "punycode": "^2.1.0" } }, "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"wrap-ansi": ["wrap-ansi@8.1.0", "", { "dependencies": { "ansi-styles": "^6.1.0", "string-width": "^5.0.1", "strip-ansi": "^7.0.1" } }, "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ=="],
"wrap-ansi-cjs": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
"yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="],
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
"@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=="],
"@types/ws/@types/node": ["@types/node@20.14.2", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-xyu6WAMVwv6AKFLB+e/7ySZVr/0zLCzOa7rSpq6jNwpqOrUbcACDWC+53d4n2QHOnDou0fbIsg8wZu/sxrnI4Q=="],
"ast-metadata-inferer/@mdn/browser-compat-data": ["@mdn/browser-compat-data@5.6.26", "", {}, "sha512-7NdgdOR7lkzrN70zGSULmrcvKyi/aJjpTJRCbuy8IZuHiLkPTvsr10jW0MJgWzK2l2wTmhdQvegTw6yNU5AVNQ=="],
"foreground-child/cross-spawn": ["cross-spawn@7.0.3", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w=="],
"glob/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
"string-width-cjs/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"string-width-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"strip-ansi-cjs/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"wrap-ansi/ansi-styles": ["ansi-styles@6.2.1", "", {}, "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug=="],
"wrap-ansi-cjs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
"wrap-ansi-cjs/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
"@types/stylus/@types/node/undici-types": ["undici-types@6.19.8", "", {}, "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="],
"@types/ws/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="],
"glob/minimatch/brace-expansion": ["brace-expansion@2.0.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="],
"string-width-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
"wrap-ansi-cjs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="],
"wrap-ansi-cjs/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
}
}

BIN
bun.lockb

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

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

10353
dist/better-xcloud.pretty.user.js vendored Normal file

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,12 @@
"build": "build.ts"
},
"devDependencies": {
"@types/bun": "^1.1.14",
"@types/node": "^22.10.1",
"@types/bun": "^1.2.6",
"@types/node": "^22.13.13",
"@types/stylus": "^0.48.43",
"eslint": "^9.16.0",
"eslint-plugin-compat": "^6.0.1",
"@webgpu/types": "^0.1.59",
"eslint": "^9.23.0",
"eslint-plugin-compat": "^6.0.2",
"stylus": "^0.64.0"
},
"peerDependencies": {

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

View File

@ -24,8 +24,12 @@ How to:
const enabled = true;
enabled && (window.BX_FLAGS = {
// Toggle WebGPU Renderer
// https://github.com/redphx/better-xcloud/discussions/657
EnableWebGPURenderer: false,
/*
Add titleId of the game(s) you want to add here.
Add titleId of the game(s) you want to test native M&KB support here.
Keep in mind: this method only works with some games.
Example:

View File

@ -37,6 +37,7 @@
&:disabled {
cursor: default;
background-color: unquote('rgb(var(--button-disabled-rgb))');
opacity: 0.5;
}
&.bx-ghost {
@ -106,7 +107,6 @@
&.bx-frosted {
--button-alpha: 0.2;
background-color: unquote('rgba(var(--button-rgb), var(--button-alpha))');
backdrop-filter: blur(4px) brightness(1.5);
&:not([disabled]):not(:active) {
&:hover, &.bx-focusable:focus {
@ -145,15 +145,16 @@
overflow: hidden;
white-space: nowrap;
// Text with icon
&:not(:only-child) {
margin-left: 10px;
margin-inline-start: 8px;
}
}
&.bx-button-multi-lines {
height: auto;
text-align: left;
padding: 10px 0;
padding: 10px;
span {
line-height: unset;

View File

@ -0,0 +1,89 @@
.bx-controller-customizations-container {
.bx-btn-detect {
display: block;
margin-bottom: 20px;
&.bx-monospaced {
background: none;
font-weight: bold;
font-size: 12px;
}
}
.bx-buttons-grid {
display: grid;
grid-template-columns: auto auto;
column-gap: 20px;
row-gap: 10px;
margin-bottom: 20px;
}
}
.bx-controller-key-row {
display: flex;
align-items: stretch;
> label {
margin-bottom: 0;
font-family: var(--bx-promptfont-font);
font-size: 32px;
text-align: center;
min-width: 50px;
flex-shrink: 0;
display: flex;
align-self: center;
&::after {
content: '';
margin: 0 12px;
font-size: 16px;
align-self: center;
}
}
.bx-select {
width: 100% !important;
> div {
min-width: 50px;
}
label {
font-family: var(--bx-promptfont-font), var(--bx-normal-font);
font-size: 32px;
text-align: center;
margin-bottom: 6px;
height: 40px;
line-height: 40px;
}
}
&:hover {
> label {
color: #ffe64b;
&::after {
color: #fff;
}
}
}
}
.bx-controller-customization-summary {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 10px;
span {
font-family: var(--bx-promptfont);
font-size: 24px;
border-radius: 6px;
background: #131313;
color: #fff;
display: inline-block;
padding: 2px;
text-align: center;
}
}

View File

@ -7,11 +7,11 @@
margin-bottom: 0 !important;
}
html[data-xds-platform=tv] & {
body[data-bx-media-type=tv] & {
flex-direction: column;
}
html:not([data-xds-platform=tv]) & {
body:not([data-bx-media-type=tv]) & {
flex-direction: row;
> button:first-of-type {
@ -34,7 +34,7 @@
flex-direction: row;
gap: 12px;
html[data-xds-platform=tv] & {
body[data-bx-media-type=tv] & {
flex-direction: column;
button {
@ -42,7 +42,7 @@
}
}
html:not([data-xds-platform=tv]) & {
body:not([data-bx-media-type=tv]) & {
button {
span {
display: none;

View File

@ -16,7 +16,7 @@
margin-right: -50%;
transform: translate(-50%, -50%);
min-width: 420px;
padding: 20px;
padding: 16px;
border-radius: 8px;
z-index: var(--bx-key-binding-dialog-z-index);
background: #1a1b1e;

View File

@ -1,3 +1,12 @@
.bx-product-details-icons {
padding: 8px;
border-radius: 4px;
svg {
margin-right: 8px;
}
}
.bx-product-details-buttons {
display: flex;
gap: 10px;

View File

@ -17,6 +17,21 @@
border-radius: 4px;
padding: 0 5px;
}
.bx-focusable {
&::after {
border-radius: 4px;
}
&:focus::after {
offset = 0;
top: offset;
left: offset;
right: offset;
bottom: offset;
}
}
}
.bx-navigation-dialog-overlay {
@ -42,10 +57,10 @@
color: white;
background: #1a1b1e;
border-radius: 10px;
width: 450px;
min-width: @css{ min(calc(100vw - 20px), 500px) };
max-width: calc(100vw - 20px);
margin: 0 0 0 auto;
padding: 20px;
padding: 16px;
max-height: 95vh;
flex-direction: column;
@ -63,7 +78,7 @@
padding: 0;
margin: 0;
flex: 1;
font-size: 1.2rem;
font-size: 1.5rem;
font-weight: bold;
}
@ -74,11 +89,9 @@
.bx-dialog-content {
flex: 1;
padding: 6px;
overflow: auto;
overflow-x: hidden;
> div {
}
}
.bx-dialog-preset-tools {
@ -86,10 +99,18 @@
margin-bottom: 12px;
gap: 6px;
select {
flex: 1;
button {
align-self: center;
min-height: 50px;
}
}
.bx-default-preset-note {
font-size: 12px;
font-style: italic;
text-align: center;
margin-bottom: 10px;
}
}
.bx-centered-dialog,
@ -157,29 +178,6 @@
letter-spacing: 6px;
}
}
.bx-shortcut-actions {
flex: 1;
position: relative;
select {
width: 100%;
height: 100%;
min-height: 38px;
display: block;
&:first-of-type {
position: absolute;
top: 0;
left: 0;
}
&:last-of-type {
opacity: 0;
z-index: calc(var(--bx-settings-z-index) + 1);
}
}
}
}
select:disabled {
@ -214,5 +212,6 @@
.bx-settings-row {
background: none;
padding: 10px;
}
}

View File

@ -10,6 +10,7 @@
display: inline-block;
min-width: 40px;
font-family: var(--bx-monospaced-font);
white-space: pre;
font-size: 13px;
margin: 0 4px;
}
@ -44,7 +45,7 @@
}
}
input[type="range"] {
input[type=range] {
display: block;
margin: 8px 0 2px auto;
min-width: 180px;
@ -62,3 +63,91 @@
}
}
}
.bx-dual-number-stepper {
> span {
display: block;
font-family: var(--bx-monospaced-font);
font-size: 13px;
white-space: pre;
margin: 0 4px;
text-align: center;
}
> div {
input[type=range] {
display: block;
width: 100%;
min-width: 180px;
background: transparent;
color: #959595 !important;
appearance: none;
padding: 8px 0;
range-track() {
background: linear-gradient(90deg, #fff var(--from), var(--bx-primary-button-color) var(--from) var(--to), #fff var(--to) 100%);
height: 8px;
border-radius: 2px;
}
range-track-hover() {
background: linear-gradient(90deg, #fff var(--from), #006635 var(--from) var(--to), #fff var(--to) 100%);
}
thumb() {
margin-top: -4px;
appearance: none;
width: 4px;
height: 16px;
background: #00b85f;
border: none;
border-radius: 2px;
}
thumb-hover() {
background: #fb3232;
}
&::-webkit-slider-runnable-track {
range-track()
}
&::-moz-range-track {
range-track()
}
&::-webkit-slider-thumb {
thumb();
}
&::-moz-range-thumb {
thumb();
}
&:hover, &&:active, &:focus {
&::-webkit-slider-runnable-track {
range-track-hover();
}
&::-moz-range-track {
range-track-hover();
}
&::-webkit-slider-thumb {
thumb-hover();
}
&::-moz-range-thumb {
thumb-hover();
}
}
}
}
&[data-disabled=true], &[disabled=true] {
input[type=range] {
display: none;
}
}
}

View File

@ -1,23 +1,3 @@
.bx-remote-play-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
background: #1a1b1e;
border-radius: 10px;
width: 420px;
max-width: calc(100vw - 20px);
margin: 0 0 0 auto;
padding: 20px;
> .bx-button {
display: table;
margin: 0 0 0 auto;
}
}
.bx-remote-play-settings {
margin-bottom: 12px;
padding-bottom: 12px;
@ -29,6 +9,7 @@
label {
flex: 1;
font-size: 14px;
p {
margin: 4px 0 0;
@ -63,23 +44,24 @@
.bx-remote-play-device-info {
flex: 1;
align-self: center;
padding: 4px 0;
}
.bx-remote-play-device-name {
font-size: 20px;
font-size: 14px;
font-weight: bold;
display: inline-block;
vertical-align: middle;
}
.bx-remote-play-console-type {
font-size: 12px;
font-size: 8px;
background: #004c87;
color: #fff;
display: inline-block;
border-radius: 14px;
padding: 2px 10px;
border-radius: 8px;
padding: 2px 6px;
margin-left: 8px;
vertical-align: middle;
}

View File

@ -25,7 +25,7 @@ button_color(name, normal, hover, active, disabled)
button_color('default', #2d3036, #515863, #222428, #8e8e8e);
button_color('primary', #008746, #04b358, #044e2a, #448262);
button_color('warning', #c16e04, #fa9005, #965603, #a2816c);
button_color('danger', #c10404, #e61d1d, #a26c6c, #df5656);
button_color('danger', #c10404, #e61d1d, #a26c6c, #bd8282);
--bx-fullscreen-text-z-index: 9999;
--bx-toast-z-index: 6000;
@ -47,10 +47,11 @@ button_color(name, normal, hover, active, disabled)
@font-face {
font-family: 'promptfont';
src: url('https://redphx.github.io/better-xcloud/fonts/promptfont.otf');
unicode-range: U+2196-E011, U+27F6, U+FF31;
}
/* Fix Stream menu buttons not hiding */
div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module__hiddenContainer]) {
#StreamHud div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module__hiddenContainer]) {
opacity: 0;
pointer-events: none !important;
position: absolute;
@ -59,9 +60,35 @@ div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module
}
/* Remove the "Cloud Gaming" text in header when the screen is too small */
@media screen and (min-width: 641px) and (max-width: 767px) {
header {
button[class^="ExperienceDropdown-module__toggleButton"],
button[class^="XboxButton-module__headerXboxButton"] {
margin-right: 10px !important;
}
a[href="/play"],
button[class^="ExperienceDropdown-module__toggleButton"] {
> div {
> div {
font-size: 12px;
}
> svg {
width: 20px;
height: 20px;
}
}
}
}
}
@media screen and (max-width: 640px) {
header a[href="/play"] {
display: none;
header {
a[href="/play"],
button[class^="ExperienceDropdown-module__toggleButton"] {
display: none;
}
}
}
@ -73,6 +100,10 @@ div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module
height: 100% !important;
}
.bx-auto-height {
height: auto !important;
}
.bx-no-scroll {
overflow: hidden !important;
}
@ -125,6 +156,10 @@ div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module
font-family: var(--bx-promptfont-font) !important;
}
.bx-monospaced {
font-family: var(--bx-monospaced-font) !important;
}
.bx-line-through {
text-decoration: line-through !important;
}
@ -140,8 +175,32 @@ div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module
font-family: var(--bx-normal-font) !important;
}
select[multiple] {
.bx-frosted {
backdrop-filter: blur(4px) brightness(1.5);
}
select[multiple], select[multiple]:focus {
overflow: auto;
border: none;
option {
padding: 4px 6px;
&:checked {
color = #1a7bc0;
background: color linear-gradient(0deg, color 0%, color 100%);
&::before {
content: '';
font-size: 12px;
display: inline-block;
margin-right: 6px;
height: 100%;
line-height: 100%;
vertical-align: middle;
}
}
}
}
/* Hide UI elements */
@ -149,32 +208,26 @@ select[multiple] {
display: none;
}
div[class*=NotFocusedDialog] {
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
width: 0px !important;
height: 0px !important;
}
#game-stream {
div[class^=NotFocusedDialog] {
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
width: 0px !important;
height: 0px !important;
}
#game-stream video:not([src]) {
visibility: hidden;
}
/* Hide Controller icon in Game tiles */
div[class*=SupportedInputsBadge] {
&:not(:has(:nth-child(2))), svg:first-of-type {
display: none;
video:not([src]) {
visibility: hidden;
}
}
.bx-game-tile-wait-time {
position: absolute;
top: 0;
left: 0;
z-index: 1;
background: #0000008c;
background: rgba(0, 0, 0, 0.5);
display: flex;
border-radius: 4px 0 4px 0;
align-items: center;
@ -194,6 +247,18 @@ div[class*=SupportedInputsBadge] {
font-weight: bold;
margin-left: 2px;
}
&[data-duration=short] {
background-color: rgba(0, 133, 133, 0.75);
}
&[data-duration=medium] {
background-color: rgba(213, 133, 0, 0.75);
}
&[data-duration=long] {
background-color: rgba(150, 0, 0, 0.75);
}
}
@ -238,3 +303,15 @@ div[class*=SupportedInputsBadge] {
opacity: 0;
}
}
.bx-horizontal-shaking {
animation: bx-horizontal-shaking .4s ease-in-out 2;
}
@keyframes bx-horizontal-shaking {
0% { transform: translateX(0) }
25% { transform: translateX(5px) }
50% { transform: translateX(-5px) }
75% { transform: translateX(5px) }
100% { transform: translateX(0) }
}

View File

@ -8,21 +8,6 @@
user-select: none;
-webkit-user-select: none;
.bx-focusable {
&::after {
border-radius: 4px;
}
&:focus::after {
offset = 0;
top: offset;
left: offset;
right: offset;
bottom: offset;
}
}
.bx-settings-reload-note {
font-size: 0.8rem;
display: block;
@ -113,10 +98,8 @@
tabsWidth = 48px;
flex-direction: column;
padding: 10px;
margin-left: tabsWidth;
width: 450px;
max-width: calc(100vw - tabsWidth);
background: #1a1b1e;
color: #fff;
font-weight: 400;
@ -127,13 +110,6 @@
overflow: overlay;
z-index: 1;
> div[data-tab-group=mkb] {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
}
.bx-top-buttons {
display: flex;
flex-direction: column;
@ -179,7 +155,6 @@
display: flex;
gap: 10px;
padding: 16px 10px;
margin: 0;
background: #2a2a2a;
border-bottom: 1px solid #343434;
@ -205,6 +180,12 @@
margin-bottom: 0 !important;
flex: 1;
svg {
width: 20px;
height: 20px;
margin-inline-end: 8px;
}
+ * {
margin: 0 0 0 auto;
}
@ -221,6 +202,10 @@
}
}
}
&.bx-settings-important-row {
background: #733b00;
}
}
.bx-settings-dialog-note {
@ -293,7 +278,8 @@
color: #828282;
}
.bx-settings-tab-contents {
.bx-settings-tab-content {
padding: 10px;
border-radius-size = 6px;
> div {
@ -316,6 +302,15 @@
border-radius: border-radius-size;
}
}
&:not([data-game-id="-1"]) {
.bx-settings-row[data-override=true], .bx-settings-row:has(*[data-override=true]) {
border-left: 4px solid orange !important;
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
padding-left: 6px !important;
}
}
}
.bx-suggest-toggler {
@ -324,18 +319,22 @@
border-radius: 4px;
overflow: hidden;
background: #003861;
height: 45px;
align-items: center;
label {
flex: 1;
padding: 10px;
align-content: center;
padding: 0 10px;
background: #004f87;
height: 100%;
}
span {
display: inline-block;
align-self: center;
padding: 10px;
width: 40px;
width: 45px;
text-align: center;
}
@ -538,3 +537,53 @@
flex: 1;
}
}
.bx-stream-settings-selection {
margin-bottom: 8px;
position: sticky;
z-index: 1000;
top: 0;
> div {
display: flex;
gap: 8px;
background: #222222;
padding: 10px;
border-bottom: 4px solid #353638;
box-shadow: 0 0 6px #000;
position: relative;
z-index: 1;
.bx-select {
flex: 1;
label {
font-weight: bold;
font-size: 1.1rem;
line-height: initial;
span {
line-height: initial;
}
}
.bx-select-indicators {
display: none;
}
}
}
p {
font-family: var(--bx-promptfont-font), var(--bx-normal-font);
margin: 0;
font-size: 13px;
background: #505050f2;
height: 25px;
line-height: 23px;
position: absolute;
bottom: -25px;
left: 0;
right: 0;
text-shadow: 0 1px #000;
}
}

View File

@ -144,7 +144,7 @@ div[class^=StreamMenu-module__container] .bx-badges {
border-radius: 0 0 4px 4px;
}
&[data-transparent=true] {
&[data-shadow=true] {
background: none;
filter: drop-shadow(1px 0 0 #000000f0) drop-shadow(-1px 0 0 #000000f0) drop-shadow(0 1px 0 #000000f0) drop-shadow(0 -1px 0 #000000f0);
}
@ -165,10 +165,10 @@ div[class^=StreamMenu-module__container] .bx-badges {
}
span {
min-width: 60px;
display: inline-block;
text-align: right;
vertical-align: middle;
white-space: pre;
&[data-grade=good] {
color: #6bffff;
@ -181,9 +181,5 @@ div[class^=StreamMenu-module__container] .bx-badges {
&[data-grade=bad] {
color: #ff5f5f;
}
&:first-of-type {
min-width: 22px;
}
}
}

View File

@ -1,4 +1,4 @@
div[class*=StreamMenu-module__menuContainer] > div[class*=Menu-module] {
#game-stream div[class^=StreamMenu-module__menuContainer] > div[class^=Menu-module] {
overflow: visible;
}

View File

@ -16,4 +16,5 @@
@import 'game-bar.styl';
@import 'stream-stats.styl';
@import 'mkb.styl';
@import 'controller.styl';
@import 'misc.styl';

View File

@ -5,8 +5,8 @@
left: 50%;
top: 24px;
transform: translate(-50%, 0);
background: #000000;
border-radius: 16px;
background: #212121;
border-radius: 10px;
color: white;
z-index: var(--bx-toast-z-index);
font-family: var(--bx-normal-font);
@ -16,9 +16,10 @@
opacity: 0;
overflow: clip;
transition: opacity 0.2s ease-in;
box-shadow: 0 0 6px #000;
&.bx-show {
opacity: 0.85;
opacity: 0.95;
}
&.bx-hide {
@ -39,8 +40,8 @@
font-size: 14px;
text-transform: uppercase;
display: inline-block;
background: #515863;
background: #fff;
padding: 12px 16px;
color: #fff;
color: #212121;
white-space: pre;
}

View File

@ -4,17 +4,11 @@ select.bx-select {
div.bx-select {
display: flex;
align-items: center;
align-items: stretch;
flex: 0 1 auto;
gap: 8px;
select {
// Render offscreen instead of "display: none" so we could get its size
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
visibility: hidden !important;
&:disabled {
& ~ button {
display: none;
@ -48,7 +42,6 @@ div.bx-select {
> div {
min-height: 24px;
box-sizing: content-box;
input {
display: inline-block;
@ -62,14 +55,17 @@ div.bx-select {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
min-height: 15px;
span {
display: block;
font-size: 10px;
font-weight: bold;
text-align: left;
line-height: initial;
line-height: 20px;
white-space: pre;
min-height: 15px;
align-content: center;
}
}
}
@ -112,10 +108,9 @@ div.bx-select {
button.bx-button {
border: none;
height: 24px;
width: 24px;
height: auto;
padding: 0;
line-height: 24px;
color: #fff;
border-radius: 4px;
font-weight: bold;
@ -127,6 +122,68 @@ div.bx-select {
line-height: unset;
}
}
&[data-controller-friendly=true] {
> div {
box-sizing: content-box;
}
select {
// Render offscreen instead of "display: none" so we could get its size
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
visibility: hidden !important;
}
}
&[data-controller-friendly=false] {
position: relative;
> div {
box-sizing: border-box;
label {
margin-right: 24px;
}
}
select {
&:disabled {
display: none;
}
&:not(:disabled) {
cursor: pointer;
position: absolute;
top: 0;
right: 0;
bottom: 0;
display: block;
opacity: 0;
z-index: calc(var(--bx-settings-z-index) + 1);
&:hover {
+ div {
background: #f0f0f0;
}
}
+ div {
label {
&::after {
content: '';
font-size: 14px;
position: absolute;
right: 8px;
pointer-events: none;
}
}
}
}
}
}
}
.bx-select-indicators {
@ -141,9 +198,11 @@ div.bx-select {
flex: 1;
background: #cfcfcf;
border-radius: 4px;
min-width: 1px;
&[data-highlighted] {
background: #9c9c9c;
min-width: 6px;
}
&[data-selected] {

View File

@ -1,4 +1,8 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='#fff' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-miterlimit='2' stroke-width='2' viewBox='0 0 32 32'>
<path d='M16.001 7.236h-2.328c-.443 0-1.941-.851-2.357-.905-.824-.106-1.684 0-2.489.176a13.04 13.04 0 0 0-3.137 1.14c-.392.275-.677.668-.866 1.104v.03l-3.302 8.963-.015.015c-.288.867-.553 3.75-.5 4.279a4.89 4.89 0 0 0 1.022 2.55c.654.823 3.71 1.364 4.057 1.016l4.462-4.475c.185-.186 1.547-.706 2.01-.706h6.884c.463 0 1.825.52 2.01.706l4.462 4.475c.347.348 3.403-.193 4.057-1.016a4.89 4.89 0 0 0 1.022-2.55c.053-.529-.212-3.412-.5-4.279l-.015-.015-3.302-8.963v-.03c-.189-.436-.474-.829-.866-1.104a13.04 13.04 0 0 0-3.137-1.14c-.805-.176-1.665-.282-2.489-.176-.416.054-1.914.905-2.357.905h-2.328' fill='none' stroke='#fff'/>
<path d='M8.172 12.914H6.519c-.235 0-.315.267-.335.452l-.052.578c0 .193.033.384.054.576.023.202.091.511.355.511h1.631l-.001 1.652c0 .234.266.315.452.335l.578.052c.193 0 .384-.033.576-.054.203-.023.511-.091.511-.355V15.03l1.652.001c.234 0 .315-.266.335-.452l.052-.578c-.001-.193-.033-.385-.055-.577-.022-.202-.09-.51-.354-.51h-1.632v-1.652c0-.234-.266-.315-.453-.335l-.577-.052c-.193 0-.385.033-.577.054-.202.023-.51.091-.51.355v1.631m16.546 2.994h-3.487c-.206 0-.413-.043-.604-.121-.177-.072-.339-.183-.476-.316-.149-.144-.259-.315-.341-.504-.156-.361-.172-.788-.032-1.157a1.57 1.57 0 0 1 .459-.641c.106-.089.223-.164.349-.222a1.52 1.52 0 0 1 .423-.123c.167-.024.338-.02.504.012a1.83 1.83 0 0 1 .455-.482 1.62 1.62 0 0 1 .522-.252c.307-.089.651-.09.959-.003a1.75 1.75 0 0 1 1.009.764 1.83 1.83 0 0 1 .251.721c.156 0 .312.031.456.09a1.24 1.24 0 0 1 .372.248c.091.087.165.19.221.302a1.19 1.19 0 0 1-.173 1.299c-.119.132-.276.239-.441.305a1.17 1.17 0 0 1-.426.08z' fill='#fff' stroke='none'/>
<svg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='none' fill-rule='evenodd' viewBox='0 0 32 32'>
<clipPath id='svg-bx-logo'>
<path d='M0 0h32v32H0z'/>
</clipPath>
<g clip-path='url(#svg-bx-logo)'>
<path d='M19.959 18.286l3.959 2.285-3.959 2.286V32L16 29.714v-9.143l3.959-2.285zM16 16V6.857l3.959-2.286 3.959 2.286-3.959 2.286v9.143L16 16zm-3.959-2.286L16 16l-3.959 2.286v9.143l-3.959-2.286V16l3.959-2.286zM8.082 2.286L12.041 0 16 2.286l-3.959 2.285v9.143l-3.959-2.285V2.286zm8.846 19.535c-.171-.098-.309-.018-.309.179s.138.437.309.536.309.018.309-.179-.138-.437-.309-.536zm0-13.714c-.171-.098-.309-.018-.309.179s.138.437.309.535.309.019.309-.178-.138-.437-.309-.536zM9.01 17.25c-.171-.099-.309-.019-.309.179s.138.437.309.535.309.019.309-.178-.138-.437-.309-.536zm0-13.714c-.171-.099-.309-.019-.309.178s.138.437.309.536.309.019.309-.179-.138-.437-.309-.535z' fill='#fff'/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 926 B

View File

@ -0,0 +1,6 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='#fff' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 32 32'>
<path d='M1.681 16h28.638'/>
<path d='M16 30.319C8.145 30.319 1.681 23.855 1.681 16S8.145 1.681 16 1.681 30.319 8.145 30.319 16'/>
<path d='M16 30.319S10.034 25.546 10.034 16 16 1.681 16 1.681 21.966 6.454 21.966 16m-.238 8.592l-2.864 2.864 2.864 2.863'/>
<path d='M21.728 20.773h5.25a3.36 3.36 0 0 1 3.341 3.341 3.36 3.36 0 0 1-3.341 3.342h-8.114'/>
</svg>

After

Width:  |  Height:  |  Size: 545 B

View File

@ -0,0 +1,7 @@
<svg xmlns='http://www.w3.org/2000/svg' width='1em' height='1em' viewBox='0 0 32 32' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round'>
<g>
<path d='M24.272 11.165h-3.294l-3.14 3.564c-.391.391-.922.611-1.476.611a2.1 2.1 0 0 1-2.087-2.088 2.09 2.09 0 0 1 .031-.362l1.22-6.274a3.89 3.89 0 0 1 3.81-3.206h6.57c1.834 0 3.439 1.573 3.833 3.295l1.205 6.185a2.09 2.09 0 0 1 .031.362 2.1 2.1 0 0 1-2.087 2.088c-.554 0-1.085-.22-1.476-.611l-3.14-3.564' fill='none' stroke='#fff' stroke-width='2'/>
<circle cx='22.625' cy='5.874' r='.879'/><path d='M11.022 24.415H7.728l-3.14 3.564c-.391.391-.922.611-1.476.611a2.1 2.1 0 0 1-2.087-2.088 2.09 2.09 0 0 1 .031-.362l1.22-6.274a3.89 3.89 0 0 1 3.81-3.206h6.57c1.834 0 3.439 1.573 3.833 3.295l1.205 6.185a2.09 2.09 0 0 1 .031.362 2.1 2.1 0 0 1-2.087 2.088c-.554 0-1.085-.22-1.476-.611l-3.14-3.564' fill='none' stroke='#fff' stroke-width='2'/>
<circle cx='9.375' cy='19.124' r='.879'/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 981 B

View File

@ -0,0 +1,4 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='#fff' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' viewBox='0 0 32 32'>
<path d='M10.417 30.271H2.97a1.25 1.25 0 0 1-1.241-1.241v-6.933c.001-.329.131-.644.363-.877L21.223 2.09c.481-.481 1.273-.481 1.754 0l6.933 6.928a1.25 1.25 0 0 1 0 1.755L10.417 30.271z'/>
<path d='M29.032 30.271H10.417m6.205-23.58l8.687 8.687'/>
</svg>

After

Width:  |  Height:  |  Size: 431 B

View File

@ -1,6 +1,9 @@
export enum GamePassCloudGallery {
ALL = 'ce573635-7c18-4d0c-9d68-90b932393470',
ALL = '29a81209-df6f-41fd-a528-2ae6b91f719c',
ALL_WITH_BYGO = 'ce573635-7c18-4d0c-9d68-90b932393470',
LEAVING_SOON = '393f05bf-e596-4ef6-9487-6d4fa0eab987',
MOST_POPULAR = 'e7590b22-e299-44db-ae22-25c61405454c',
NATIVE_MKB = '8fa264dd-124f-4af3-97e8-596fcdf4b486',
RECENTLY_ADDED = '44a55037-770f-4bbf-bde5-a9fa27dba1da',
TOUCH = '9c86f07a-f3e8-45ad-82a0-a1f759597059',
}

View File

@ -24,11 +24,13 @@ export enum GamepadKey {
LS_DOWN = 101,
LS_LEFT = 102,
LS_RIGHT = 103,
LS = 104,
RS_UP = 200,
RS_DOWN = 201,
RS_LEFT = 202,
RS_RIGHT = 203,
RS = 204,
};
export const GamepadKeyName: Record<number, [string, PrompFont]> = {
@ -56,12 +58,16 @@ export const GamepadKeyName: Record<number, [string, PrompFont]> = {
[GamepadKey.LS_DOWN]: ['Left Stick Down', PrompFont.LS_DOWN],
[GamepadKey.LS_LEFT]: ['Left Stick Left', PrompFont.LS_LEFT],
[GamepadKey.LS_RIGHT]: ['Left Stick Right', PrompFont.LS_RIGHT],
[GamepadKey.LS]: ['Left Stick', PrompFont.LS],
[GamepadKey.R3]: ['R3', PrompFont.R3],
[GamepadKey.RS_UP]: ['Right Stick Up', PrompFont.RS_UP],
[GamepadKey.RS_DOWN]: ['Right Stick Down', PrompFont.RS_DOWN],
[GamepadKey.RS_LEFT]: ['Right Stick Left', PrompFont.RS_LEFT],
[GamepadKey.RS_RIGHT]: ['Right Stick Right', PrompFont.RS_RIGHT],
[GamepadKey.RS]: ['Right Stick', PrompFont.RS],
[GamepadKey.SHARE]: ['Screenshot', PrompFont.SHARE],
};

View File

@ -37,131 +37,6 @@ export const enum MkbPresetKey {
}
export type KeyCode =
| 'Backspace'
| 'Tab'
| 'Enter'
| 'ShiftLeft'
| 'ShiftRight'
| 'ControlLeft'
| 'ControlRight'
| 'AltLeft'
| 'AltRight'
| 'Pause'
| 'CapsLock'
| 'Escape'
| 'Space'
| 'PageUp'
| 'PageDown'
| 'End'
| 'Home'
| 'ArrowLeft'
| 'ArrowUp'
| 'ArrowRight'
| 'ArrowDown'
| 'PrintScreen'
| 'Insert'
| 'Delete'
| 'Digit0'
| 'Digit1'
| 'Digit2'
| 'Digit3'
| 'Digit4'
| 'Digit5'
| 'Digit6'
| 'Digit7'
| 'Digit8'
| 'Digit9'
| 'KeyA'
| 'KeyB'
| 'KeyC'
| 'KeyD'
| 'KeyE'
| 'KeyF'
| 'KeyG'
| 'KeyH'
| 'KeyI'
| 'KeyJ'
| 'KeyK'
| 'KeyL'
| 'KeyM'
| 'KeyN'
| 'KeyO'
| 'KeyP'
| 'KeyQ'
| 'KeyR'
| 'KeyS'
| 'KeyT'
| 'KeyU'
| 'KeyV'
| 'KeyW'
| 'KeyX'
| 'KeyY'
| 'KeyZ'
| 'MetaLeft'
| 'MetaRight'
| 'ContextMenu'
| 'F1'
| 'F2'
| 'F3'
| 'F4'
| 'F5'
| 'F6'
| 'F7'
| 'F8'
| 'F9'
| 'F10'
| 'F11'
| 'F12'
| 'NumLock'
| 'ScrollLock'
| 'AudioVolumeMute'
| 'AudioVolumeDown'
| 'AudioVolumeUp'
| 'MediaTrackNext'
| 'MediaTrackPrevious'
| 'MediaStop'
| 'MediaPlayPause'
| 'LaunchMail'
| 'LaunchMediaPlayer'
| 'LaunchApplication1'
| 'LaunchApplication2'
| 'Semicolon'
| 'Equal'
| 'Comma'
| 'Minus'
| 'Period'
| 'Slash'
| 'Backquote'
| 'BracketLeft'
| 'Backslash'
| 'BracketRight'
| 'Quote'
| 'Numpad0'
| 'Numpad1'
| 'Numpad2'
| 'Numpad3'
| 'Numpad4'
| 'Numpad5'
| 'Numpad6'
| 'Numpad7'
| 'Numpad8'
| 'Numpad9'
| 'NumpadMultiply'
| 'NumpadAdd'
| 'NumpadSubtract'
| 'NumpadDecimal'
| 'NumpadDivide';
export type KeyCodeExcludeModifiers = Exclude<KeyCode,
'ShiftLeft'
| 'ShiftRight'
| 'ControlLeft'
| 'ControlRight'
| 'AltLeft'
| 'AltRight'
>
export const enum KeyModifier {
CTRL = 1,
ALT = 2,

View File

@ -1,5 +1,9 @@
import type { BaseSettingsStorage } from "@/utils/settings-storages/base-settings-storage";
import type { BlockFeature, CodecProfile, DeviceVibrationMode, GameBarPosition, LoadingScreenRocket, NativeMkbMode, StreamPlayerType, StreamResolution, StreamStat, StreamStatPosition, StreamVideoProcessing, TouchControllerMode, TouchControllerStyleCustom, TouchControllerStyleStandard, UiLayout, UiSection, UiTheme, VideoPosition, VideoPowerPreference, VideoRatio } from "./pref-values"
export const enum StorageKey {
GLOBAL = 'BetterXcloud',
STREAM = 'BetterXcloud.Stream',
LOCALE = 'BetterXcloud.Locale',
LOCALE_TRANSLATIONS = 'BetterXcloud.Locale.Translations',
@ -10,9 +14,11 @@ export const enum StorageKey {
GH_PAGES_COMMIT_HASH = 'BetterXcloud.GhPages.CommitHash',
LIST_CUSTOM_TOUCH_LAYOUTS = 'BetterXcloud.GhPages.CustomTouchLayouts',
LIST_FORCE_NATIVE_MKB = 'BetterXcloud.GhPages.ForceNativeMkb',
LIST_LOCAL_CO_OP = 'BetterXcloud.GhPages.LocalCoOp',
}
export const enum PrefKey {
export const enum GlobalPref {
VERSION_LAST_CHECK = 'version.lastCheck',
VERSION_LATEST = 'version.latest',
VERSION_CURRENT = 'version.current',
@ -39,31 +45,16 @@ export const enum PrefKey {
GAME_BAR_POSITION = 'gameBar.position',
LOCAL_CO_OP_ENABLED = 'localCoOp.enabled',
DEVICE_VIBRATION_MODE = 'deviceVibration.mode',
DEVICE_VIBRATION_INTENSITY = 'deviceVibration.intensity',
CONTROLLER_POLLING_RATE = 'controller.pollingRate',
NATIVE_MKB_MODE = 'nativeMkb.mode',
NATIVE_MKB_FORCED_GAMES = 'nativeMkb.forcedGames',
NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY = 'nativeMkb.scroll.sensitivityX',
NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY = 'nativeMkb.scroll.sensitivityY',
MKB_ENABLED = 'mkb.enabled',
MKB_HIDE_IDLE_CURSOR = 'mkb.cursor.hideIdle',
MKB_P1_MAPPING_PRESET_ID = 'mkb.p1.preset.mappingId',
MKB_P1_SLOT = 'mkb.p1.slot',
MKB_P2_MAPPING_PRESET_ID = 'mkb.p2.preset.mappingId',
MKB_P2_SLOT = 'mkb.p2.slot',
KEYBOARD_SHORTCUTS_IN_GAME_PRESET_ID = 'keyboardShortcuts.preset.inGameId',
SCREENSHOT_APPLY_FILTERS = 'screenshot.applyFilters',
BLOCK_TRACKING = 'block.tracking',
BLOCK_SOCIAL_FEATURES = 'block.social',
BLOCK_FEATURES = 'block.features',
LOADING_SCREEN_GAME_ART = 'loadingScreen.gameArt.show',
LOADING_SCREEN_SHOW_WAIT_TIME = 'loadingScreen.waitTime.show',
@ -73,7 +64,6 @@ export const enum PrefKey {
UI_LAYOUT = 'ui.layout',
UI_SCROLLBAR_HIDE = 'ui.hideScrollbar',
UI_HIDE_SECTIONS = 'ui.hideSections',
BYOG_DISABLED = 'feature.byog.disabled',
UI_GAME_CARD_SHOW_WAIT_TIME = 'ui.gameCard.waitTime.show',
UI_SIMPLIFY_STREAM_MENU = 'ui.streamMenu.simplify',
@ -83,6 +73,87 @@ export const enum PrefKey {
UI_SKIP_SPLASH_VIDEO = 'ui.splashVideo.skip',
UI_HIDE_SYSTEM_MENU_ICON = 'ui.systemMenu.hideHandle',
UI_REDUCE_ANIMATIONS = 'ui.reduceAnimations',
UI_IMAGE_QUALITY = 'ui.imageQuality',
UI_THEME = 'ui.theme',
AUDIO_MIC_ON_PLAYING = 'audio.mic.onPlaying',
AUDIO_VOLUME_CONTROL_ENABLED = 'audio.volume.booster.enabled',
REMOTE_PLAY_ENABLED = 'xhome.enabled',
REMOTE_PLAY_STREAM_RESOLUTION = 'xhome.video.resolution',
GAME_FORTNITE_FORCE_CONSOLE = 'game.fortnite.forceConsole',
}
export type GlobalPrefTypeMap = {
[GlobalPref.AUDIO_MIC_ON_PLAYING]: boolean;
[GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED]: boolean;
[GlobalPref.BLOCK_FEATURES]: BlockFeature[];
[GlobalPref.BLOCK_TRACKING]: boolean;
[GlobalPref.GAME_BAR_POSITION]: GameBarPosition;
[GlobalPref.GAME_FORTNITE_FORCE_CONSOLE]: boolean;
[GlobalPref.LOADING_SCREEN_GAME_ART]: boolean;
[GlobalPref.LOADING_SCREEN_ROCKET]: LoadingScreenRocket;
[GlobalPref.LOADING_SCREEN_SHOW_WAIT_TIME]: boolean;
[GlobalPref.MKB_ENABLED]: boolean;
[GlobalPref.MKB_HIDE_IDLE_CURSOR]: boolean;
[GlobalPref.NATIVE_MKB_FORCED_GAMES]: string[];
[GlobalPref.NATIVE_MKB_MODE]: NativeMkbMode;
[GlobalPref.REMOTE_PLAY_ENABLED]: boolean;
[GlobalPref.REMOTE_PLAY_STREAM_RESOLUTION]: StreamResolution;
[GlobalPref.SCREENSHOT_APPLY_FILTERS]: boolean;
[GlobalPref.SERVER_BYPASS_RESTRICTION]: string;
[GlobalPref.SERVER_PREFER_IPV6]: boolean;
[GlobalPref.SERVER_REGION]: string;
[GlobalPref.STREAM_CODEC_PROFILE]: CodecProfile;
[GlobalPref.STREAM_COMBINE_SOURCES]: boolean;
[GlobalPref.STREAM_MAX_VIDEO_BITRATE]: number;
[GlobalPref.STREAM_PREFERRED_LOCALE]: StreamPreferredLocale;
[GlobalPref.STREAM_RESOLUTION]: StreamResolution;
[GlobalPref.TOUCH_CONTROLLER_AUTO_OFF]: boolean;
[GlobalPref.TOUCH_CONTROLLER_DEFAULT_OPACITY]: number;
[GlobalPref.TOUCH_CONTROLLER_MODE]: TouchControllerMode;
[GlobalPref.TOUCH_CONTROLLER_STYLE_CUSTOM]: TouchControllerStyleCustom;
[GlobalPref.TOUCH_CONTROLLER_STYLE_STANDARD]: TouchControllerStyleStandard;
[GlobalPref.UI_CONTROLLER_FRIENDLY]: boolean;
[GlobalPref.UI_CONTROLLER_SHOW_STATUS]: boolean;
[GlobalPref.UI_DISABLE_FEEDBACK_DIALOG]: boolean;
[GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME]: boolean;
[GlobalPref.UI_HIDE_SECTIONS]: UiSection[];
[GlobalPref.UI_HIDE_SYSTEM_MENU_ICON]: boolean;
[GlobalPref.UI_IMAGE_QUALITY]: number;
[GlobalPref.UI_LAYOUT]: UiLayout;
[GlobalPref.UI_REDUCE_ANIMATIONS]: boolean;
[GlobalPref.UI_SCROLLBAR_HIDE]: boolean;
[GlobalPref.UI_SIMPLIFY_STREAM_MENU]: boolean;
[GlobalPref.UI_SKIP_SPLASH_VIDEO]: boolean;
[GlobalPref.UI_THEME]: UiTheme;
[GlobalPref.VERSION_CURRENT]: string;
[GlobalPref.VERSION_LAST_CHECK]: number;
[GlobalPref.VERSION_LATEST]: string;
[GlobalPref.SCRIPT_LOCALE]: string;
[GlobalPref.USER_AGENT_PROFILE]: string;
}
export const enum StreamPref {
LOCAL_CO_OP_ENABLED = 'localCoOp.enabled',
DEVICE_VIBRATION_MODE = 'deviceVibration.mode',
DEVICE_VIBRATION_INTENSITY = 'deviceVibration.intensity',
CONTROLLER_POLLING_RATE = 'controller.pollingRate',
CONTROLLER_SETTINGS = 'controller.settings',
NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY = 'nativeMkb.scroll.sensitivityX',
NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY = 'nativeMkb.scroll.sensitivityY',
MKB_P1_MAPPING_PRESET_ID = 'mkb.p1.preset.mappingId',
MKB_P1_SLOT = 'mkb.p1.slot',
MKB_P2_MAPPING_PRESET_ID = 'mkb.p2.preset.mappingId',
MKB_P2_SLOT = 'mkb.p2.slot',
KEYBOARD_SHORTCUTS_IN_GAME_PRESET_ID = 'keyboardShortcuts.preset.inGameId',
VIDEO_PLAYER_TYPE = 'video.player.type',
VIDEO_POWER_PREFERENCE = 'video.player.powerPreference',
@ -95,8 +166,6 @@ export const enum PrefKey {
VIDEO_SATURATION = 'video.saturation',
VIDEO_POSITION = 'video.position',
AUDIO_MIC_ON_PLAYING = 'audio.mic.onPlaying',
AUDIO_VOLUME_CONTROL_ENABLED = 'audio.volume.booster.enabled',
AUDIO_VOLUME = 'audio.volume',
STATS_ITEMS = 'stats.items',
@ -104,12 +173,141 @@ export const enum PrefKey {
STATS_QUICK_GLANCE_ENABLED = 'stats.quickGlance.enabled',
STATS_POSITION = 'stats.position',
STATS_TEXT_SIZE = 'stats.textSize',
STATS_TRANSPARENT = 'stats.transparent',
STATS_OPACITY = 'stats.opacity',
STATS_OPACITY_ALL = 'stats.opacity.all',
STATS_OPACITY_BACKGROUND = 'stats.opacity.background',
STATS_CONDITIONAL_FORMATTING = 'stats.colors',
REMOTE_PLAY_ENABLED = 'xhome.enabled',
REMOTE_PLAY_STREAM_RESOLUTION = 'xhome.video.resolution',
GAME_FORTNITE_FORCE_CONSOLE = 'game.fortnite.forceConsole',
}
export type StreamPrefTypeMap = {
[StreamPref.AUDIO_VOLUME]: number;
[StreamPref.CONTROLLER_POLLING_RATE]: number;
[StreamPref.CONTROLLER_SETTINGS]: ControllerSettings;
[StreamPref.DEVICE_VIBRATION_INTENSITY]: number;
[StreamPref.DEVICE_VIBRATION_MODE]: DeviceVibrationMode;
[StreamPref.KEYBOARD_SHORTCUTS_IN_GAME_PRESET_ID]: number;
[StreamPref.LOCAL_CO_OP_ENABLED]: boolean;
[StreamPref.MKB_P1_MAPPING_PRESET_ID]: number;
[StreamPref.MKB_P1_SLOT]: number;
[StreamPref.MKB_P2_MAPPING_PRESET_ID]: number;
[StreamPref.MKB_P2_SLOT]: number;
[StreamPref.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY]: number;
[StreamPref.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY]: number;
[StreamPref.STATS_CONDITIONAL_FORMATTING]: boolean;
[StreamPref.STATS_ITEMS]: StreamStat[];
[StreamPref.STATS_OPACITY_ALL]: number;
[StreamPref.STATS_OPACITY_BACKGROUND]: number;
[StreamPref.STATS_POSITION]: StreamStatPosition;
[StreamPref.STATS_QUICK_GLANCE_ENABLED]: boolean;
[StreamPref.STATS_SHOW_WHEN_PLAYING]: boolean;
[StreamPref.STATS_TEXT_SIZE]: string;
[StreamPref.VIDEO_BRIGHTNESS]: number;
[StreamPref.VIDEO_CONTRAST]: number;
[StreamPref.VIDEO_MAX_FPS]: number;
[StreamPref.VIDEO_PLAYER_TYPE]: StreamPlayerType;
[StreamPref.VIDEO_POSITION]: VideoPosition;
[StreamPref.VIDEO_POWER_PREFERENCE]: VideoPowerPreference;
[StreamPref.VIDEO_PROCESSING]: StreamVideoProcessing;
[StreamPref.VIDEO_RATIO]: VideoRatio;
[StreamPref.VIDEO_SATURATION]: number;
[StreamPref.VIDEO_SHARPNESS]: number;
}
export type AllPrefs = GlobalPref | StreamPref;
export const ALL_PREFS: {
global: GlobalPref[],
stream: StreamPref[],
} = {
global: [
GlobalPref.AUDIO_MIC_ON_PLAYING,
GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED,
GlobalPref.BLOCK_FEATURES,
GlobalPref.BLOCK_TRACKING,
GlobalPref.GAME_BAR_POSITION,
GlobalPref.GAME_FORTNITE_FORCE_CONSOLE,
GlobalPref.LOADING_SCREEN_GAME_ART,
GlobalPref.LOADING_SCREEN_ROCKET,
GlobalPref.LOADING_SCREEN_SHOW_WAIT_TIME,
GlobalPref.MKB_ENABLED,
GlobalPref.MKB_HIDE_IDLE_CURSOR,
GlobalPref.NATIVE_MKB_FORCED_GAMES,
GlobalPref.NATIVE_MKB_MODE,
GlobalPref.REMOTE_PLAY_ENABLED,
GlobalPref.REMOTE_PLAY_STREAM_RESOLUTION,
GlobalPref.SCREENSHOT_APPLY_FILTERS,
GlobalPref.SERVER_BYPASS_RESTRICTION,
GlobalPref.SERVER_PREFER_IPV6,
GlobalPref.SERVER_REGION,
GlobalPref.STREAM_CODEC_PROFILE,
GlobalPref.STREAM_COMBINE_SOURCES,
GlobalPref.STREAM_MAX_VIDEO_BITRATE,
GlobalPref.STREAM_PREFERRED_LOCALE,
GlobalPref.STREAM_RESOLUTION,
GlobalPref.TOUCH_CONTROLLER_AUTO_OFF,
GlobalPref.TOUCH_CONTROLLER_DEFAULT_OPACITY,
GlobalPref.TOUCH_CONTROLLER_MODE,
GlobalPref.TOUCH_CONTROLLER_STYLE_CUSTOM,
GlobalPref.TOUCH_CONTROLLER_STYLE_STANDARD,
GlobalPref.UI_CONTROLLER_FRIENDLY,
GlobalPref.UI_CONTROLLER_SHOW_STATUS,
GlobalPref.UI_DISABLE_FEEDBACK_DIALOG,
GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME,
GlobalPref.UI_HIDE_SECTIONS,
GlobalPref.UI_HIDE_SYSTEM_MENU_ICON,
GlobalPref.UI_IMAGE_QUALITY,
GlobalPref.UI_LAYOUT,
GlobalPref.UI_REDUCE_ANIMATIONS,
GlobalPref.UI_SCROLLBAR_HIDE,
GlobalPref.UI_SIMPLIFY_STREAM_MENU,
GlobalPref.UI_SKIP_SPLASH_VIDEO,
GlobalPref.UI_THEME,
GlobalPref.VERSION_CURRENT,
GlobalPref.VERSION_LAST_CHECK,
GlobalPref.VERSION_LATEST,
GlobalPref.SCRIPT_LOCALE,
GlobalPref.USER_AGENT_PROFILE,
],
stream: [
StreamPref.AUDIO_VOLUME,
StreamPref.CONTROLLER_POLLING_RATE,
StreamPref.CONTROLLER_SETTINGS,
StreamPref.DEVICE_VIBRATION_INTENSITY,
StreamPref.DEVICE_VIBRATION_MODE,
StreamPref.KEYBOARD_SHORTCUTS_IN_GAME_PRESET_ID,
StreamPref.LOCAL_CO_OP_ENABLED,
StreamPref.MKB_P1_MAPPING_PRESET_ID,
StreamPref.MKB_P1_SLOT,
StreamPref.MKB_P2_MAPPING_PRESET_ID,
StreamPref.MKB_P2_SLOT,
StreamPref.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY,
StreamPref.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY,
StreamPref.STATS_CONDITIONAL_FORMATTING,
StreamPref.STATS_ITEMS,
StreamPref.STATS_OPACITY_ALL,
StreamPref.STATS_OPACITY_BACKGROUND,
StreamPref.STATS_POSITION,
StreamPref.STATS_QUICK_GLANCE_ENABLED,
StreamPref.STATS_SHOW_WHEN_PLAYING,
StreamPref.STATS_TEXT_SIZE,
StreamPref.VIDEO_BRIGHTNESS,
StreamPref.VIDEO_CONTRAST,
StreamPref.VIDEO_MAX_FPS,
StreamPref.VIDEO_PLAYER_TYPE,
StreamPref.VIDEO_POSITION,
StreamPref.VIDEO_POWER_PREFERENCE,
StreamPref.VIDEO_PROCESSING,
StreamPref.VIDEO_RATIO,
StreamPref.VIDEO_SATURATION,
StreamPref.VIDEO_SHARPNESS,
],
} as const;
export type AnySettingsStorage = BaseSettingsStorage<GlobalPref> | BaseSettingsStorage<StreamPref>;
export type AnyPref = GlobalPref | StreamPref;
export type PrefTypeMap<Key> = Key extends GlobalPref
? GlobalPrefTypeMap
: Key extends StreamPref
? StreamPrefTypeMap
: never;

View File

@ -6,6 +6,9 @@ export const enum UiSection {
NEWS = 'news',
TOUCH = 'touch',
BOYG = 'byog',
RECENTLY_ADDED = 'recently-added',
LEAVING_SOON = 'leaving-soon',
GENRES = 'genres',
}
export const enum GameBarPosition {
@ -84,6 +87,12 @@ export const enum StreamStat {
CLOCK = 'time',
};
export const enum StreamStatPosition {
TOP_LEFT = 'top-left',
TOP_CENTER = 'top-center',
TOP_RIGHT = 'top-right',
}
export const enum VideoRatio {
'16:9' = '16:9',
'18:9' = '18:9',
@ -101,12 +110,32 @@ export const enum VideoPosition {
BOTTOM_HALF = 'bottom-half',
}
export const enum VideoPowerPreference {
DEFAULT = 'default',
LOW_POWER = 'low-power',
HIGH_PERFORMANCE = 'high-performance',
}
export const enum StreamPlayerType {
VIDEO = 'default',
WEBGL2 = 'webgl2',
WEBGPU = 'webgpu',
}
export const enum StreamVideoProcessing {
USM = 'usm',
CAS = 'cas',
}
export const enum BlockFeature {
CHAT = 'chat',
FRIENDS = 'friends',
BYOG = 'byog',
NOTIFICATIONS_INVITES = 'notifications-invites',
NOTIFICATIONS_ACHIEVEMENTS = 'notifications-achievements',
}
export const enum UiTheme {
DEFAULT = 'default',
DARK_OLED = 'dark-oled',
}

View File

@ -18,15 +18,19 @@ export enum PrompFont {
LEFT = '≺',
RIGHT = '≼',
LS = '⇱',
L3 = '↺',
LS_UP = '↾',
LS_DOWN = '⇂',
LS_LEFT = '↼',
LS_RIGHT = '⇀',
RS = '⇲',
R3 = '↻',
RS_UP = '↿',
RS_DOWN = '⇃',
RS_LEFT = '↽',
RS_RIGHT = '⇁',
SHARE = '⇧',
}

View File

@ -1,6 +1,8 @@
export const enum ShortcutAction {
BETTER_XCLOUD_SETTINGS_SHOW = 'bx.settings.show',
CONTROLLER_XBOX_BUTTON_PRESS = 'controller.xbox.press',
STREAM_VIDEO_TOGGLE = 'stream.video.toggle',
STREAM_SCREENSHOT_CAPTURE = 'stream.screenshot.capture',

View File

@ -27,23 +27,28 @@ import { ScreenshotManager } from "./utils/screenshot-manager";
import { NativeMkbHandler } from "./modules/mkb/native-mkb-handler";
import { GuideMenu } from "./modules/ui/guide-menu";
import { updateVideoPlayer } from "./modules/stream/stream-settings-utils";
import { NativeMkbMode, TouchControllerMode, UiSection } from "./enums/pref-values";
import { BlockFeature, NativeMkbMode, TouchControllerMode, UiSection } from "./enums/pref-values";
import { HeaderSection } from "./modules/ui/header";
import { GameTile } from "./modules/ui/game-tile";
import { ProductDetailsPage } from "./modules/ui/product-details";
import { NavigationDialogManager } from "./modules/ui/dialog/navigation-dialog";
import { PrefKey } from "./enums/pref-keys";
import { getPref } from "./utils/settings-storages/global-settings-storage";
import { SettingsDialog } from "./modules/ui/dialog/settings-dialog";
import { StreamUiHandler } from "./modules/stream/stream-ui";
import { GlobalPref, StreamPref } from "./enums/pref-keys";
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";
import { DeviceVibrationManager } from "./modules/device-vibration-manager";
import { BxEventBus } from "./utils/bx-event-bus";
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();
// Handle login page
if (window.location.pathname.includes('/auth/msa')) {
@ -112,7 +117,7 @@ if (isFullVersion() && BX_FLAGS.SafariWorkaround && document.readyState !== 'loa
const isSafari = UserAgent.isSafari();
let $secondaryAction: HTMLElement;
if (isSafari) {
$secondaryAction = CE('p', {}, t('settings-reloading'));
$secondaryAction = CE('p', false, t('settings-reloading'));
} else {
$secondaryAction = CE('a', {
href: 'https://better-xcloud.github.io/troubleshooting',
@ -122,12 +127,12 @@ if (isFullVersion() && BX_FLAGS.SafariWorkaround && document.readyState !== 'loa
// Show the reloading overlay
const $fragment = document.createDocumentFragment();
$fragment.appendChild(CE('style', {}, css));
$fragment.appendChild(CE('style', false, css));
$fragment.appendChild(CE('div',{
class: 'bx-reload-overlay',
},
CE('div', {},
CE('p', {}, t('load-failed-message')),
CE('div', false,
CE('p', false, t('load-failed-message')),
$secondaryAction,
),
));
@ -159,18 +164,20 @@ document.addEventListener('readystatechange', e => {
return;
}
STATES.isSignedIn = !!((window as any).xbcUser?.isSignedIn);
STATES.isSignedIn = !!window.xbcUser?.isSignedIn;
if (STATES.isSignedIn) {
// Preload Remote Play
RemotePlayManager.getInstance()?.initialize();
if (isFullVersion()) {
RemotePlayManager.getInstance()?.initialize();
}
} 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
if (getPref<UiSection[]>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.FRIENDS)) {
if (getGlobalPref(GlobalPref.UI_HIDE_SECTIONS).includes(UiSection.FRIENDS) || getGlobalPref(GlobalPref.BLOCK_FEATURES).includes(BlockFeature.FRIENDS)) {
const $parent = document.querySelector('div[class*=PlayWithFriendsSkeleton]')?.closest<HTMLElement>('div[class*=HomePage-module]');
$parent && ($parent.style.display = 'none');
}
@ -190,35 +197,23 @@ window.addEventListener('popstate', onHistoryChanged);
window.history.pushState = patchHistoryMethod('pushState');
window.history.replaceState = patchHistoryMethod('replaceState');
window.addEventListener(BxEvent.XCLOUD_SERVERS_UNAVAILABLE, e => {
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();
}
}, { once: true });
window.addEventListener(BxEvent.XCLOUD_SERVERS_READY, e => {
STATES.isSignedIn = true;
window.setTimeout(HeaderSection.watchHeader, 2000);
BxEventBus.Script.on('ui.header.rendered', () => {
HeaderSection.getInstance().checkHeader();
});
window.addEventListener(BxEvent.STREAM_LOADING, e => {
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';
}
});
// Setup loading screen
getPref(PrefKey.LOADING_SCREEN_GAME_ART) && window.addEventListener(BxEvent.TITLE_INFO_READY, LoadingScreen.setup);
getGlobalPref(GlobalPref.LOADING_SCREEN_GAME_ART) && BxEventBus.Script.on('titleInfo.ready', LoadingScreen.setup);
window.addEventListener(BxEvent.STREAM_STARTING, e => {
BxEventBus.Stream.on('state.starting', () => {
// Hide loading screen
LoadingScreen.hide();
@ -232,12 +227,13 @@ window.addEventListener(BxEvent.STREAM_STARTING, e => {
}
});
window.addEventListener(BxEvent.STREAM_PLAYING, e => {
window.BX_STREAM_SETTINGS = StreamSettings.settings;
StreamSettings.refreshAllSettings();
BxEventBus.Stream.on('state.playing', payload => {
if (isFullVersion()) {
window.BX_STREAM_SETTINGS = StreamSettings.settings;
StreamSettings.refreshAllSettings();
}
STATES.isPlaying = true;
StreamUiHandler.observe();
if (isFullVersion()) {
const gameBar = GameBar.getInstance();
@ -251,21 +247,52 @@ window.addEventListener(BxEvent.STREAM_PLAYING, e => {
KeyboardShortcutHandler.getInstance().start();
// Setup screenshot
const $video = (e as any).$video as HTMLVideoElement;
const $video = payload.$video as HTMLVideoElement;
ScreenshotManager.getInstance().updateCanvasSize($video.videoWidth, $video.videoHeight);
// Setup local co-op
getPref(PrefKey.LOCAL_CO_OP_ENABLED) && BxExposed.toggleLocalCoOp(getPref(PrefKey.LOCAL_CO_OP_ENABLED));
if (getStreamPref(StreamPref.LOCAL_CO_OP_ENABLED)) {
BxExposed.toggleLocalCoOp(true);
Toast.show(t('local-co-op'), t('enabled'));
}
}
updateVideoPlayer();
});
window.addEventListener(BxEvent.STREAM_ERROR_PAGE, e => {
BxEvent.dispatch(window, BxEvent.STREAM_STOPPED);
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') {
@ -274,9 +301,9 @@ isFullVersion() && window.addEventListener(BxEvent.XCLOUD_RENDERING_COMPONENT, e
});
// Detect game change
window.addEventListener(BxEvent.DATA_CHANNEL_CREATED, e => {
const dataChannel = (e as any).dataChannel;
if (!dataChannel || dataChannel.label !== 'message') {
BxEventBus.Stream.on('dataChannelCreated', payload => {
const { dataChannel } = payload;
if (dataChannel?.label !== 'message') {
return;
}
@ -285,31 +312,47 @@ window.addEventListener(BxEvent.DATA_CHANNEL_CREATED, e => {
return;
}
// Get xboxTitleId from message
if (msg.data.includes('/titleinfo')) {
const json = JSON.parse(JSON.parse(msg.data).content);
const xboxTitleId = parseInt(json.titleid, 16);
STATES.currentStream.xboxTitleId = xboxTitleId;
if (!msg.data.includes('/titleinfo')) {
return;
}
// Get titleSlug for Remote Play
if (STATES.remotePlay.isPlaying) {
STATES.currentStream.titleSlug = 'remote-play';
if (json.focused) {
const productTitle = await XboxApi.getProductTitle(xboxTitleId);
if (productTitle) {
STATES.currentStream.titleSlug = productTitleToSlug(productTitle);
}
// Get xboxTitleId from message
const currentStream = STATES.currentStream;
const json = JSON.parse(JSON.parse(msg.data).content);
const currentId = currentStream.xboxTitleId ?? null;
let newId: number = parseInt(json.titleid, 16);
// Get titleSlug for Remote Play
if (STATES.remotePlay.isPlaying) {
currentStream.titleSlug = 'remote-play';
if (json.focused) {
const productTitle = await XboxApi.getProductTitle(newId);
if (productTitle) {
currentStream.titleSlug = productTitleToSlug(productTitle);
} else {
newId = -1;
}
} else {
newId = 0;
}
}
if (currentId !== newId) {
currentStream.xboxTitleId = newId;
BxEventBus.Stream.emit('xboxTitleId.changed', {
id: newId,
});
}
});
});
function unload() {
if (!STATES.isPlaying) {
return;
}
BxLogger.warning('Unloading');
if (isFullVersion()) {
KeyboardShortcutHandler.getInstance().stop();
@ -321,7 +364,7 @@ function unload() {
}
// Destroy StreamPlayer
STATES.currentStream.streamPlayer?.destroy();
STATES.currentStream.streamPlayerManager?.destroy();
STATES.isPlaying = false;
STATES.currentStream = {};
@ -337,12 +380,14 @@ function unload() {
TouchController.reset();
GameBar.getInstance()?.disable();
BxEventBus.Stream.emit('xboxTitleId.changed', { id: -1 });
}
}
window.addEventListener(BxEvent.STREAM_STOPPED, unload);
BxEventBus.Stream.on('state.stopped', unload);
window.addEventListener('pagehide', e => {
BxEvent.dispatch(window, BxEvent.STREAM_STOPPED);
BxEventBus.Stream.emit('state.stopped', {});
});
isFullVersion() && window.addEventListener(BxEvent.CAPTURE_SCREENSHOT, e => {
@ -353,9 +398,11 @@ isFullVersion() && window.addEventListener(BxEvent.CAPTURE_SCREENSHOT, e => {
function main() {
GhPagesUtils.fetchLatestCommit();
if (getPref<NativeMkbMode>(PrefKey.NATIVE_MKB_MODE) !== NativeMkbMode.OFF) {
const customList = getPref<string[]>(PrefKey.NATIVE_MKB_FORCED_GAMES);
BX_FLAGS.ForceNativeMkbTitles.push(...customList);
if (isFullVersion()) {
if (getGlobalPref(GlobalPref.NATIVE_MKB_MODE) !== NativeMkbMode.OFF) {
const customList = getGlobalPref(GlobalPref.NATIVE_MKB_FORCED_GAMES);
BX_FLAGS.ForceNativeMkbTitles.push(...customList);
}
}
StreamSettings.setup();
@ -368,24 +415,23 @@ function main() {
patchCanvasContext();
isFullVersion() && AppInterface && patchPointerLockApi();
getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED) && patchAudioContext();
getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED) && patchAudioContext();
if (getPref(PrefKey.BLOCK_TRACKING)) {
if (getGlobalPref(GlobalPref.BLOCK_TRACKING)) {
patchMeControl();
disableAdobeAudienceManager();
}
RootDialogObserver.waitForRootDialog();
// Setup UI
addCss();
GuideMenu.getInstance().addEventListeners();
StreamStatsCollector.setupEvents();
StreamBadges.setupEvents();
StreamStats.setupEvents();
if (isFullVersion()) {
WebGPUPlayer.prepare();
STATES.userAgent.capabilities.touch && TouchController.updateCustomList();
DeviceVibrationManager.getInstance();
@ -397,28 +443,28 @@ function main() {
disablePwa();
// Preload Remote Play
if (getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
if (getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED)) {
RemotePlayManager.detect();
}
if (getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL) {
if (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL) {
TouchController.setup();
}
// Start PointerProviderServer
if (AppInterface && (getPref(PrefKey.MKB_ENABLED) || getPref<NativeMkbMode>(PrefKey.NATIVE_MKB_MODE) === NativeMkbMode.ON)) {
if (AppInterface && (getGlobalPref(GlobalPref.MKB_ENABLED) || getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON)) {
STATES.pointerServerPort = AppInterface.startPointerServer() || 9269;
BxLogger.info('startPointerServer', 'Port', STATES.pointerServerPort.toString());
}
// Show wait time in game card
getPref(PrefKey.UI_GAME_CARD_SHOW_WAIT_TIME) && GameTile.setup();
getGlobalPref(GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME) && GameTile.setup();
EmulatedMkbHandler.setupEvents();
}
// Show a toast when connecting/disconecting controller
if (getPref(PrefKey.UI_CONTROLLER_SHOW_STATUS)) {
if (getGlobalPref(GlobalPref.UI_CONTROLLER_SHOW_STATUS)) {
window.addEventListener('gamepadconnected', e => showGamepadToast(e.gamepad));
window.addEventListener('gamepaddisconnected', e => showGamepadToast(e.gamepad));
}

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

@ -1,6 +1,6 @@
import { AppInterface, STATES } from "@utils/global";
import { BxEvent } from "@utils/bx-event";
import { StreamSettings } from "@/utils/stream-settings";
import { BxEventBus } from "@/utils/bx-event-bus";
const VIBRATION_DATA_MAP = {
gamepadIndex: 8,
@ -37,8 +37,8 @@ export class DeviceVibrationManager {
constructor() {
this.boundOnMessage = this.onMessage.bind(this);
window.addEventListener(BxEvent.DATA_CHANNEL_CREATED, e => {
const dataChannel = (e as any).dataChannel as RTCDataChannel;
BxEventBus.Stream.on('dataChannelCreated', payload => {
const { dataChannel } = payload;
if (dataChannel?.label === 'input') {
this.reset();
@ -47,9 +47,7 @@ export class DeviceVibrationManager {
}
});
window.addEventListener(BxEvent.DEVICE_VIBRATION_CHANGED, e => {
this.setupDataChannel();
});
BxEventBus.Stream.on('deviceVibration.updated', () => this.setupDataChannel());
}
private setupDataChannel() {

View File

@ -1,4 +1,4 @@
import { BxEvent } from "@/utils/bx-event";
import { BxEventBus } from "@/utils/bx-event-bus";
export abstract class BaseGameBarAction {
abstract $content: HTMLElement;
@ -7,7 +7,7 @@ export abstract class BaseGameBarAction {
reset() {}
onClick(e: Event) {
BxEvent.dispatch(window, BxEvent.GAME_BAR_ACTION_ACTIVATED);
BxEventBus.Stream.emit('gameBar.activated', {});
};
render(): HTMLElement {

View File

@ -6,20 +6,21 @@ import { BxIcon } from "@utils/bx-icon";
import type { BaseGameBarAction } from "./base-action";
import { STATES } from "@utils/global";
import { MicrophoneAction } from "./microphone-action";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref } from "@/enums/pref-keys";
import { TrueAchievementsAction } from "./true-achievements-action";
import { SpeakerAction } from "./speaker-action";
import { RendererAction } from "./renderer-action";
import { BxLogger } from "@/utils/bx-logger";
import { GameBarPosition, TouchControllerMode } from "@/enums/pref-values";
import { BxEventBus } from "@/utils/bx-event-bus";
import { getGlobalPref } from "@/utils/pref-utils";
export class GameBar {
private static instance: GameBar | null | undefined;
public static getInstance(): typeof GameBar['instance'] {
if (typeof GameBar.instance === 'undefined') {
if (getPref<GameBarPosition>(PrefKey.GAME_BAR_POSITION) !== GameBarPosition.OFF) {
if (getGlobalPref(GlobalPref.GAME_BAR_POSITION) !== GameBarPosition.OFF) {
GameBar.instance = new GameBar();
} else {
GameBar.instance = null;
@ -45,7 +46,7 @@ export class GameBar {
let $container;
const position = getPref<GameBarPosition>(PrefKey.GAME_BAR_POSITION);
const position = getGlobalPref(GlobalPref.GAME_BAR_POSITION);
const $gameBar = CE('div', { id: 'bx-game-bar', class: 'bx-gone', 'data-position': position },
$container = CE('div', { class: 'bx-game-bar-container bx-offscreen' }),
@ -54,7 +55,7 @@ export class GameBar {
this.actions = [
new ScreenshotAction(),
...(STATES.userAgent.capabilities.touch && (getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) !== TouchControllerMode.OFF) ? [new TouchControlAction()] : []),
...(STATES.userAgent.capabilities.touch && (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) !== TouchControllerMode.OFF) ? [new TouchControlAction()] : []),
new SpeakerAction(),
new RendererAction(),
new MicrophoneAction(),
@ -81,7 +82,7 @@ export class GameBar {
});
// Hide game bar after clicking on an action
window.addEventListener(BxEvent.GAME_BAR_ACTION_ACTIVATED, this.hideBar);
BxEventBus.Stream.on('gameBar.activated', this.hideBar);
$container.addEventListener('pointerover', this.clearHideTimeout);
$container.addEventListener('pointerout', this.beginHideTimeout);

View File

@ -1,8 +1,8 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BaseGameBarAction } from "./base-action";
import { MicrophoneShortcut, MicrophoneState } from "../shortcuts/microphone-shortcut";
import { BxEventBus } from "@/utils/bx-event-bus";
export class MicrophoneAction extends BaseGameBarAction {
@ -24,11 +24,10 @@ export class MicrophoneAction extends BaseGameBarAction {
onClick: this.onClick,
});
this.$content = CE('div', {}, $btnMuted, $btnDefault);
this.$content = CE('div', false, $btnMuted, $btnDefault);
window.addEventListener(BxEvent.MICROPHONE_STATE_CHANGED, e => {
const microphoneState = (e as any).microphoneState;
const enabled = microphoneState === MicrophoneState.ENABLED;
BxEventBus.Stream.on('microphone.state.changed', payload => {
const enabled = payload.state === MicrophoneState.ENABLED;
this.$content.dataset.activated = enabled.toString();
// Show the button in Game Bar if the mic is enabled

View File

@ -2,7 +2,7 @@ import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BaseGameBarAction } from "./base-action";
import { RendererShortcut } from "../shortcuts/renderer-shortcut";
import { BxEvent } from "@/utils/bx-event";
import { BxEventBus } from "@/utils/bx-event-bus";
export class RendererAction extends BaseGameBarAction {
@ -24,11 +24,10 @@ export class RendererAction extends BaseGameBarAction {
classes: ['bx-activated'],
});
this.$content = CE('div', {}, $btnDefault, $btnActivated);
this.$content = CE('div', false, $btnDefault, $btnActivated);
window.addEventListener(BxEvent.VIDEO_VISIBILITY_CHANGED, e => {
const isShowing = (e as any).isShowing;
this.$content.dataset.activated = (!isShowing).toString();
BxEventBus.Stream.on('video.visibility.changed', payload => {
this.$content.dataset.activated = (!payload.isVisible).toString();
});
}

View File

@ -1,8 +1,8 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BaseGameBarAction } from "./base-action";
import { SoundShortcut, SpeakerState } from "../shortcuts/sound-shortcut";
import { BxEventBus } from "@/utils/bx-event-bus";
export class SpeakerAction extends BaseGameBarAction {
@ -24,12 +24,10 @@ export class SpeakerAction extends BaseGameBarAction {
classes: ['bx-activated'],
});
this.$content = CE('div', {}, $btnEnable, $btnMuted);
window.addEventListener(BxEvent.SPEAKER_STATE_CHANGED, e => {
const speakerState = (e as any).speakerState;
const enabled = speakerState === SpeakerState.ENABLED;
this.$content = CE('div', false, $btnEnable, $btnMuted);
BxEventBus.Stream.on('speaker.state.changed', payload => {
const enabled = payload.state === SpeakerState.ENABLED;
this.$content.dataset.activated = (!enabled).toString();
});
}

View File

@ -25,7 +25,7 @@ export class TouchControlAction extends BaseGameBarAction {
classes: ['bx-activated'],
});
this.$content = CE('div', {}, $btnEnable, $btnDisable);
this.$content = CE('div', false, $btnEnable, $btnDisable);
}
onClick = (e: Event) => {

View File

@ -2,8 +2,8 @@ import { CE } from "@utils/html";
import { getPreferredServerRegion } from "@utils/region";
import { t } from "@utils/translation";
import { STATES } from "@utils/global";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { compressCss } from "@macros/build" with { type: "macro" };
import { LoadingScreenRocket } from "@/enums/pref-values";
@ -35,9 +35,11 @@ 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 (getPref<LoadingScreenRocket>(PrefKey.LOADING_SCREEN_ROCKET) === LoadingScreenRocket.HIDE) {
if (getGlobalPref(GlobalPref.LOADING_SCREEN_ROCKET) === LoadingScreenRocket.HIDE) {
LoadingScreen.hideRocket();
}
}
@ -63,6 +65,11 @@ export class LoadingScreen {
// Limit max width to reduce image size
imageUrl = imageUrl + '?w=1920';
const imageQuality = getGlobalPref(GlobalPref.UI_IMAGE_QUALITY);
if (imageQuality !== 90) {
imageUrl += '&q=' + imageQuality;
}
$bgStyle.textContent! += compressCss(`
#game-stream {
background-color: transparent !important;
@ -89,7 +96,7 @@ export class LoadingScreen {
static setupWaitTime(waitTime: number) {
// Hide rocket when queing
if (getPref<LoadingScreenRocket>(PrefKey.LOADING_SCREEN_ROCKET) === LoadingScreenRocket.HIDE_QUEUE) {
if (getGlobalPref(GlobalPref.LOADING_SCREEN_ROCKET) === LoadingScreenRocket.HIDE_QUEUE) {
LoadingScreen.hideRocket();
}
@ -110,11 +117,11 @@ export class LoadingScreen {
let $waitTimeBox = LoadingScreen.$waitTimeBox;
if (!$waitTimeBox) {
$waitTimeBox = CE('div', { class: 'bx-wait-time-box' },
CE('label', {}, t('server')),
CE('span', {}, getPreferredServerRegion()),
CE('label', {}, t('wait-time-estimated')),
CE('label', false, t('server')),
CE('span', false, getPreferredServerRegion()),
CE('label', false, t('wait-time-estimated')),
$estimated = CE('span', {}),
CE('label', {}, t('wait-time-countdown')),
CE('label', false, t('wait-time-countdown')),
$countDown = CE('span', {}),
);
@ -146,7 +153,7 @@ export class LoadingScreen {
LoadingScreen.orgWebTitle && (document.title = LoadingScreen.orgWebTitle);
LoadingScreen.$waitTimeBox && LoadingScreen.$waitTimeBox.classList.add('bx-gone');
if (getPref(PrefKey.LOADING_SCREEN_GAME_ART) && LoadingScreen.$bgStyle) {
if (getGlobalPref(GlobalPref.LOADING_SCREEN_GAME_ART) && LoadingScreen.$bgStyle) {
const $rocketBg = document.querySelector('#game-stream rect[width="800"]');
$rocketBg && $rocketBg.addEventListener('transitionend', e => {
LoadingScreen.$bgStyle.textContent += compressCss(`

View File

@ -1,4 +1,4 @@
import { MouseButtonCode, WheelCode, type KeyCode } from "@/enums/mkb";
import { MouseButtonCode, WheelCode } from "@/enums/mkb";
export const enum KeyModifier {
CTRL = 1,

View File

@ -11,13 +11,15 @@ import { BxLogger } from "@utils/bx-logger";
import { PointerClient } from "./pointer-client";
import { NativeMkbHandler } from "./native-mkb-handler";
import { MkbHandler, MouseDataProvider } from "./base-mkb-handler";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref, StreamPref } from "@/enums/pref-keys";
import { getGlobalPref, getStreamPref } from "@/utils/pref-utils";
import { GamepadKey, GamepadStick } from "@/enums/gamepad";
import { MkbPopup } from "./mkb-popup";
import type { MkbConvertedPresetData } from "@/types/presets";
import { StreamSettings } from "@/utils/stream-settings";
import { ShortcutAction } from "@/enums/shortcut-actions";
import { BxEventBus } from "@/utils/bx-event-bus";
import { generateVirtualControllerMapping, toXcloudGamepadKey } from "@/utils/gamepad";
const PointerToMouseButton = {
1: 0,
@ -132,7 +134,7 @@ export class EmulatedMkbHandler extends MkbHandler {
private static readonly LOG_TAG = 'EmulatedMkbHandler';
static isAllowed() {
return getPref(PrefKey.MKB_ENABLED) && (AppInterface || !UserAgent.isMobile());
return getGlobalPref(GlobalPref.MKB_ENABLED) && (AppInterface || !UserAgent.isMobile());
}
private PRESET!: MkbConvertedPresetData | null;
@ -151,6 +153,8 @@ export class EmulatedMkbHandler extends MkbHandler {
};
private nativeGetGamepads: Navigator['getGamepads'];
private xCloudGamepad: XcloudGamepad = generateVirtualControllerMapping(0);
private initialized = false;
private enabled = false;
private mouseDataProvider: MouseDataProvider | undefined;
@ -170,16 +174,16 @@ export class EmulatedMkbHandler extends MkbHandler {
private popup: MkbPopup;
private STICK_MAP: { [key in GamepadKey]?: [GamepadKey[], number, number] } = {
[GamepadKey.LS_LEFT]: [this.LEFT_STICK_X, 0, -1],
[GamepadKey.LS_RIGHT]: [this.LEFT_STICK_X, 0, 1],
[GamepadKey.LS_UP]: [this.LEFT_STICK_Y, 1, -1],
[GamepadKey.LS_DOWN]: [this.LEFT_STICK_Y, 1, 1],
private STICK_MAP: { [key in GamepadKey]?: [GamepadKey[], number] } = {
[GamepadKey.LS_LEFT]: [this.LEFT_STICK_X, -1],
[GamepadKey.LS_RIGHT]: [this.LEFT_STICK_X, 1],
[GamepadKey.LS_UP]: [this.LEFT_STICK_Y, 1],
[GamepadKey.LS_DOWN]: [this.LEFT_STICK_Y, -1],
[GamepadKey.RS_LEFT]: [this.RIGHT_STICK_X, 2, -1],
[GamepadKey.RS_RIGHT]: [this.RIGHT_STICK_X, 2, 1],
[GamepadKey.RS_UP]: [this.RIGHT_STICK_Y, 3, -1],
[GamepadKey.RS_DOWN]: [this.RIGHT_STICK_Y, 3, 1],
[GamepadKey.RS_LEFT]: [this.RIGHT_STICK_X, -1],
[GamepadKey.RS_RIGHT]: [this.RIGHT_STICK_X, 1],
[GamepadKey.RS_UP]: [this.RIGHT_STICK_Y, 1],
[GamepadKey.RS_DOWN]: [this.RIGHT_STICK_Y, -1],
};
private constructor() {
@ -204,11 +208,16 @@ export class EmulatedMkbHandler extends MkbHandler {
private getVirtualGamepad = () => this.VIRTUAL_GAMEPAD;
private updateStick(stick: GamepadStick, x: number, y: number) {
const virtualGamepad = this.getVirtualGamepad();
virtualGamepad.axes[stick * 2] = x;
virtualGamepad.axes[stick * 2 + 1] = y;
const gamepad = this.xCloudGamepad;
if (stick === GamepadStick.LEFT) {
gamepad.LeftThumbXAxis = x;
gamepad.LeftThumbYAxis = -y;
} else {
gamepad.RightThumbXAxis = x;
gamepad.RightThumbYAxis = -y;
}
virtualGamepad.timestamp = performance.now();
window.BX_EXPOSED.inputChannel?.sendGamepadInput(performance.now(), [this.xCloudGamepad]);
}
/*
@ -223,29 +232,20 @@ export class EmulatedMkbHandler extends MkbHandler {
private vectorLength = (x: number, y: number): number => Math.sqrt(x ** 2 + y ** 2);
private resetGamepad() {
const gamepad = this.getVirtualGamepad();
resetXcloudGamepads() {
const index = getStreamPref(StreamPref.MKB_P1_SLOT) - 1;
// Reset axes
gamepad.axes = [0, 0, 0, 0];
// Reset buttons
for (const button of gamepad.buttons) {
button.pressed = false;
button.value = 0;
}
gamepad.timestamp = performance.now();
this.xCloudGamepad = generateVirtualControllerMapping(0, {
GamepadIndex: getStreamPref(StreamPref.LOCAL_CO_OP_ENABLED) ? index : 0,
Dirty: true,
});
this.VIRTUAL_GAMEPAD.index = index;
}
private pressButton(buttonIndex: GamepadKey, pressed: boolean) {
const virtualGamepad = this.getVirtualGamepad();
const xCloudKey = toXcloudGamepadKey(buttonIndex)!;
if (buttonIndex >= 100) {
let [valueArr, axisIndex] = this.STICK_MAP[buttonIndex]!;
valueArr = valueArr as number[];
axisIndex = axisIndex as number;
let [valueArr]: [GamepadKey[], number] = this.STICK_MAP[buttonIndex]!;
// Remove old index of the array
for (let i = valueArr.length - 1; i >= 0; i--) {
if (valueArr[i] === buttonIndex) {
@ -258,18 +258,19 @@ export class EmulatedMkbHandler extends MkbHandler {
let value;
if (valueArr.length) {
// Get value of the last key of the axis
value = this.STICK_MAP[valueArr[valueArr.length - 1]]![2] as number;
value = this.STICK_MAP[valueArr[valueArr.length - 1]]![1] as number;
} else {
value = 0;
}
virtualGamepad.axes[axisIndex] = value;
// @ts-ignore
this.xCloudGamepad[xCloudKey] = value;
} else {
virtualGamepad.buttons[buttonIndex].pressed = pressed;
virtualGamepad.buttons[buttonIndex].value = pressed ? 1 : 0;
// @ts-ignore
this.xCloudGamepad[xCloudKey] = pressed ? 1 : 0;
}
virtualGamepad.timestamp = performance.now();
window.BX_EXPOSED.inputChannel?.sendGamepadInput(performance.now(), [this.xCloudGamepad]);
}
private onKeyboardEvent = (e: KeyboardEvent) => {
@ -427,7 +428,7 @@ export class EmulatedMkbHandler extends MkbHandler {
return true;
}
toggle(force?: boolean) {
async toggle(force?: boolean) {
if (!this.initialized) {
return;
}
@ -439,7 +440,12 @@ export class EmulatedMkbHandler extends MkbHandler {
}
if (this.enabled) {
document.body.requestPointerLock();
try {
await document.body.requestPointerLock({ unadjustedMovement: true });
} catch (e) {
document.body.requestPointerLock();
console.log(e);
}
} else {
document.pointerLockElement && document.exitPointerLock();
}
@ -447,7 +453,7 @@ export class EmulatedMkbHandler extends MkbHandler {
refreshPresetData() {
this.PRESET = window.BX_STREAM_SETTINGS.mkbPreset;
this.resetGamepad();
this.resetXcloudGamepads();
}
waitForMouseData(showPopup: boolean) {
@ -517,7 +523,7 @@ export class EmulatedMkbHandler extends MkbHandler {
window.addEventListener('keyup', this.onKeyboardEvent);
window.addEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, this.onPollingModeChanged);
window.addEventListener(BxEvent.XCLOUD_DIALOG_SHOWN, this.onDialogShown);
BxEventBus.Script.on('dialog.shown', this.onDialogShown);
if (AppInterface) {
// Android app doesn't support PointerLock API so we need to use a different method
@ -554,7 +560,7 @@ export class EmulatedMkbHandler extends MkbHandler {
this.stop();
this.waitForMouseData(false);
document.pointerLockElement && document.exitPointerLock();
document.exitPointerLock();
window.removeEventListener('keydown', this.onKeyboardEvent);
window.removeEventListener('keyup', this.onKeyboardEvent);
@ -568,18 +574,13 @@ export class EmulatedMkbHandler extends MkbHandler {
}
window.removeEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, this.onPollingModeChanged);
window.removeEventListener(BxEvent.XCLOUD_DIALOG_SHOWN, this.onDialogShown);
BxEventBus.Script.off('dialog.shown', this.onDialogShown);
this.mouseDataProvider?.destroy();
window.removeEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, this.onPollingModeChanged);
}
updateGamepadSlots() {
// Set gamepad slot
this.VIRTUAL_GAMEPAD.index = getPref<number>(PrefKey.MKB_P1_SLOT) - 1;
}
start() {
if (!this.enabled) {
this.enabled = true;
@ -589,8 +590,8 @@ export class EmulatedMkbHandler extends MkbHandler {
this.isPolling = true;
this.escKeyDownTime = -1;
this.resetGamepad();
this.updateGamepadSlots();
window.BX_EXPOSED.toggleLocalCoOp(getStreamPref(StreamPref.LOCAL_CO_OP_ENABLED));
this.resetXcloudGamepads();
window.navigator.getGamepads = this.patchedGetGamepads;
this.waitForMouseData(false);
@ -619,7 +620,7 @@ export class EmulatedMkbHandler extends MkbHandler {
const virtualGamepad = this.getVirtualGamepad();
if (virtualGamepad.connected) {
// Dispatch "gamepaddisconnected" event
this.resetGamepad();
this.resetXcloudGamepads();
virtualGamepad.connected = false;
virtualGamepad.timestamp = performance.now();
@ -639,7 +640,7 @@ export class EmulatedMkbHandler extends MkbHandler {
static setupEvents() {
if (isFullVersion()) {
window.addEventListener(BxEvent.STREAM_PLAYING, () => {
BxEventBus.Stream.on('state.playing', () => {
if (STATES.currentStream.titleInfo?.details.hasMkbSupport) {
// Enable native MKB in Android app
NativeMkbHandler.getInstance()?.init();
@ -649,7 +650,7 @@ export class EmulatedMkbHandler extends MkbHandler {
});
if (EmulatedMkbHandler.isAllowed()) {
window.addEventListener(BxEvent.MKB_UPDATED, () => {
BxEventBus.Stream.on('mkb.setting.updated', () => {
EmulatedMkbHandler.getInstance()?.refreshPresetData();
});
}

View File

@ -1,12 +1,13 @@
import { CE, createButton, ButtonStyle, type BxButtonOptions } from "@/utils/html";
import { t } from "@/utils/translation";
import { BxEvent } from "@/utils/bx-event";
import { ShortcutAction } from "@/enums/shortcut-actions";
import { SettingsDialog } from "../ui/dialog/settings-dialog";
import type { MkbHandler } from "./base-mkb-handler";
import { NativeMkbHandler } from "./native-mkb-handler";
import { StreamSettings } from "@/utils/stream-settings";
import { KeyHelper } from "./key-helper";
import { BxEventBus } from "@/utils/bx-event-bus";
import { BxIcon } from "@/utils/bx-icon";
type MkbPopupType = 'virtual' | 'native';
@ -24,7 +25,7 @@ export class MkbPopup {
constructor() {
this.render();
window.addEventListener(BxEvent.KEYBOARD_SHORTCUTS_UPDATED, e => {
BxEventBus.Stream.on('keyboardShortcuts.updated', () => {
const $newButton = this.createActivateButton();
this.$btnActivate.replaceWith($newButton);
this.$btnActivate = $newButton;
@ -77,7 +78,7 @@ export class MkbPopup {
this.$title = CE('p'),
this.$btnActivate = this.createActivateButton(),
CE('div', {},
CE('div', false,
createButton({
label: t('ignore'),
style: ButtonStyle.GHOST,
@ -90,6 +91,7 @@ export class MkbPopup {
createButton({
label: t('manage'),
icon: BxIcon.MANAGE,
style: ButtonStyle.FOCUSABLE,
onClick: () => {
const dialog = SettingsDialog.getInstance();

View File

@ -1,11 +1,11 @@
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
export class MouseCursorHider {
private static instance: MouseCursorHider | null | undefined;
public static getInstance(): typeof MouseCursorHider['instance'] {
if (typeof MouseCursorHider.instance === 'undefined') {
if (!getPref(PrefKey.MKB_ENABLED) && getPref(PrefKey.MKB_HIDE_IDLE_CURSOR)) {
if (!getGlobalPref(GlobalPref.MKB_ENABLED) && getGlobalPref(GlobalPref.MKB_HIDE_IDLE_CURSOR)) {
MouseCursorHider.instance = new MouseCursorHider();
} else {
MouseCursorHider.instance = null;

View File

@ -4,27 +4,15 @@ import { AppInterface, STATES } from "@/utils/global";
import { MkbHandler } from "./base-mkb-handler";
import { t } from "@/utils/translation";
import { BxEvent } from "@/utils/bx-event";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref, StreamPref } from "@/enums/pref-keys";
import { BxLogger } from "@/utils/bx-logger";
import { MkbPopup } from "./mkb-popup";
import { KeyHelper } from "./key-helper";
import { StreamSettings } from "@/utils/stream-settings";
import { ShortcutAction } from "@/enums/shortcut-actions";
import { NativeMkbMode } from "@/enums/pref-values";
type NativeMouseData = {
X: number,
Y: number,
Buttons: number,
WheelX: number,
WheelY: number,
Type?: 0, // 0: Relative, 1: Absolute
}
type XcloudInputSink = {
onMouseInput: (data: NativeMouseData) => void;
}
import { BxEventBus } from "@/utils/bx-event-bus";
import { getStreamPref, getGlobalPref } from "@/utils/pref-utils";
export class NativeMkbHandler extends MkbHandler {
private static instance: NativeMkbHandler | null | undefined;
@ -42,20 +30,18 @@ export class NativeMkbHandler extends MkbHandler {
private readonly LOG_TAG = 'NativeMkbHandler';
static isAllowed = () => {
return STATES.browser.capabilities.emulatedNativeMkb && getPref<NativeMkbMode>(PrefKey.NATIVE_MKB_MODE) === NativeMkbMode.ON;
return STATES.browser.capabilities.emulatedNativeMkb && getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON;
}
private pointerClient: PointerClient | undefined;
private enabled = false;
private mouseButtonsPressed = 0;
private mouseWheelX = 0;
private mouseWheelY = 0;
private mouseVerticalMultiply = 0;
private mouseHorizontalMultiply = 0;
private inputSink: XcloudInputSink | undefined;
private inputChannel: XcloudInputChannel | undefined;
private popup!: MkbPopup;
@ -100,10 +86,6 @@ export class NativeMkbHandler extends MkbHandler {
this.onKeyboardEvent(event as KeyboardEvent);
break;
case BxEvent.XCLOUD_DIALOG_SHOWN:
this.onDialogShown();
break;
case BxEvent.POINTER_LOCK_REQUESTED:
this.onPointerLockRequested(event);
break;
@ -119,7 +101,7 @@ export class NativeMkbHandler extends MkbHandler {
init() {
this.pointerClient = PointerClient.getInstance();
this.inputSink = window.BX_EXPOSED.inputSink;
this.inputChannel = window.BX_EXPOSED.inputChannel;
// Stop keyboard input at startup
this.updateInputConfigurationAsync(false);
@ -130,15 +112,15 @@ export class NativeMkbHandler extends MkbHandler {
Toast.show('Cannot enable Mouse & Keyboard feature');
}
this.mouseVerticalMultiply = getPref(PrefKey.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY);
this.mouseHorizontalMultiply = getPref(PrefKey.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY);
this.mouseVerticalMultiply = getStreamPref(StreamPref.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY);
this.mouseHorizontalMultiply = getStreamPref(StreamPref.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY);
window.addEventListener('keyup', this);
window.addEventListener(BxEvent.XCLOUD_DIALOG_SHOWN, this);
window.addEventListener(BxEvent.POINTER_LOCK_REQUESTED, this);
window.addEventListener(BxEvent.POINTER_LOCK_EXITED, this);
window.addEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, this);
BxEventBus.Script.on('dialog.shown', this.onDialogShown);
const shortcutKey = StreamSettings.findKeyboardShortcut(ShortcutAction.MKB_TOGGLE);
if (shortcutKey) {
@ -199,13 +181,13 @@ export class NativeMkbHandler extends MkbHandler {
window.removeEventListener('keyup', this);
window.removeEventListener(BxEvent.XCLOUD_DIALOG_SHOWN, this);
window.removeEventListener(BxEvent.POINTER_LOCK_REQUESTED, this);
window.removeEventListener(BxEvent.POINTER_LOCK_EXITED, this);
window.removeEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, this);
BxEventBus.Script.off('dialog.shown', this.onDialogShown);
this.waitForMouseData(false);
document.pointerLockElement && document.exitPointerLock();
document.exitPointerLock();
}
handleMouseMove(data: MkbMouseMove): void {
@ -213,8 +195,8 @@ export class NativeMkbHandler extends MkbHandler {
X: data.movementX,
Y: data.movementY,
Buttons: this.mouseButtonsPressed,
WheelX: this.mouseWheelX,
WheelY: this.mouseWheelY,
WheelX: 0,
WheelY: 0,
});
}
@ -232,30 +214,30 @@ export class NativeMkbHandler extends MkbHandler {
X: 0,
Y: 0,
Buttons: this.mouseButtonsPressed,
WheelX: this.mouseWheelX,
WheelY: this.mouseWheelY,
WheelX: 0,
WheelY: 0,
});
}
handleMouseWheel(data: MkbMouseWheel): boolean {
const { vertical, horizontal } = data;
this.mouseWheelX = horizontal;
let mouseWheelX = horizontal;
if (this.mouseHorizontalMultiply && this.mouseHorizontalMultiply !== 1) {
this.mouseWheelX *= this.mouseHorizontalMultiply;
mouseWheelX *= this.mouseHorizontalMultiply;
}
this.mouseWheelY = vertical;
let mouseWheelY = vertical;
if (this.mouseVerticalMultiply && this.mouseVerticalMultiply !== 1) {
this.mouseWheelY *= this.mouseVerticalMultiply;
mouseWheelY *= this.mouseVerticalMultiply;
}
this.sendMouseInput({
X: 0,
Y: 0,
Buttons: this.mouseButtonsPressed,
WheelX: this.mouseWheelX,
WheelY: this.mouseWheelY,
WheelX: mouseWheelX,
WheelY: mouseWheelY,
});
return true;
@ -279,13 +261,11 @@ export class NativeMkbHandler extends MkbHandler {
private sendMouseInput(data: NativeMouseData) {
data.Type = 0; // Relative
this.inputSink?.onMouseInput(data);
this.inputChannel?.queueMouseInput(data);
}
private resetMouseInput() {
this.mouseButtonsPressed = 0;
this.mouseWheelX = 0;
this.mouseWheelY = 0;
this.sendMouseInput({
X: 0,

View File

@ -8,6 +8,7 @@ enum PointerAction {
BUTTON_RELEASE = 3,
SCROLL = 4,
POINTER_CAPTURE_CHANGED = 5,
PROTOCOL_VERSION = 127,
}
@ -15,6 +16,7 @@ export class PointerClient {
private static instance: PointerClient;
public static getInstance = () => PointerClient.instance ?? (PointerClient.instance = new PointerClient());
private readonly LOG_TAG = 'PointerClient';
private readonly REQUIRED_PROTOCOL_VERSION = 2;
private socket: WebSocket | undefined | null;
private mkbHandler: MkbHandler | undefined;
@ -56,6 +58,15 @@ export class PointerClient {
let messageType = dataView.getInt8(0);
let offset = Int8Array.BYTES_PER_ELEMENT;
switch (messageType) {
case PointerAction.PROTOCOL_VERSION:
const protocolVersion = this.onProtocolVersion(dataView, offset);
BxLogger.info(this.LOG_TAG, 'Protocol version', protocolVersion);
if (protocolVersion !== this.REQUIRED_PROTOCOL_VERSION) {
alert('Required MKB protocol: ' + protocolVersion);
this.stop();
}
break;
case PointerAction.MOVE:
this.onMove(dataView, offset);
break;
@ -75,6 +86,10 @@ export class PointerClient {
});
}
private onProtocolVersion(dataView: DataView, offset: number) {
return dataView.getUint16(offset);
}
onMove(dataView: DataView, offset: number) {
// [X, Y]
const x = dataView.getInt16(offset);

View File

@ -1,22 +1,31 @@
import type { ScriptEvents, StreamEvents } from "@/utils/bx-event-bus";
import type { PatchArray, PatchName, PatchPage } from "./patcher";
export class PatcherUtils {
static indexOf(txt: string, searchString: string, startIndex: number, maxRange: number): number {
static indexOf(txt: string, searchString: string, startIndex: number, maxRange=0, after=false): number {
if (startIndex < 0) {
return -1;
}
const index = txt.indexOf(searchString, startIndex);
if (index < 0 || (maxRange && index - startIndex > maxRange)) {
return -1;
}
return index;
return after ? index + searchString.length : index;
}
static lastIndexOf(txt: string, searchString: string, startIndex: number, maxRange: number): number {
static lastIndexOf(txt: string, searchString: string, startIndex: number, maxRange=0, after=false): number {
if (startIndex < 0) {
return -1;
}
const index = txt.lastIndexOf(searchString, startIndex);
if (index < 0 || (maxRange && startIndex - index > maxRange)) {
return -1;
}
return index;
return after ? index + searchString.length : index;
}
static insertAt(txt: string, index: number, insertString: string): string {
@ -27,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);
}
@ -42,4 +51,57 @@ export class PatcherUtils {
return str;
}
private static isVarCharacter(char: string) {
const code = char.charCodeAt(0);
// Check for uppercase letters (A-Z)
const isUppercase = code >= 65 && code <= 90;
// Check for lowercase letters (a-z)
const isLowercase = code >= 97 && code <= 122;
// Check for digits (0-9)
const isDigit = code >= 48 && code <= 57;
// Check for special characters '_' and '$'
const isSpecial = char === '_' || char === '$';
return isUppercase || isLowercase || isDigit || isSpecial;
}
static getVariableNameBefore(str: string, index: number) {
if (index < 0) {
return null;
}
const end = index;
let start = end - 1;
while (PatcherUtils.isVarCharacter(str[start])) {
start -= 1;
}
return str.substring(start + 1, end);
}
static getVariableNameAfter(str: string, index: number) {
if (index < 0) {
return null;
}
const start = index;
let end = start + 1;
while (PatcherUtils.isVarCharacter(str[end])) {
end += 1;
}
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

@ -1,27 +1,28 @@
import { AppInterface, SCRIPT_VERSION, STATES } from "@utils/global";
import { BX_FLAGS } from "@utils/bx-flags";
import { BxLogger } from "@utils/bx-logger";
import { hashCode, renderString } from "@utils/utils";
import { blockSomeNotifications, hashCode, renderString } from "@utils/utils";
import { BxEvent } from "@/utils/bx-event";
import codeControllerShortcuts from "./patches/controller-shortcuts.js" with { type: "text" };
import codeControllerCustomization from "./patches/controller-customization.js" with { type: "text" };
import codePollGamepad from "./patches/poll-gamepad.js" with { type: "text" };
import codeExposeStreamSession from "./patches/expose-stream-session.js" with { type: "text" };
import codeGameCardIcons from "./patches/game-card-icons.js" with { type: "text" };
import codeLocalCoOpEnable from "./patches/local-co-op-enable.js" with { type: "text" };
import codeSetCurrentlyFocusedInteractable from "./patches/set-currently-focused-interactable.js" with { type: "text" };
import codeRemotePlayEnable from "./patches/remote-play-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 { FeatureGates } from "@/utils/feature-gates.js";
import { PrefKey, StorageKey } from "@/enums/pref-keys.js";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
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";
import { t } from "@/utils/translation";
import { NativeMkbMode, TouchControllerMode, UiLayout, UiSection } from "@/enums/pref-values";
import { BlockFeature, NativeMkbMode, TouchControllerMode, UiLayout, UiSection } from "@/enums/pref-values";
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';
@ -30,11 +31,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;
}
@ -42,6 +39,7 @@ const PATCHES = {
},
// Set disableTelemetry() to true
/*
disableTelemetry(str: string) {
let text = '.disableTelemetry=function(){return!1}';
if (!str.includes(text)) {
@ -50,6 +48,7 @@ const PATCHES = {
return str.replace(text, '.disableTelemetry=function(){return!0}');
},
*/
disableTelemetryProvider(str: string) {
let text = 'this.enableLightweightTelemetry=!';
@ -90,18 +89,18 @@ const PATCHES = {
return false;
}
const layout = getPref<UiLayout>(PrefKey.UI_LAYOUT) === UiLayout.TV ? UiLayout.TV : UiLayout.DEFAULT;
const layout = getGlobalPref(GlobalPref.UI_LAYOUT) === UiLayout.TV ? UiLayout.TV : UiLayout.DEFAULT;
return str.replace(text, `?"${layout}":"${layout}"`);
},
// Replace "/direct-connect" with "/play"
remotePlayDirectConnectUrl(str: string) {
const index = str.indexOf('/direct-connect');
if (index < 0) {
remotePlayPostStreamRedirectUrl(str: string) {
let text = '.RemotePlayRoot.getLink()):';
if (!str.includes(text)) {
return false;
}
return str.replace(str.substring(index - 9, index + 15), 'https://www.xbox.com/play');
str = str.replace(text, '.Home.getLink()):');
return str;
},
remotePlayKeepAlive(str: string) {
@ -122,7 +121,9 @@ const PATCHES = {
return false;
}
return str.replace(text, codeRemotePlayEnable);
const newCode = `connectMode: window.BX_REMOTE_PLAY_CONFIG ? "xhome-connect" : "cloud-connect",
remotePlayServerId: (window.BX_REMOTE_PLAY_CONFIG && window.BX_REMOTE_PLAY_CONFIG.serverId) || '',`;
return str.replace(text, newCode);
},
// Remote Play: Disable achievement toast
@ -132,33 +133,10 @@ const PATCHES = {
return false;
}
const newCode = `if (!!window.BX_REMOTE_PLAY_CONFIG) return;`;
const newCode = `if (window.location.pathname.includes('/consoles/launch/')) return;`;
return str.replace(text, text + newCode);
},
// Remote Play: Prevent adding "Fortnite" to the "Jump back in" list
remotePlayRecentlyUsedTitleIds(str: string) {
let text = '(e.data.recentlyUsedTitleIds)){';
if (!str.includes(text)) {
return false;
}
const newCode = `if (window.BX_REMOTE_PLAY_CONFIG) return;`;
return str.replace(text, text + newCode);
},
// Remote Play: change web page's title
remotePlayWebTitle(str: string) {
let text = 'titleTemplate:void 0,title:';
const index = str.indexOf(text);
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index + text.length, `!!window.BX_REMOTE_PLAY_CONFIG ? "${t('remote-play')} - Better xCloud" :`);
return str;
},
// Block WebRTC stats collector
blockWebRtcStatsCollector(str: string) {
let text = 'this.shouldCollectStats=!0';
@ -188,29 +166,49 @@ const PATCHES = {
str = PatcherUtils.replaceWith(str, setTimeoutIndex, tmp, tmpPatched);
// Block gamepad stats collecting
if (getPref(PrefKey.BLOCK_TRACKING)) {
if (getGlobalPref(GlobalPref.BLOCK_TRACKING)) {
codeBlock = codeBlock.replace('this.inputPollingIntervalStats.addValue', '');
codeBlock = codeBlock.replace('this.inputPollingDurationStats.addValue', '');
}
// Map the Share button on Xbox Series controller with the capturing screenshot feature
const match = codeBlock.match(/this\.gamepadTimestamps\.set\((\w+)\.index/);
if (match) {
const gamepadVar = match[1];
const newCode = renderString(codeControllerShortcuts, {
gamepadVar,
});
codeBlock = codeBlock.replace('this.gamepadTimestamps.set', newCode + 'this.gamepadTimestamps.set');
// Controller shortcuts
let match = codeBlock.match(/this\.gamepadTimestamps\.set\(([A-Za-z0-9_$]+)\.index/);
if (!match) {
return false;
}
let newCode = renderString(codePollGamepad, {
gamepadVar: match[1],
});
codeBlock = codeBlock.replace('this.gamepadTimestamps.set', newCode + 'this.gamepadTimestamps.set');
// Controller customization
match = codeBlock.match(/let ([A-Za-z0-9_$]+)=this\.gamepadMappings\.find/);
if (!match) {
return false;
}
const xCloudGamepadVar = match[1];
const inputFeedbackManager = PatcherUtils.indexOf(codeBlock, 'this.inputFeedbackManager.onGamepadConnected(', 0, 10000);
const backetIndex = PatcherUtils.indexOf(codeBlock, '}', inputFeedbackManager, 100);
if (backetIndex < 0) {
return false;
}
let customizationCode = ';'; // End previous code line
customizationCode += renderString(codeControllerCustomization, { xCloudGamepadVar });
codeBlock = PatcherUtils.insertAt(codeBlock, backetIndex, customizationCode);
str = str.substring(0, index) + codeBlock + str.substring(setTimeoutIndex);
return str;
},
enableXcloudLogger(str: string) {
let text = 'this.telemetryProvider=e}log(e,t,r){';
if (!str.includes(text)) {
let index = str.indexOf('this.telemetryProvider.trackErrorLike');
index > -1 && (index = PatcherUtils.lastIndexOf(str, '}log(', index, 1500));
index > -1 && (index = PatcherUtils.indexOf(str, '{', index, 30, true));
if (index < 0) {
return false;
}
@ -220,7 +218,7 @@ const logFunc = [console.debug, console.log, console.warn, console.error][logLev
logFunc(logTag, '//', logMessage);
`;
str = str.replaceAll(text, text + newCode);
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
@ -245,25 +243,6 @@ logFunc(logTag, '//', logMessage);
return str;
},
// Override website's settings
overrideSettings(str: string) {
const index = str.indexOf(',EnableStreamGate:');
if (index < 0) {
return false;
}
// Find the next "},"
const endIndex = str.indexOf('},', index);
let newSettings = JSON.stringify(FeatureGates);
newSettings = newSettings.substring(1, newSettings.length - 1);
const newCode = newSettings;
str = str.substring(0, endIndex) + ',' + newCode + str.substring(endIndex);
return str;
},
disableGamepadDisconnectedScreen(str: string) {
const index = str.indexOf('"GamepadDisconnected_Title",');
if (index < 0) {
@ -378,9 +357,9 @@ if (window.BX_EXPOSED.stopTakRendering) {
}
let autoOffCode = '';
if (getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF) {
if (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF) {
autoOffCode = 'return;';
} else if (getPref(PrefKey.TOUCH_CONTROLLER_AUTO_OFF)) {
} else if (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_AUTO_OFF)) {
autoOffCode = `
const gamepads = window.navigator.getGamepads();
let gamepadFound = false;
@ -422,24 +401,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 (getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF) {
newCode += 'e.canShowTakHUD = false;';
if (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF) {
newCode += 'options.canShowTakHUD = false;';
}
str = str.replace(text, newCode + text);
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
@ -555,19 +529,19 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
return false;
}
const opacity = (getPref<TouchControllerDefaultOpacity>(PrefKey.TOUCH_CONTROLLER_DEFAULT_OPACITY) / 100).toFixed(1);
const opacity = (getGlobalPref(GlobalPref.TOUCH_CONTROLLER_DEFAULT_OPACITY) / 100).toFixed(1);
const newCode = `opacityMultiplier: ${opacity}`;
str = str.replace(text, newCode);
return str;
},
patchShowSensorControls(str: string) {
let text = '{shouldShowSensorControls:';
let text = ',{shouldShowSensorControls:';
if (!str.includes(text)) {
return false;
}
const newCode = `{shouldShowSensorControls: (window.BX_EXPOSED && window.BX_EXPOSED.shouldShowSensorControls) ||`;
const newCode = `,{shouldShowSensorControls: (window.BX_EXPOSED && window.BX_EXPOSED.shouldShowSensorControls) ||`;
str = str.replace(text, newCode);
return str;
@ -644,15 +618,14 @@ true` + text;
return str;
},
exposeInputSink(str: string) {
let text = 'this.controlChannel=null,this.inputChannel=null';
if (!str.includes(text)) {
exposeInputChannel(str: string) {
let index = str.indexOf('this.flushData=');
if (index < 0) {
return false;
}
const newCode = 'window.BX_EXPOSED.inputSink = this;';
str = str.replace(text, newCode + text);
const newCode = 'window.BX_EXPOSED.inputChannel = this,';
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
@ -715,6 +688,18 @@ true` + text;
return str;
},
// Don't render News section
ignoreNewsSection(str: string) {
let index = str.indexOf('Logger("CarouselRow")');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'const ', index, 200));
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index, 'return null;');
return str;
},
// Don't render "Play With Friends" sections
ignorePlayWithFriendsSection(str: string) {
let index = str.indexOf('location:"PlayWithFriendsRow",');
@ -734,16 +719,8 @@ true` + text;
// Don't render "All Games" sections
ignoreAllGamesSection(str: string) {
let index = str.indexOf('className:"AllGamesRow-module__allGamesRowContainer');
if (index < 0) {
return false;
}
index = PatcherUtils.indexOf(str, 'grid:!0,', index, 1500);
if (index < 0) {
return false;
}
index = PatcherUtils.lastIndexOf(str, '(0,', index, 70);
index > -1 && (index = PatcherUtils.indexOf(str, 'grid:!0,', index, 1500));
index > -1 && (index = PatcherUtils.lastIndexOf(str, '(0,', index, 70));
if (index < 0) {
return false;
}
@ -752,6 +729,18 @@ true` + text;
return str;
},
ignoreByogSection(str: string) {
let index = str.indexOf('"ByogRow-module__container');
index > -1 && (index = PatcherUtils.lastIndexOf(str, 'return', index, 100));
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index, 'return null;');
return str;
},
// home-page.js
ignorePlayWithTouchSection(str: string) {
let index = str.indexOf('("Play_With_Touch"),');
@ -780,12 +769,14 @@ true` + text;
return false;
}
const PREF_HIDE_SECTIONS = getPref<UiSection[]>(PrefKey.UI_HIDE_SECTIONS);
const PREF_HIDE_SECTIONS = getGlobalPref(GlobalPref.UI_HIDE_SECTIONS);
const siglIds: GamePassCloudGallery[] = [];
const sections: PartialRecord<UiSection, GamePassCloudGallery> = {
[UiSection.NATIVE_MKB]: GamePassCloudGallery.NATIVE_MKB,
[UiSection.MOST_POPULAR]: GamePassCloudGallery.MOST_POPULAR,
[UiSection.LEAVING_SOON]: GamePassCloudGallery.LEAVING_SOON,
[UiSection.RECENTLY_ADDED]: GamePassCloudGallery.RECENTLY_ADDED,
};
for (const section of PREF_HIDE_SECTIONS) {
@ -807,6 +798,17 @@ if (e && e.id) {
return str;
},
ignoreGenresSection(str: string) {
let index = str.indexOf('="GenresRow"');
index > -1 && (index = PatcherUtils.lastIndexOf(str, '{', index));
if (index < 0) {
return false;
}
str = PatcherUtils.insertAt(str, index + 1, 'return null;');
return str;
},
// Override Storage.getSettings()
overrideStorageGetSettings(str: string) {
let text = '}getSetting(e){';
@ -844,15 +846,15 @@ if (this.baseStorageKey in window.BX_EXPOSED.overrideSettings) {
return str;
},
// 24225.js#4127, 24.17.11
patchSetCurrentlyFocusedInteractable(str: string) {
let index = str.indexOf('.setCurrentlyFocusedInteractable=(');
// 49851.js#4083, 27.0.4
patchSetCurrentFocus(str: string) {
let index = str.indexOf('.setCurrentFocus=(');
if (index < 0) {
return false;
}
index = str.indexOf('{', index) + 1;
str = str.substring(0, index) + codeSetCurrentlyFocusedInteractable + str.substring(index);
str = PatcherUtils.insertAt(str, index, 'e && BxEvent.dispatch(window, BxEvent.NAVIGATION_FOCUS_CHANGED, { element: e });');
return str;
},
@ -912,20 +914,6 @@ if (this.baseStorageKey in window.BX_EXPOSED.overrideSettings) {
return str;
},
// Optimize Game slug generator by using cached RegEx
optimizeGameSlugGenerator(str: string) {
let text = '/[;,/?:@&=+_`~$%#^*()!^\\u2122\\xae\\xa9]/g';
if (!str.includes(text)) {
return false;
}
str = str.replace(text, 'window.BX_EXPOSED.GameSlugRegexes[0]');
str = str.replace('/ {2,}/g', 'window.BX_EXPOSED.GameSlugRegexes[1]');
str = str.replace('/ /g', 'window.BX_EXPOSED.GameSlugRegexes[2]');
return str;
},
modifyPreloadedState(str: string) {
let text = '=window.__PRELOADED_STATE__;';
if (!str.includes(text)) {
@ -956,86 +944,396 @@ if (this.baseStorageKey in window.BX_EXPOSED.overrideSettings) {
str = str.replace(text, text + 'return;');
return str;
}
};
},
changeNotificationsSubscription(str: string) {
let text = ';buildSubscriptionQueryParamsForNotifications(';
let index = str.indexOf(text);
if (index < 0) {
return false;
}
index += text.length;
// Get parameter name
const subsVar = str[index];
// Find index after {
index = str.indexOf('{', index) + 1;
const blockFeatures = getGlobalPref(GlobalPref.BLOCK_FEATURES);
const filters = [];
if (blockFeatures.includes(BlockFeature.NOTIFICATIONS_INVITES)) {
filters.push('GameInvite', 'PartyInvite');
}
if (blockFeatures.includes(BlockFeature.FRIENDS)) {
filters.push('Follower');
}
if (blockFeatures.includes(BlockFeature.NOTIFICATIONS_ACHIEVEMENTS)) {
filters.push('AchievementUnlock');
}
const newCode = `
let subs = ${subsVar};
subs = subs.filter(val => !${JSON.stringify(filters)}.includes(val));
${subsVar} = subs;
`;
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
exposeReactCreateComponent(str: string) {
let index = str.indexOf('.prototype.isReactComponent={}');
index > -1 && (index = PatcherUtils.indexOf(str, '.createElement=', index));
if (index < 0) {
return false;
}
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;
},
// 27.0.6-hotfix.1, 73704.js
gameCardCustomIcons(str: string) {
let initialIndex = str.indexOf('const{supportedInputIcons:');
if (initialIndex < 0) {
return false;
}
const returnIndex = PatcherUtils.lastIndexOf(str, 'return ', str.indexOf('SupportedInputsBadge'));
if (returnIndex < 0) {
return false;
}
// Find function's parameter
const arrowIndex = PatcherUtils.lastIndexOf(str, '=>{', initialIndex, 300);
if (arrowIndex < 0) {
return false;
}
const paramVar = PatcherUtils.getVariableNameBefore(str, arrowIndex);
// Find supportedInputIcons and title var names
const supportedInputIconsVar = PatcherUtils.getVariableNameAfter(str, PatcherUtils.indexOf(str, 'supportedInputIcons:', initialIndex, 100, true));
if (!paramVar || !supportedInputIconsVar) {
return false;
}
const newCode = renderString(codeGameCardIcons, {
param: paramVar,
supportedInputIcons: supportedInputIconsVar,
});
str = PatcherUtils.insertAt(str, returnIndex, newCode);
return str;
},
/*
// 27.0.6-hotfix.1, 28444.js
gameCardPassTitle(str: string) {
// Pass gameTitle info to gameCardCustomIcons()
let index = str.indexOf('=["productId","showInputBadges","ownershipBadgeType"');
index > -1 && (index = PatcherUtils.indexOf(str, ',gameTitle:', index, 500, true));
if (index < 0) {
return false;
}
const gameTitleVar = PatcherUtils.getVariableNameAfter(str, index);
if (!gameTitleVar) {
return false;
}
index = PatcherUtils.indexOf(str, 'return', index);
index = PatcherUtils.indexOf(str, 'productId:', index);
if (index < 0) {
return false;
}
const newCode = `gameTitle: ${gameTitleVar},`;
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
*/
// 27.0.6-hotfix.1, 78831.js
setImageQuality(str: string) {
let index = str.indexOf('const{size:{width:');
index > -1 && (index = PatcherUtils.indexOf(str, '=new URLSearchParams', index, 500));
if (index < 0) {
return false;
}
const paramVar = PatcherUtils.getVariableNameBefore(str, index);
if (!paramVar) {
return false;
}
// Find "return" keyword
index = PatcherUtils.indexOf(str, 'return', index, 200);
const newCode = `${paramVar}.set('q', ${getGlobalPref(GlobalPref.UI_IMAGE_QUALITY)});`;
str = PatcherUtils.insertAt(str, index, newCode);
return str;
},
setBackgroundImageQuality(str: string) {
let index = str.indexOf('}?w=${');
index > -1 && (index = PatcherUtils.indexOf(str, '}', index + 1, 10, true));
if (index < 0) {
return false;
}
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');
},
patchCustomInputIcon(str: string) {
let index = str.indexOf('.MouseAndKeyboard="MouseAndKeyboard"');
if (index < 0) {
return false;
}
// Get productId
const productIdMatch = /const (\w+)=(\w+)=>{/.exec(str.substring(index, index + 200));
if (!productIdMatch) {
return false;
}
// Define productId variable
str = str.replace(productIdMatch[0], productIdMatch[0] + `const productId = ${productIdMatch[2]};`);
let match = /(\w+)&&(\w+\.push\(\w+\.Touch\))/.exec(str);
if (!match) {
return false;
}
str = str.replace(match[0], `(${match[1]} || window.BX_EXPOSED.hasCustomTouchControl(productId)) && ${match[2]}`);
match = /(\w+)&&(\w+\.push\(\w+\.MouseAndKeyboard\))/.exec(str);
if (match) {
str = str.replace(match[0], `(${match[1]} || window.BX_EXPOSED.hasCustomNativeMkb(productId)) && ${match[2]}`);
}
return str;
},
/*
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 && getPref<NativeMkbMode>(PrefKey.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
...(AppInterface && getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
'enableNativeMkb',
'exposeInputSink',
'disableAbsoluteMouse',
] : []),
] : []) as PatchArray,
'exposeReactCreateComponent',
'injectCreatePortal',
'broadcastPollingMode',
getGlobalPref(GlobalPref.UI_GAME_CARD_SHOW_WAIT_TIME) && 'patchSetCurrentFocus',
'patchGamepadPolling',
'modifyPreloadedState',
'optimizeGameSlugGenerator',
'detectBrowserRouterReady',
'patchRequestInfoCrash',
'disableStreamGate',
'overrideSettings',
'broadcastPollingMode',
'patchGamepadPolling',
'exposeStreamSession',
'supportLocalCoOp',
'disableStreamGate',
'exposeDialogRoutes',
'homePageBeforeLoad',
'productDetailPageBeforeLoad',
...(getGlobalPref(GlobalPref.UI_IMAGE_QUALITY) < 90 ? [
'setImageQuality',
] : []) as PatchArray,
'patchRequestInfoCrash',
'injectErrorPageUseEffect',
'streamPageBeforeLoad',
'injectGuideHomeUseEffect',
'injectAchievementsProgressUseEffect',
'injectAchievementsDetailUseEffect',
'guideAchievementsDefaultLocked',
'injectHeaderUseEffect',
'homePageBeforeLoad',
'patchCustomInputIcon',
'gameCardCustomIcons',
// 'gameCardPassTitle',
'productDetailPageBeforeLoad',
'enableTvRoutes',
'supportLocalCoOp',
'overrideStorageGetSettings',
getPref(PrefKey.UI_GAME_CARD_SHOW_WAIT_TIME) && 'patchSetCurrentlyFocusedInteractable',
getPref<UiLayout>(PrefKey.UI_LAYOUT) !== UiLayout.DEFAULT && 'websiteLayout',
getPref(PrefKey.GAME_FORTNITE_FORCE_CONSOLE) && 'forceFortniteConsole',
getGlobalPref(GlobalPref.UI_LAYOUT) !== UiLayout.DEFAULT && 'websiteLayout',
getGlobalPref(GlobalPref.GAME_FORTNITE_FORCE_CONSOLE) && 'forceFortniteConsole',
...(STATES.userAgent.capabilities.touch ? [
'disableTouchContextMenu',
] : []),
] : []) as PatchArray,
...(getPref(PrefKey.BLOCK_TRACKING) ? [
...(getGlobalPref(GlobalPref.BLOCK_TRACKING) ? [
'disableAiTrack',
'disableTelemetry',
// 'disableTelemetry',
'blockWebRtcStatsCollector',
'disableIndexDbLogging',
'disableTelemetryProvider',
] : []),
] : []) as PatchArray,
...(getPref(PrefKey.REMOTE_PLAY_ENABLED) ? [
...(getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED) ? [
'remotePlayKeepAlive',
'remotePlayDirectConnectUrl',
'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([
getPref<UiSection>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.FRIENDS) && 'ignorePlayWithFriendsSection',
getPref<UiSection>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.ALL_GAMES) && 'ignoreAllGamesSection',
STATES.browser.capabilities.touch && getPref<UiSection>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.TOUCH) && 'ignorePlayWithTouchSection',
(getPref<UiSection>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.NATIVE_MKB) || getPref<UiSection>(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.MOST_POPULAR)) && 'ignoreSiglSections',
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',
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
// TODO: check this
// @ts-ignore
let STREAM_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
'exposeInputChannel',
'patchXcloudTitleInfo',
'disableGamepadDisconnectedScreen',
'patchStreamHud',
@ -1043,44 +1341,45 @@ let STREAM_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
'alwaysShowStreamHud',
'injectStreamMenuUseEffect',
// 'exposeEventTarget',
// Patch volume control for normal stream
getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED) && !getPref(PrefKey.STREAM_COMBINE_SOURCES) && 'patchAudioMediaStream',
getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED) && !getGlobalPref(GlobalPref.STREAM_COMBINE_SOURCES) && 'patchAudioMediaStream',
// Patch volume control for combined audio+video stream
getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED) && getPref(PrefKey.STREAM_COMBINE_SOURCES) && 'patchCombinedAudioVideoMediaStream',
getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED) && getGlobalPref(GlobalPref.STREAM_COMBINE_SOURCES) && 'patchCombinedAudioVideoMediaStream',
// Skip feedback dialog
getPref(PrefKey.UI_DISABLE_FEEDBACK_DIALOG) && 'skipFeedbackDialog',
getGlobalPref(GlobalPref.UI_DISABLE_FEEDBACK_DIALOG) && 'skipFeedbackDialog',
...(STATES.userAgent.capabilities.touch ? [
getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL && 'patchShowSensorControls',
getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL && 'exposeTouchLayoutManager',
(getPref<TouchControllerMode>(PrefKey.TOUCH_CONTROLLER_MODE) === TouchControllerMode.OFF || getPref(PrefKey.TOUCH_CONTROLLER_AUTO_OFF)) && 'disableTakRenderer',
getPref<TouchControllerDefaultOpacity>(PrefKey.TOUCH_CONTROLLER_DEFAULT_OPACITY) !== 100 && 'patchTouchControlDefaultOpacity',
'patchBabylonRendererClass',
] : []),
BX_FLAGS.EnableXcloudLogging && 'enableConsoleLogging',
getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL && 'patchShowSensorControls',
getGlobalPref(GlobalPref.TOUCH_CONTROLLER_MODE) === TouchControllerMode.ALL && 'exposeTouchLayoutManager',
(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,
'patchPollGamepads',
getPref(PrefKey.STREAM_COMBINE_SOURCES) && 'streamCombineSources',
getGlobalPref(GlobalPref.STREAM_COMBINE_SOURCES) && 'streamCombineSources',
...(getPref(PrefKey.REMOTE_PLAY_ENABLED) ? [
...(getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED) ? [
'remotePlayPostStreamRedirectUrl',
'patchRemotePlayMkb',
'remotePlayConnectMode',
] : []),
] : []) as PatchArray,
// Native MKB
...(AppInterface && getPref<NativeMkbMode>(PrefKey.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
...(AppInterface && getGlobalPref(GlobalPref.NATIVE_MKB_MODE) === NativeMkbMode.ON ? [
'patchMouseAndKeyboardEnabled',
'disableNativeRequestPointerLock',
] : []),
] : []) as PatchArray,
]);
let PRODUCT_DETAIL_PAGE_PATCH_ORDERS = PatcherUtils.filterPatches([
AppInterface && 'detectProductDetailPage',
'detectProductDetailPage',
]);
const ALL_PATCHES = [...PATCH_ORDERS, ...HOME_PAGE_PATCH_ORDERS, ...STREAM_PAGE_PATCH_ORDERS, ...PRODUCT_DETAIL_PAGE_PATCH_ORDERS];
@ -1171,6 +1470,7 @@ export class Patcher {
let patchedFuncStr = funcStr;
let modified = false;
const chunkAppliedPatches = [];
for (let patchIndex = 0; patchIndex < patchesToCheck.length; patchIndex++) {
const patchName = patchesToCheck[patchIndex];
@ -1193,18 +1493,21 @@ 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);
} catch (e: unknown) {
@ -1212,6 +1515,7 @@ export class Patcher {
BxLogger.error(LOG_TAG, 'Error', appliedPatches, e.message, patchedFuncStr);
}
}
BX_FLAGS.Debug && console.timeEnd(LOG_TAG);
}
// Save to cache
@ -1272,11 +1576,13 @@ export class PatcherCache {
// Get client.js's hash
let webVersion = '';
const $link = document.querySelector<HTMLLinkElement>('link[data-chunk="client"][href*="/client."]');
const $link = document.querySelector<HTMLLinkElement>('link[data-chunk="client"][as="script"][href*="/client."]');
if ($link) {
const match = /\/client\.([^\.]+)\.js/.exec($link.href);
match && (webVersion = match[1]);
} else {
}
if (!webVersion) {
// Get version from <meta>
// Sometimes this value is missing
webVersion = (document.querySelector<HTMLMetaElement>('meta[name=gamepass-app-version]'))?.content ?? '';

View File

@ -1,99 +0,0 @@
if (window.BX_EXPOSED.disableGamepadPolling) {
this.inputConfiguration.useIntervalWorkerThreadForInput && this.intervalWorker ? this.intervalWorker.scheduleTimer(50) : this.pollGamepadssetTimeoutTimerID = setTimeout(this.pollGamepads, 50);
return;
}
const currentGamepad = ${gamepadVar};
// Share button on XS controller
if (currentGamepad.buttons[17] && currentGamepad.buttons[17].pressed) {
window.dispatchEvent(new Event(BxEvent.CAPTURE_SCREENSHOT));
}
const btnHome = currentGamepad.buttons[16];
if (btnHome) {
if (!this.bxHomeStates) {
this.bxHomeStates = {};
}
let intervalMs = 0;
let hijack = false;
if (btnHome.pressed) {
hijack = true;
intervalMs = 16;
this.gamepadIsIdle.set(currentGamepad.index, false);
if (this.bxHomeStates[currentGamepad.index]) {
const lastTimestamp = this.bxHomeStates[currentGamepad.index].timestamp;
if (currentGamepad.timestamp !== lastTimestamp) {
this.bxHomeStates[currentGamepad.index].timestamp = currentGamepad.timestamp;
const handled = window.BX_EXPOSED.handleControllerShortcut(currentGamepad);
if (handled) {
this.bxHomeStates[currentGamepad.index].shortcutPressed += 1;
}
}
} else {
// First time pressing > save current timestamp
window.BX_EXPOSED.resetControllerShortcut(currentGamepad.index);
this.bxHomeStates[currentGamepad.index] = {
shortcutPressed: 0,
timestamp: currentGamepad.timestamp,
};
}
} else if (this.bxHomeStates[currentGamepad.index]) {
hijack = true;
const info = structuredClone(this.bxHomeStates[currentGamepad.index]);
// Home button released
this.bxHomeStates[currentGamepad.index] = null;
if (info.shortcutPressed === 0) {
const fakeGamepadMappings = [{
GamepadIndex: currentGamepad.index,
A: 0,
B: 0,
X: 0,
Y: 0,
LeftShoulder: 0,
RightShoulder: 0,
LeftTrigger: 0,
RightTrigger: 0,
View: 0,
Menu: 0,
LeftThumb: 0,
RightThumb: 0,
DPadUp: 0,
DPadDown: 0,
DPadLeft: 0,
DPadRight: 0,
Nexus: 1,
LeftThumbXAxis: 0,
LeftThumbYAxis: 0,
RightThumbXAxis: 0,
RightThumbYAxis: 0,
PhysicalPhysicality: 0,
VirtualPhysicality: 0,
Dirty: true,
Virtual: false,
}];
const isLongPress = (currentGamepad.timestamp - info.timestamp) >= 500;
intervalMs = isLongPress ? 500 : 100;
this.inputSink.onGamepadInput(performance.now() - intervalMs, fakeGamepadMappings);
} else {
intervalMs = window.BX_STREAM_SETTINGS.controllerPollingRate;
}
}
if (hijack && intervalMs) {
// Listen to next button press
this.inputConfiguration.useIntervalWorkerThreadForInput && this.intervalWorker ? this.intervalWorker.scheduleTimer(intervalMs) : this.pollGamepadssetTimeoutTimerID = setTimeout(this.pollGamepads, intervalMs);
// Hijack this button
return;
}
}

View File

@ -1,2 +0,0 @@
connectMode: window.BX_REMOTE_PLAY_CONFIG ? "xhome-connect" : "cloud-connect",
remotePlayServerId: (window.BX_REMOTE_PLAY_CONFIG && window.BX_REMOTE_PLAY_CONFIG.serverId) || '',

View File

@ -1,7 +0,0 @@
const msg = JSON.parse(e);
if (msg.reason === 'WarningForBeingIdle' && !window.location.pathname.includes('/launch/')) {
try {
this.sendKeepAlive();
return;
} catch (ex) { console.log(ex); }
}

View File

@ -1 +0,0 @@
e && BxEvent.dispatch(window, BxEvent.NAVIGATION_FOCUS_CHANGED, { element: e });

View File

@ -0,0 +1,167 @@
import { BxEvent as BxEventNamespace } from "@/utils/bx-event";
// "currentGamepad" variable in poll-gamepad.js
declare const currentGamepad: Gamepad;
declare const $xCloudGamepadVar$: XcloudGamepad;
declare const BxEvent: typeof BxEventNamespace;
// Share button on XS controller
const shareButtonPressed = currentGamepad.buttons[17]?.pressed;
let shareButtonHandled = false;
const xCloudGamepad: XcloudGamepad = $xCloudGamepadVar$;
if (currentGamepad.id in window.BX_STREAM_SETTINGS.controllers) {
const controller = window.BX_STREAM_SETTINGS.controllers[currentGamepad.id];
if (controller?.customization) {
const MIN_RANGE = 0.1;
const { mapping, ranges } = controller.customization;
const pressedButtons: PartialRecord<keyof XcloudGamepad, number> = {};
const releasedButtons: PartialRecord<keyof XcloudGamepad, number> = {};
let isModified = false;
// Limit left trigger range
if (ranges.LeftTrigger) {
const [from, to] = ranges.LeftTrigger;
xCloudGamepad.LeftTrigger = xCloudGamepad.LeftTrigger > to ? 1 : xCloudGamepad.LeftTrigger;
xCloudGamepad.LeftTrigger = xCloudGamepad.LeftTrigger < from ? 0 : xCloudGamepad.LeftTrigger;
}
// Limit right trigger range
if (ranges.RightTrigger) {
const [from, to] = ranges.RightTrigger;
xCloudGamepad.RightTrigger = xCloudGamepad.RightTrigger > to ? 1 : xCloudGamepad.RightTrigger;
xCloudGamepad.RightTrigger = xCloudGamepad.RightTrigger < from ? 0 : xCloudGamepad.RightTrigger;
}
// Limit left stick deadzone
if (ranges.LeftThumb) {
const [from, to] = ranges.LeftThumb;
const xAxis = xCloudGamepad.LeftThumbXAxis;
const yAxis = xCloudGamepad.LeftThumbYAxis;
const range = Math.abs(Math.sqrt(xAxis * xAxis + yAxis * yAxis));
let newRange = range > to ? 1 : range;
newRange = newRange < from ? 0 : newRange;
if (newRange !== range) {
xCloudGamepad.LeftThumbXAxis = xAxis * (newRange / range);
xCloudGamepad.LeftThumbYAxis = yAxis * (newRange / range);
}
}
// Limit right stick deadzone
if (ranges.RightThumb) {
const [from, to] = ranges.RightThumb;
const xAxis = xCloudGamepad.RightThumbXAxis;
const yAxis = xCloudGamepad.RightThumbYAxis;
const range = Math.abs(Math.sqrt(xAxis * xAxis + yAxis * yAxis));
let newRange = range > to ? 1 : range;
newRange = newRange < from ? 0 : newRange;
if (newRange !== range) {
xCloudGamepad.RightThumbXAxis = xAxis * (newRange / range);
xCloudGamepad.RightThumbYAxis = yAxis * (newRange / range);
}
}
// Handle the Share button
if (shareButtonPressed && 'Share' in mapping) {
const targetButton = mapping['Share'];
if (typeof targetButton === 'string') {
pressedButtons[targetButton] = 1;
}
// Don't send capturing request
shareButtonHandled = true;
delete mapping['Share'];
}
// Handle other buttons
let key: keyof typeof mapping;
for (key in mapping) {
const mappedKey = mapping[key];
if (key === 'LeftStickAxes' || key === 'RightStickAxes') {
let sourceX: keyof XcloudGamepad;
let sourceY: keyof XcloudGamepad;
let targetX: keyof XcloudGamepad;
let targetY: keyof XcloudGamepad;
if (key === 'LeftStickAxes') {
sourceX = 'LeftThumbXAxis';
sourceY = 'LeftThumbYAxis';
targetX = 'RightThumbXAxis';
targetY = 'RightThumbYAxis';
} else {
sourceX = 'RightThumbXAxis';
sourceY = 'RightThumbYAxis';
targetX = 'LeftThumbXAxis';
targetY = 'LeftThumbYAxis';
}
if (typeof mappedKey === 'string') {
// Calculate moved range
const rangeX = xCloudGamepad[sourceX];
const rangeY = xCloudGamepad[sourceY];
const movedRange = Math.abs(Math.sqrt(rangeX * rangeX + rangeY * rangeY));
const moved = movedRange >= MIN_RANGE;
// Swap sticks
if (moved) {
pressedButtons[targetX] = rangeX;
pressedButtons[targetY] = rangeY;
}
}
// Unbind original stick
releasedButtons[sourceX] = 0;
releasedButtons[sourceY] = 0;
isModified = true;
} else if (typeof mappedKey === 'string') {
let pressed = false;
let value = 0;
if (key === 'LeftTrigger' || key === 'RightTrigger') {
// Only set pressed state when pressing pass max range
const currentRange = xCloudGamepad[key];
if (mappedKey === 'LeftTrigger' || mappedKey === 'RightTrigger') {
pressed = currentRange >= MIN_RANGE;
value = currentRange;
} else {
pressed = true;
value = currentRange >= 0.9 ? 1 : 0;
}
} else if (xCloudGamepad[key]) {
pressed = true;
value = xCloudGamepad[key] as number;
}
if (pressed) {
// Only copy button value when it's being pressed
pressedButtons[mappedKey] = value;
// Unbind original button
releasedButtons[key] = 0;
isModified = true;
}
} else if (mappedKey === false) {
// Disable key
pressedButtons[key] = 0;
isModified = true;
}
}
isModified && Object.assign(xCloudGamepad, releasedButtons, pressedButtons);
}
}
// Capture screenshot when the Share button is pressed
if (shareButtonPressed && !shareButtonHandled) {
window.dispatchEvent(new Event(BxEvent.CAPTURE_SCREENSHOT));
}

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

@ -1,19 +1,23 @@
window.BX_EXPOSED.streamSession = this;
import type { MicrophoneState } from "@/modules/shortcuts/microphone-shortcut";
import { BxEvent as BxEventNamespace } from "@/utils/bx-event";
const orgSetMicrophoneState = this.setMicrophoneState.bind(this);
this.setMicrophoneState = state => {
declare const $this$: any;
declare const BxEvent: typeof BxEventNamespace;
const self = $this$;
window.BX_EXPOSED.streamSession = self;
// Patch setMicrophoneState()
const orgSetMicrophoneState = self.setMicrophoneState.bind(self);
self.setMicrophoneState = (state: MicrophoneState) => {
orgSetMicrophoneState(state);
const evt = new Event(BxEvent.MICROPHONE_STATE_CHANGED);
evt.microphoneState = state;
window.dispatchEvent(evt);
window.BxEventBus.Stream.emit('microphone.state.changed', { state });
};
window.dispatchEvent(new Event(BxEvent.STREAM_SESSION_READY));
// Patch updateDimensions() to make native touch work correctly with WebGL2
let updateDimensionsStr = this.updateDimensions.toString();
let updateDimensionsStr = self.updateDimensions.toString();
if (updateDimensionsStr.startsWith('function ')) {
updateDimensionsStr = updateDimensionsStr.substring(9);
@ -23,7 +27,6 @@ if (updateDimensionsStr.startsWith('function ')) {
const renderTargetVar = updateDimensionsStr.match(/if\((\w+)\){/)[1];
updateDimensionsStr = updateDimensionsStr.replaceAll(renderTargetVar + '.scroll', 'scroll');
updateDimensionsStr = updateDimensionsStr.replace(`if(${renderTargetVar}){`, `
if (${renderTargetVar}) {
const scrollWidth = ${renderTargetVar}.dataset.width ? parseInt(${renderTargetVar}.dataset.width) : ${renderTargetVar}.scrollWidth;

View File

@ -0,0 +1,12 @@
declare const $supportedInputIcons$: Array<any>;
declare const $param$: { productId: string };
const supportedInputIcons = $supportedInputIcons$;
const { productId } = $param$;
// Remove controller icon
supportedInputIcons.shift();
if (window.BX_EXPOSED.localCoOpManager!.isSupported(productId)) {
supportedInputIcons.push(window.BX_EXPOSED.createReactLocalCoOpIcon);
}

View File

@ -1,9 +1,14 @@
import { BxLogger as OrgBxLogger } from "@/utils/bx-logger";
declare const BxLogger: typeof OrgBxLogger;
declare const $this$: any;
// Save the original onGamepadChanged() and onGamepadInput()
this.orgOnGamepadChanged = this.onGamepadChanged;
this.orgOnGamepadInput = this.onGamepadInput;
$this$.orgOnGamepadChanged = $this$.onGamepadChanged;
$this$.orgOnGamepadInput = $this$.onGamepadInput;
let match;
let onGamepadChangedStr = this.onGamepadChanged.toString();
let onGamepadChangedStr = $this$.onGamepadChanged.toString();
// Fix problem with Safari
if (onGamepadChangedStr.startsWith('function ')) {
@ -11,9 +16,9 @@ if (onGamepadChangedStr.startsWith('function ')) {
}
onGamepadChangedStr = onGamepadChangedStr.replaceAll('0', 'arguments[1]');
eval(`this.patchedOnGamepadChanged = function ${onGamepadChangedStr}`);
eval(`$this$.patchedOnGamepadChanged = function ${onGamepadChangedStr}`);
let onGamepadInputStr = this.onGamepadInput.toString();
let onGamepadInputStr = $this$.onGamepadInput.toString();
// Fix problem with Safari
if (onGamepadInputStr.startsWith('function ')) {
onGamepadInputStr = onGamepadInputStr.substring(9);
@ -22,19 +27,19 @@ if (onGamepadInputStr.startsWith('function ')) {
match = onGamepadInputStr.match(/(\w+\.GamepadIndex)/);
if (match) {
const gamepadIndexVar = match[0];
onGamepadInputStr = onGamepadInputStr.replace('this.gamepadStates.get(', `this.gamepadStates.get(${gamepadIndexVar},`);
eval(`this.patchedOnGamepadInput = function ${onGamepadInputStr}`);
onGamepadInputStr = onGamepadInputStr.replace('$this$.gamepadStates.get(', `$this$.gamepadStates.get(${gamepadIndexVar},`);
eval(`$this$.patchedOnGamepadInput = function ${onGamepadInputStr}`);
BxLogger.info('supportLocalCoOp', '✅ Successfully patched local co-op support');
} else {
BxLogger.error('supportLocalCoOp', '❌ Unable to patch local co-op support');
}
// Add method to switch between patched and original methods
this.toggleLocalCoOp = enable => {
$this$.toggleLocalCoOp = (enable: boolean) => {
BxLogger.info('toggleLocalCoOp', enable ? 'Enabled' : 'Disabled');
this.onGamepadChanged = enable ? this.patchedOnGamepadChanged : this.orgOnGamepadChanged;
this.onGamepadInput = enable ? this.patchedOnGamepadInput : this.orgOnGamepadInput;
$this$.onGamepadChanged = enable ? $this$.patchedOnGamepadChanged : $this$.orgOnGamepadChanged;
$this$.onGamepadInput = enable ? $this$.patchedOnGamepadInput : $this$.orgOnGamepadInput;
// Reconnect all gamepads
const gamepads = window.navigator.getGamepads();
@ -48,10 +53,13 @@ this.toggleLocalCoOp = enable => {
continue;
}
// Don't show toast
(gamepad as any)._noToast = true;
window.dispatchEvent(new GamepadEvent('gamepaddisconnected', { gamepad }));
window.dispatchEvent(new GamepadEvent('gamepadconnected', { gamepad }));
}
};
// Expose this method
window.BX_EXPOSED.toggleLocalCoOp = this.toggleLocalCoOp.bind(this);
window.BX_EXPOSED.toggleLocalCoOp = $this$.toggleLocalCoOp.bind(this);

View File

@ -0,0 +1,98 @@
type GamepadManager = {
pollGamepadssetTimeoutTimerID: number;
intervalWorker: any;
pollGamepads(pollGamepads: any, arg1: number): any;
gamepadIsIdle: any;
inputSink: any;
inputConfiguration: any;
bxHomeStates: any;
};
declare const $gamepadVar$: Gamepad;
declare const $this$: GamepadManager;
const self = $this$;
if (window.BX_EXPOSED.disableGamepadPolling) {
self.inputConfiguration.useIntervalWorkerThreadForInput && self.intervalWorker ? self.intervalWorker.scheduleTimer(50) : self.pollGamepadssetTimeoutTimerID = window.setTimeout(self.pollGamepads, 50);
// @ts-ignore
return;
}
const currentGamepad = $gamepadVar$;
const btnHome = currentGamepad.buttons[16];
// Controller shortcuts
if (btnHome) {
if (!self.bxHomeStates) {
self.bxHomeStates = {};
}
let intervalMs = 0;
let hijack = false;
if (btnHome.pressed) {
hijack = true;
intervalMs = 16;
self.gamepadIsIdle.set(currentGamepad.index, false);
if (self.bxHomeStates[currentGamepad.index]) {
const lastTimestamp = self.bxHomeStates[currentGamepad.index].timestamp;
if (currentGamepad.timestamp !== lastTimestamp) {
self.bxHomeStates[currentGamepad.index].timestamp = currentGamepad.timestamp;
const handled = window.BX_EXPOSED.handleControllerShortcut(currentGamepad);
if (handled) {
self.bxHomeStates[currentGamepad.index].shortcutPressed += 1;
}
}
} else {
// First time pressing > save current timestamp
window.BX_EXPOSED.resetControllerShortcut(currentGamepad.index);
self.bxHomeStates[currentGamepad.index] = {
shortcutPressed: 0,
timestamp: currentGamepad.timestamp,
};
}
} else if (self.bxHomeStates[currentGamepad.index]) {
hijack = true;
const info = structuredClone(self.bxHomeStates[currentGamepad.index]);
// Home button released
self.bxHomeStates[currentGamepad.index] = null;
if (info.shortcutPressed === 0) {
const fakeGamepadMappings: XcloudGamepad[] = [{
GamepadIndex: currentGamepad.index,
A: 0, B: 0, X: 0, Y: 0,
LeftShoulder: 0, RightShoulder: 0,
LeftTrigger: 0, RightTrigger: 0,
View: 0, Menu: 0,
LeftThumb: 0, RightThumb: 0,
DPadUp: 0, DPadDown: 0, DPadLeft: 0, DPadRight: 0,
Nexus: 1,
LeftThumbXAxis: 0, LeftThumbYAxis: 0,
RightThumbXAxis: 0, RightThumbYAxis: 0,
PhysicalPhysicality: 0, VirtualPhysicality: 0,
Dirty: true, Virtual: false,
}];
const isLongPress = (currentGamepad.timestamp - info.timestamp) >= 500;
intervalMs = isLongPress ? 500 : 100;
self.inputSink.onGamepadInput(performance.now() - intervalMs, fakeGamepadMappings);
} else {
intervalMs = window.BX_STREAM_SETTINGS.controllerPollingRate;
}
}
if (hijack && intervalMs) {
// Listen to next button press
self.inputConfiguration.useIntervalWorkerThreadForInput && self.intervalWorker ? self.intervalWorker.scheduleTimer(intervalMs) : self.pollGamepadssetTimeoutTimerID = setTimeout(self.pollGamepads, intervalMs);
// Hijack this button
// @ts-ignore
return;
}
}

View File

@ -0,0 +1,11 @@
declare const $this$: any;
declare const e: string;
try {
const msg = JSON.parse(e);
if (msg.reason === 'WarningForBeingIdle' && window.location.pathname.includes('/consoles/launch/')) {
$this$.sendKeepAlive();
// @ts-ignore
return;
}
} catch (ex) { console.log(ex); }

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

@ -0,0 +1,26 @@
declare const e: {
gamepad: Gamepad;
repeat: number;
leftMotorPercent: number;
rightMotorPercent: number;
leftTriggerMotorPercent: number;
rightTriggerMotorPercent: number;
};
if (e?.gamepad?.connected) {
const gamepadSettings = window.BX_STREAM_SETTINGS.controllers[e.gamepad.id];
if (gamepadSettings?.customization) {
const intensity = gamepadSettings.customization.vibrationIntensity;
if (intensity <= 0) {
e.repeat = 0;
// @ts-ignore
return;
} else if (intensity < 1) {
e.leftMotorPercent *= intensity;
e.rightMotorPercent *= intensity;
e.leftTriggerMotorPercent *= intensity;
e.rightTriggerMotorPercent *= intensity;
}
}
}

View File

@ -1,16 +0,0 @@
const gamepad = e.gamepad;
if (gamepad?.connected) {
const gamepadSettings = window.BX_STREAM_SETTINGS.controllers[gamepad.id];
if (gamepadSettings) {
const intensity = gamepadSettings.vibrationIntensity;
if (intensity === 0) {
return void(e.repeat = 0);
} else if (intensity < 1) {
e.leftMotorPercent *= intensity;
e.rightMotorPercent *= intensity;
e.leftTriggerMotorPercent *= intensity;
e.rightTriggerMotorPercent *= intensity;
}
}
}

View File

@ -0,0 +1,119 @@
import { BxLogger } from "@/utils/bx-logger";
import { BaseStreamPlayer, StreamPlayerElement, StreamPlayerFilter } from "./base-stream-player";
import { StreamVideoProcessing, type StreamPlayerType } from "@/enums/pref-values";
export abstract class BaseCanvasPlayer extends BaseStreamPlayer {
protected $canvas: HTMLCanvasElement;
protected targetFps = 60;
protected frameInterval = 0;
protected lastFrameTime = 0;
protected animFrameId: number | null = null;
protected frameCallback: any;
private boundDrawFrame: () => void;
constructor(playerType: StreamPlayerType, $video: HTMLVideoElement, logTag: string) {
super(playerType, StreamPlayerElement.CANVAS, $video, logTag);
const $canvas = document.createElement('canvas');
$canvas.width = $video.videoWidth;
$canvas.height = $video.videoHeight;
this.$canvas = $canvas;
$video.insertAdjacentElement('afterend', this.$canvas);
let frameCallback: any;
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
const $video = this.$video;
frameCallback = $video.requestVideoFrameCallback.bind($video);
} else {
frameCallback = requestAnimationFrame;
}
this.frameCallback = frameCallback;
this.boundDrawFrame = this.drawFrame.bind(this);
}
async init(): Promise<void> {
super.init();
await this.setupShaders();
this.setupRendering();
}
setTargetFps(target: number) {
this.targetFps = target;
this.lastFrameTime = 0;
this.frameInterval = target ? Math.floor(1000 / target) : 0;
}
getCanvas() {
return this.$canvas;
}
destroy() {
BxLogger.info(this.logTag, 'Destroy');
this.isStopped = true;
if (this.animFrameId) {
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
this.$video.cancelVideoFrameCallback(this.animFrameId);
} else {
cancelAnimationFrame(this.animFrameId);
}
this.animFrameId = null;
}
if (this.$canvas.isConnected) {
this.$canvas.remove();
}
this.$canvas.width = 1;
this.$canvas.height = 1;
}
toFilterId(processing: StreamVideoProcessing) {
return processing === StreamVideoProcessing.CAS ? StreamPlayerFilter.CAS : StreamPlayerFilter.USM;
}
protected shouldDraw() {
if (this.targetFps >= 60) {
// Always draw
return true;
} else if (this.targetFps === 0) {
// Don't draw when FPS is 0
return false;
}
const currentTime = performance.now();
const timeSinceLastFrame = currentTime - this.lastFrameTime;
if (timeSinceLastFrame < this.frameInterval) {
// Skip frame to limit FPS
return false;
}
this.lastFrameTime = currentTime;
return true;
}
private drawFrame() {
if (this.isStopped) {
return;
}
this.animFrameId = this.frameCallback(this.boundDrawFrame);
if (!this.shouldDraw()) {
return;
}
this.updateFrame();
}
protected setupRendering(): void {
this.animFrameId = this.frameCallback(this.boundDrawFrame);
}
protected abstract setupShaders(): void;
abstract updateFrame(): void;
}

View File

@ -0,0 +1,48 @@
import { StreamVideoProcessing, type StreamPlayerType } from "@/enums/pref-values";
import type { StreamPlayerOptions } from "@/types/stream";
import { BxLogger } from "@/utils/bx-logger";
export const enum StreamPlayerElement {
VIDEO = 'video',
CANVAS = 'canvas',
}
export const enum StreamPlayerFilter {
USM = 1,
CAS = 2,
}
export abstract class BaseStreamPlayer {
protected logTag: string;
protected playerType: StreamPlayerType;
protected elementType: StreamPlayerElement;
protected $video: HTMLVideoElement;
protected options: StreamPlayerOptions = {
processing: StreamVideoProcessing.USM,
sharpness: 0,
brightness: 1.0,
contrast: 1.0,
saturation: 1.0,
};
protected isStopped = false;
constructor(playerType: StreamPlayerType, elementType: StreamPlayerElement, $video: HTMLVideoElement, logTag: string) {
this.playerType = playerType;
this.elementType = elementType;
this.$video = $video;
this.logTag = logTag;
}
init() {
BxLogger.info(this.logTag, 'Initialize');
}
updateOptions(newOptions: Partial<StreamPlayerOptions>, refresh=false) {
this.options = Object.assign(this.options, newOptions);
refresh && this.refreshPlayer();
}
abstract refreshPlayer(): void;
}

View File

@ -0,0 +1,102 @@
import { CE } from "@/utils/html";
import { BaseStreamPlayer, StreamPlayerElement } from "../base-stream-player";
import { StreamPlayerType, StreamVideoProcessing } from "@/enums/pref-values";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { ScreenshotManager } from "@/utils/screenshot-manager";
export class VideoPlayer extends BaseStreamPlayer {
private $videoCss!: HTMLStyleElement;
private $usmMatrix!: SVGFEConvolveMatrixElement;
constructor($video: HTMLVideoElement, logTag: string) {
super(StreamPlayerType.VIDEO, StreamPlayerElement.VIDEO, $video, logTag);
}
init(): void {
super.init();
// Setup SVG filters
const xmlns = 'http://www.w3.org/2000/svg';
const $svg = CE('svg', {
id: 'bx-video-filters',
class: 'bx-gone',
xmlns,
},
CE('defs', { xmlns: 'http://www.w3.org/2000/svg' },
CE('filter', {
id: 'bx-filter-usm',
xmlns,
}, this.$usmMatrix = CE('feConvolveMatrix', {
id: 'bx-filter-usm-matrix',
order: '3',
xmlns,
}) as unknown as SVGFEConvolveMatrixElement),
),
);
this.$videoCss = CE('style', { id: 'bx-video-css' });
const $fragment = document.createDocumentFragment();
$fragment.append(this.$videoCss, $svg);
document.documentElement.appendChild($fragment);
}
protected setupRendering(): void {}
forceDrawFrame(): void {}
updateCanvas(): void {}
refreshPlayer() {
let filters = this.getVideoPlayerFilterStyle();
let videoCss = '';
if (filters) {
videoCss += `filter: ${filters} !important;`;
}
// Apply video filters to screenshots
if (getGlobalPref(GlobalPref.SCREENSHOT_APPLY_FILTERS)) {
ScreenshotManager.getInstance().updateCanvasFilters(filters);
}
let css = '';
if (videoCss) {
css = `#game-stream video { ${videoCss} }`;
}
this.$videoCss.textContent = css;
}
clearFilters() {
this.$videoCss.textContent = '';
}
private getVideoPlayerFilterStyle() {
const filters = [];
const sharpness = this.options.sharpness || 0;
if (this.options.processing === StreamVideoProcessing.USM && sharpness != 0) {
const level = (7 - ((sharpness / 2) - 1) * 0.5).toFixed(1); // 5, 5.5, 6, 6.5, 7
const matrix = `0 -1 0 -1 ${level} -1 0 -1 0`;
this.$usmMatrix?.setAttributeNS(null, 'kernelMatrix', matrix);
filters.push(`url(#bx-filter-usm)`);
}
const saturation = this.options.saturation || 100;
if (saturation != 100) {
filters.push(`saturate(${saturation}%)`);
}
const contrast = this.options.contrast || 100;
if (contrast != 100) {
filters.push(`contrast(${contrast}%)`);
}
const brightness = this.options.brightness || 100;
if (brightness != 100) {
filters.push(`brightness(${brightness}%)`);
}
return filters.join(' ');
}
}

View File

@ -1,268 +0,0 @@
import vertClarityBoost from "./shaders/clarity_boost.vert" with { type: "text" };
import fsClarityBoost from "./shaders/clarity_boost.fs" with { type: "text" };
import { BxLogger } from "@/utils/bx-logger";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
export class WebGL2Player {
private readonly LOG_TAG = 'WebGL2Player';
private $video: HTMLVideoElement;
private $canvas: HTMLCanvasElement;
private gl: WebGL2RenderingContext | null = null;
private resources: Array<any> = [];
private program: WebGLProgram | null = null;
private stopped: boolean = false;
private options = {
filterId: 1,
sharpenFactor: 0,
brightness: 0.0,
contrast: 0.0,
saturation: 0.0,
};
private targetFps = 60;
private frameInterval = 0;
private lastFrameTime = 0;
private animFrameId: number | null = null;
constructor($video: HTMLVideoElement) {
BxLogger.info(this.LOG_TAG, 'Initialize');
this.$video = $video;
const $canvas = document.createElement('canvas');
$canvas.width = $video.videoWidth;
$canvas.height = $video.videoHeight;
this.$canvas = $canvas;
this.setupShaders();
this.setupRendering();
$video.insertAdjacentElement('afterend', $canvas);
}
setFilter(filterId: number, update = true) {
this.options.filterId = filterId;
update && this.updateCanvas();
}
setSharpness(sharpness: number, update = true) {
this.options.sharpenFactor = sharpness;
update && this.updateCanvas();
}
setBrightness(brightness: number, update = true) {
this.options.brightness = 1 + (brightness - 100) / 100;
update && this.updateCanvas();
}
setContrast(contrast: number, update = true) {
this.options.contrast = 1 + (contrast - 100) / 100;
update && this.updateCanvas();
}
setSaturation(saturation: number, update = true) {
this.options.saturation = 1 + (saturation - 100) / 100;
update && this.updateCanvas();
}
setTargetFps(target: number) {
this.targetFps = target;
this.lastFrameTime = 0;
this.frameInterval = target ? Math.floor(1000 / target) : 0;
}
getCanvas() {
return this.$canvas;
}
updateCanvas() {
const gl = this.gl!;
const program = this.program!;
gl.uniform2f(gl.getUniformLocation(program, 'iResolution'), this.$canvas.width, this.$canvas.height);
gl.uniform1i(gl.getUniformLocation(program, 'filterId'), this.options.filterId);
gl.uniform1f(gl.getUniformLocation(program, 'sharpenFactor'), this.options.sharpenFactor);
gl.uniform1f(gl.getUniformLocation(program, 'brightness'), this.options.brightness);
gl.uniform1f(gl.getUniformLocation(program, 'contrast'), this.options.contrast);
gl.uniform1f(gl.getUniformLocation(program, 'saturation'), this.options.saturation);
}
forceDrawFrame() {
const gl = this.gl!;
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, this.$video);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
private setupRendering() {
let frameCallback: any;
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
const $video = this.$video;
frameCallback = $video.requestVideoFrameCallback.bind($video);
} else {
frameCallback = requestAnimationFrame;
}
let animate = () => {
if (this.stopped) {
return;
}
this.animFrameId = frameCallback(animate);
let draw = true;
// Don't draw when FPS is 0
if (this.targetFps === 0) {
draw = false;
} else if (this.targetFps < 60) {
// Limit FPS
const currentTime = performance.now();
const timeSinceLastFrame = currentTime - this.lastFrameTime;
if (timeSinceLastFrame < this.frameInterval) {
draw = false;
} else {
this.lastFrameTime = currentTime;
}
}
if (draw) {
const gl = this.gl!;
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, this.$video);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
}
this.animFrameId = frameCallback(animate);
}
private setupShaders() {
BxLogger.info(this.LOG_TAG, 'Setting up', getPref(PrefKey.VIDEO_POWER_PREFERENCE));
const gl = this.$canvas.getContext('webgl2', {
isBx: true,
antialias: true,
alpha: false,
powerPreference: getPref(PrefKey.VIDEO_POWER_PREFERENCE),
}) as WebGL2RenderingContext;
this.gl = gl;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferWidth);
// Vertex shader: Identity map
const vShader = gl.createShader(gl.VERTEX_SHADER)!;
gl.shaderSource(vShader, vertClarityBoost);
gl.compileShader(vShader);
const fShader = gl.createShader(gl.FRAGMENT_SHADER)!;
gl.shaderSource(fShader, fsClarityBoost);
gl.compileShader(fShader);
// Create and link program
const program = gl.createProgram()!;
this.program = program;
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
gl.useProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error(`Link failed: ${gl.getProgramInfoLog(program)}`);
console.error(`vs info-log: ${gl.getShaderInfoLog(vShader)}`);
console.error(`fs info-log: ${gl.getShaderInfoLog(fShader)}`);
}
this.updateCanvas();
// Vertices: A screen-filling quad made from two triangles
const buffer = gl.createBuffer();
this.resources.push(buffer);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
// Texture to contain the video data
const texture = gl.createTexture();
this.resources.push(texture);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Bind texture to the "data" argument to the fragment shader
gl.uniform1i(gl.getUniformLocation(program, 'data'), 0);
gl.activeTexture(gl.TEXTURE0);
// gl.bindTexture(gl.TEXTURE_2D, texture);
}
resume() {
this.stop();
this.stopped = false;
BxLogger.info(this.LOG_TAG, 'Resume');
this.$canvas.classList.remove('bx-gone');
this.setupRendering();
}
stop() {
BxLogger.info(this.LOG_TAG, 'Stop');
this.$canvas.classList.add('bx-gone');
this.stopped = true;
if (this.animFrameId) {
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
this.$video.cancelVideoFrameCallback(this.animFrameId);
} else {
cancelAnimationFrame(this.animFrameId);
}
this.animFrameId = null;
}
}
destroy() {
BxLogger.info(this.LOG_TAG, 'Destroy');
this.stop();
const gl = this.gl;
if (gl) {
gl.getExtension('WEBGL_lose_context')?.loseContext();
gl.useProgram(null);
for (const resource of this.resources) {
if (resource instanceof WebGLProgram) {
gl.deleteProgram(resource);
} else if (resource instanceof WebGLShader) {
gl.deleteShader(resource);
} else if (resource instanceof WebGLTexture) {
gl.deleteTexture(resource);
} else if (resource instanceof WebGLBuffer) {
gl.deleteBuffer(resource);
}
}
this.gl = null;
}
if (this.$canvas.isConnected) {
this.$canvas.parentElement?.removeChild(this.$canvas);
}
this.$canvas.width = 1;
this.$canvas.height = 1;
}
}

View File

@ -10,8 +10,8 @@ const int FILTER_UNSHARP_MASKING = 1;
// constrast = 0.8
const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
// Luminosity factor
const vec3 LUMINOSITY_FACTOR = vec3(0.2126, 0.7152, 0.0722);
// Luminosity factor: https://www.w3.org/TR/AERT/#color-contrast
const vec3 LUMINOSITY_FACTOR = vec3(0.299, 0.587, 0.114);
uniform int filterId;
uniform float sharpenFactor;

View File

@ -0,0 +1,141 @@
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";
import { StreamPlayerType } from "@/enums/pref-values";
export class WebGL2Player extends BaseCanvasPlayer {
private gl: WebGL2RenderingContext | null = null;
private resources: Array<WebGLBuffer | WebGLTexture | WebGLProgram | WebGLShader> = [];
private program: WebGLProgram | null = null;
constructor($video: HTMLVideoElement) {
super(StreamPlayerType.WEBGL2, $video, 'WebGL2Player');
}
private updateCanvas() {
console.log('updateCanvas', this.options);
const gl = this.gl!;
const program = this.program!;
const filterId = this.toFilterId(this.options.processing);
gl.uniform2f(gl.getUniformLocation(program, 'iResolution'), this.$canvas.width, this.$canvas.height);
gl.uniform1i(gl.getUniformLocation(program, 'filterId'), filterId);
gl.uniform1f(gl.getUniformLocation(program, 'sharpenFactor'), this.options.sharpness);
gl.uniform1f(gl.getUniformLocation(program, 'brightness'), this.options.brightness / 100);
gl.uniform1f(gl.getUniformLocation(program, 'contrast'), this.options.contrast / 100);
gl.uniform1f(gl.getUniformLocation(program, 'saturation'), this.options.saturation / 100);
}
updateFrame() {
const gl = this.gl!;
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, this.$video);
gl.drawArrays(gl.TRIANGLES, 0, 3);
}
protected async setupShaders(): Promise<void> {
const gl = this.$canvas.getContext('webgl2', {
isBx: true,
antialias: true,
alpha: false,
depth: false,
preserveDrawingBuffer: false,
stencil: false,
powerPreference: getStreamPref(StreamPref.VIDEO_POWER_PREFERENCE),
} as WebGLContextAttributes) as WebGL2RenderingContext;
this.gl = gl;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferWidth);
// Vertex shader: Identity map
const vShader = gl.createShader(gl.VERTEX_SHADER)!;
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, compressCodeFile('./src/modules/player/webgl2/shaders/clarity-boost.fs') as any as string);
gl.compileShader(fShader);
// Create and link program
const program = gl.createProgram()!;
this.program = program;
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
gl.useProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error(`Link failed: ${gl.getProgramInfoLog(program)}`);
console.error(`vs info-log: ${gl.getShaderInfoLog(vShader)}`);
console.error(`fs info-log: ${gl.getShaderInfoLog(fShader)}`);
}
this.updateCanvas();
// Vertices: A screen-filling quad made from two triangles
const buffer = gl.createBuffer();
this.resources.push(buffer);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
-1.0, -1.0, // Bottom-left
3.0, -1.0, // Bottom-right
-1.0, 3.0, // Top-left
]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
// Texture to contain the video data
const texture = gl.createTexture();
this.resources.push(texture);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
// Bind texture to the "data" argument to the fragment shader
gl.uniform1i(gl.getUniformLocation(program, 'data'), 0);
gl.activeTexture(gl.TEXTURE0);
// gl.bindTexture(gl.TEXTURE_2D, texture);
}
destroy() {
super.destroy();
const gl = this.gl;
if (!gl) {
return;
}
gl.getExtension('WEBGL_lose_context')?.loseContext();
gl.useProgram(null);
for (const resource of this.resources) {
if (resource instanceof WebGLProgram) {
gl.deleteProgram(resource);
} else if (resource instanceof WebGLShader) {
gl.deleteShader(resource);
} else if (resource instanceof WebGLTexture) {
gl.deleteTexture(resource);
} else if (resource instanceof WebGLBuffer) {
gl.deleteBuffer(resource);
}
}
this.gl = null;
}
refreshPlayer(): void {
this.updateCanvas();
}
}

View File

@ -0,0 +1,93 @@
struct Params {
filterId: f32,
sharpness: f32,
brightness: f32,
contrast: f32,
saturation: f32,
};
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@location(0) uv: vec2<f32>,
};
@group(0) @binding(0) var ourSampler: sampler;
@group(0) @binding(1) var ourTexture: texture_external;
@group(0) @binding(2) var<uniform> ourParams: Params;
const FILTER_UNSHARP_MASKING: f32 = 1.0;
const CAS_CONTRAST_PEAK: f32 = 0.8 * -3.0 + 8.0;
// Luminosity factor: https://www.w3.org/TR/AERT/#color-contrast
const LUMINOSITY_FACTOR = vec3(0.299, 0.587, 0.114);
@vertex
fn vsMain(@location(0) pos: vec2<f32>) -> VertexOutput {
var out: VertexOutput;
out.position = vec4(pos, 0.0, 1.0);
// Flip the Y-coordinate of UVs
out.uv = (vec2(pos.x, 1.0 - (pos.y + 1.0)) + vec2(1.0, 1.0)) * 0.5;
return out;
}
fn clarityBoost(coord: vec2<f32>, texSize: vec2<f32>, e: vec3<f32>) -> vec3<f32> {
let texelSize = 1.0 / texSize;
// Load 3x3 neighborhood samples
let a = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2(-1.0, 1.0)).rgb;
let b = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2( 0.0, 1.0)).rgb;
let c = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2( 1.0, 1.0)).rgb;
let d = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2(-1.0, 0.0)).rgb;
let f = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2( 1.0, 0.0)).rgb;
let g = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2(-1.0, -1.0)).rgb;
let h = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2( 0.0, -1.0)).rgb;
let i = textureSampleBaseClampToEdge(ourTexture, ourSampler, coord + texelSize * vec2( 1.0, -1.0)).rgb;
// Unsharp Masking (USM)
if ourParams.filterId == FILTER_UNSHARP_MASKING {
let gaussianBlur = (a + c + g + i) * 1.0 + (b + d + f + h) * 2.0 + e * 4.0;
let blurred = gaussianBlur / 16.0;
return e + (e - blurred) * (ourParams.sharpness / 3.0);
}
// Contrast Adaptive Sharpening (CAS)
let minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
let maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
let reciprocalMaxRgb = 1.0 / maxRgb;
var amplifyRgb = clamp(min(minRgb, 2.0 - maxRgb) * reciprocalMaxRgb, vec3(0.0), vec3(1.0));
amplifyRgb = 1.0 / sqrt(amplifyRgb);
let weightRgb = -(1.0 / (amplifyRgb * CAS_CONTRAST_PEAK));
let reciprocalWeightRgb = 1.0 / (4.0 * weightRgb + 1.0);
let window = b + d + f + h;
let outColor = clamp((window * weightRgb + e) * reciprocalWeightRgb, vec3(0.0), vec3(1.0));
return mix(e, outColor, ourParams.sharpness / 2.0);
}
@fragment
fn fsMain(input: VertexOutput) -> @location(0) vec4<f32> {
let texSize = vec2<f32>(textureDimensions(ourTexture));
let center = textureSampleBaseClampToEdge(ourTexture, ourSampler, input.uv);
var adjustedRgb = clarityBoost(input.uv, texSize, center.rgb);
// Compute grayscale intensity
let gray = dot(adjustedRgb, LUMINOSITY_FACTOR);
// Interpolate between grayscale and color
adjustedRgb = mix(vec3(gray), adjustedRgb, ourParams.saturation);
// Adjust contrast
adjustedRgb = (adjustedRgb - 0.5) * ourParams.contrast + 0.5;
// Adjust brightness
adjustedRgb *= ourParams.brightness;
return vec4(adjustedRgb, 1.0);
}

View File

@ -0,0 +1,188 @@
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";
import { BX_FLAGS } from "@/utils/bx-flags";
export class WebGPUPlayer extends BaseCanvasPlayer {
static device: GPUDevice;
context!: GPUCanvasContext | null;
pipeline!: GPURenderPipeline | null;
sampler!: GPUSampler | null;
bindGroup!: GPUBindGroup | null;
optionsUpdated: boolean = false;
paramsBuffer!: GPUBuffer | null;
vertexBuffer!: GPUBuffer | null;
static async prepare(): Promise<void> {
if (!BX_FLAGS.EnableWebGPURenderer || !navigator.gpu) {
BxEventBus.Script.emit('webgpu.ready', {});
return;
}
try {
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
WebGPUPlayer.device = await adapter.requestDevice();
WebGPUPlayer.device?.addEventListener('uncapturederror', e => {
console.error((e as GPUUncapturedErrorEvent).error.message);
});
}
} catch (ex) {
alert(ex);
}
BxEventBus.Script.emit('webgpu.ready', {});
}
constructor($video: HTMLVideoElement) {
super(StreamPlayerType.WEBGPU, $video, 'WebGPUPlayer');
}
protected setupShaders(): void {
this.context = this.$canvas.getContext('webgpu')!;
if (!this.context) {
alert('Can\'t initiate context');
return;
}
const format = navigator.gpu.getPreferredCanvasFormat();
this.context.configure({
device: WebGPUPlayer.device,
format,
alphaMode: 'opaque',
});
this.vertexBuffer = WebGPUPlayer.device.createBuffer({
label: 'vertex buffer',
size: 6 * 4, // 6 floats (2 per vertex)
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true,
});
const mappedRange = this.vertexBuffer.getMappedRange();
new Float32Array(mappedRange).set([
-1, 3, // Vertex 1
-1, -1, // Vertex 2
3, -1, // Vertex 3
]);
this.vertexBuffer.unmap();
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: {
module: shaderModule,
entryPoint: 'vsMain',
buffers: [{
arrayStride: 8,
attributes: [{
format: 'float32x2',
offset: 0,
shaderLocation: 0,
}],
}],
},
fragment: {
module: shaderModule,
entryPoint: 'fsMain',
targets: [{ format }],
},
primitive: { topology: 'triangle-list' },
});
this.sampler = WebGPUPlayer.device.createSampler({ magFilter: 'linear', minFilter: 'linear' });
this.updateCanvas();
}
private prepareUniformBuffer(value: any, classType: any) {
const uniform = new classType(value);
const uniformBuffer = WebGPUPlayer.device.createBuffer({
size: uniform.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
WebGPUPlayer.device.queue.writeBuffer(uniformBuffer, 0, uniform);
return uniformBuffer;
}
private updateCanvas() {
const externalTexture = WebGPUPlayer.device.importExternalTexture({ source: this.$video });
if (!this.optionsUpdated) {
this.paramsBuffer = this.prepareUniformBuffer([
this.toFilterId(this.options.processing),
this.options.sharpness,
this.options.brightness / 100,
this.options.contrast / 100,
this.options.saturation / 100,
], Float32Array);
this.optionsUpdated = true;
}
this.bindGroup = WebGPUPlayer.device.createBindGroup({
layout: this.pipeline!.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: this.sampler },
{ binding: 1, resource: externalTexture as any },
{ binding: 2, resource: { buffer: this.paramsBuffer } },
],
});
}
updateFrame(): void {
this.updateCanvas();
const commandEncoder = WebGPUPlayer.device.createCommandEncoder();
const passEncoder = commandEncoder.beginRenderPass({
colorAttachments: [{
view: this.context!.getCurrentTexture().createView(),
loadOp: 'clear',
storeOp: 'store',
clearValue: [0.0, 0.0, 0.0, 1.0],
}]
});
passEncoder.setPipeline(this.pipeline!);
passEncoder.setBindGroup(0, this.bindGroup);
passEncoder.setVertexBuffer(0, this.vertexBuffer);
passEncoder.draw(3);
passEncoder.end();
WebGPUPlayer.device.queue.submit([commandEncoder.finish()]);
}
refreshPlayer(): void {
this.optionsUpdated = false;
this.updateCanvas();
}
destroy(): void {
super.destroy();
this.isStopped = true;
// Unset GPU resources
this.pipeline = null;
this.bindGroup = null;
this.sampler = null;
this.paramsBuffer?.destroy();
this.paramsBuffer = null;
this.vertexBuffer?.destroy();
this.vertexBuffer = null;
// Reset the WebGPU context (force garbage collection)
if (this.context) {
this.context.unconfigure();
this.context = null;
}
console.log('WebGPU context successfully freed.');
}
}

View File

@ -5,8 +5,8 @@ import { t } from "@utils/translation";
import { localRedirect } from "@modules/ui/ui";
import { BxLogger } from "@utils/bx-logger";
import { HeaderSection } from "./ui/header";
import { PrefKey } from "@/enums/pref-keys";
import { getPref, setPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref, setGlobalPref } from "@/utils/pref-utils";
import { RemotePlayDialog } from "./ui/dialog/remote-play-dialog";
export const enum RemotePlayConsoleState {
@ -37,7 +37,7 @@ export class RemotePlayManager {
private static instance: RemotePlayManager | null | undefined;
public static getInstance(): typeof RemotePlayManager['instance'] {
if (typeof RemotePlayManager.instance === 'undefined') {
if (getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
if (getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED)) {
RemotePlayManager.instance = new RemotePlayManager();
} else {
RemotePlayManager.instance = null;
@ -156,6 +156,11 @@ export class RemotePlayManager {
},
};
// Start with "isDefault" = true first
this.regions.sort((a: RemotePlayRegion, b: RemotePlayRegion) => {
return a.isDefault ? -1 : 0;
})
// Test servers one by one
for (const region of this.regions) {
try {
@ -186,7 +191,7 @@ export class RemotePlayManager {
play(serverId: string, resolution?: string) {
if (resolution) {
setPref(PrefKey.REMOTE_PLAY_STREAM_RESOLUTION, resolution);
setGlobalPref(GlobalPref.REMOTE_PLAY_STREAM_RESOLUTION, resolution, 'ui');
}
STATES.remotePlay.config = {
@ -195,6 +200,7 @@ export class RemotePlayManager {
window.BX_REMOTE_PLAY_CONFIG = STATES.remotePlay.config;
localRedirect('/launch/fortnite/BT5P2X999VH2#remote-play');
setTimeout(() => localRedirect('/consoles/launch/' + serverId), 100);
}
togglePopup(force = null) {
@ -221,7 +227,7 @@ export class RemotePlayManager {
}
static detect() {
if (!getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
if (!getGlobalPref(GlobalPref.REMOTE_PLAY_ENABLED)) {
return;
}

View File

@ -0,0 +1,352 @@
import { GlobalPref, StreamPref, type AnyPref } from "@/enums/pref-keys";
import { limitVideoPlayerFps, onChangeVideoPlayerType, updateVideoPlayer } from "./stream/stream-settings-utils";
import { StreamStats } from "./stream/stream-stats";
import { SoundShortcut } from "./shortcuts/sound-shortcut";
import { STATES } from "@/utils/global";
import { getGamePref, getStreamPref, hasGamePref, isStreamPref, setGameIdPref, STORAGE } from "@/utils/pref-utils";
import { BxExposed } from "@/utils/bx-exposed";
import { StreamSettings } from "@/utils/stream-settings";
import { NativeMkbHandler } from "./mkb/native-mkb-handler";
import { BxEventBus } from "@/utils/bx-event-bus";
import { SettingElement } from "@/utils/setting-element";
import { CE } from "@/utils/html";
import { t } from "@/utils/translation";
import { BxSelectElement } from "@/web-components/bx-select";
import { XboxApi } from "@/utils/xbox-api";
import { EmulatedMkbHandler } from "./mkb/mkb-handler";
type SettingType = Partial<{
hidden: true;
onChange: () => void;
onChangeUi: () => void;
$element: HTMLElement;
}>;
export class SettingsManager {
private static instance: SettingsManager;
public static getInstance = () => SettingsManager.instance ?? (SettingsManager.instance = new SettingsManager());
private $streamSettingsSelection!: HTMLElement;
private $tips!: HTMLElement;
private playingGameId: number = -1;
private targetGameId: number = -1;
// @ts-ignore
private SETTINGS: Record<GlobalPref | StreamPref, SettingType> = {
// [GlobalPref.VERSION_LATEST]: { hidden: true },
// [GlobalPref.VERSION_LAST_CHECK]: { hidden: true },
// [GlobalPref.VERSION_CURRENT]: { hidden: true },
[StreamPref.LOCAL_CO_OP_ENABLED]: {
onChange: () => {
BxExposed.toggleLocalCoOp(getStreamPref(StreamPref.LOCAL_CO_OP_ENABLED));
},
},
[StreamPref.DEVICE_VIBRATION_MODE]: {
onChange: StreamSettings.refreshControllerSettings,
},
[StreamPref.DEVICE_VIBRATION_INTENSITY]: {
onChange: StreamSettings.refreshControllerSettings,
},
[StreamPref.CONTROLLER_POLLING_RATE]: {
onChange: StreamSettings.refreshControllerSettings,
},
[StreamPref.CONTROLLER_SETTINGS]: {
onChange: StreamSettings.refreshControllerSettings,
},
[StreamPref.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY]: {
onChange: () => {
const value = getStreamPref(StreamPref.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY);
NativeMkbHandler.getInstance()?.setHorizontalScrollMultiplier(value / 100);
},
},
[StreamPref.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY]: {
onChange: () => {
const value = getStreamPref(StreamPref.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY);
NativeMkbHandler.getInstance()?.setVerticalScrollMultiplier(value / 100);
},
},
[StreamPref.VIDEO_PLAYER_TYPE]: {
onChange: updateVideoPlayer,
onChangeUi: onChangeVideoPlayerType,
},
[StreamPref.VIDEO_POWER_PREFERENCE]: {
onChange: () => {
const streamPlayer = STATES.currentStream.streamPlayerManager;
if (!streamPlayer) {
return;
}
updateVideoPlayer();
},
},
[StreamPref.VIDEO_PROCESSING]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_SHARPNESS]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_MAX_FPS]: {
onChange: () => {
const value = getStreamPref(StreamPref.VIDEO_MAX_FPS);
limitVideoPlayerFps(value);
},
},
[StreamPref.VIDEO_RATIO]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_BRIGHTNESS]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_CONTRAST]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_SATURATION]: {
onChange: updateVideoPlayer,
},
[StreamPref.VIDEO_POSITION]: {
onChange: updateVideoPlayer,
},
[StreamPref.AUDIO_VOLUME]: {
onChange: () => {
const value = getStreamPref(StreamPref.AUDIO_VOLUME);
SoundShortcut.setGainNodeVolume(value);
},
},
[StreamPref.STATS_ITEMS]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.STATS_QUICK_GLANCE_ENABLED]: {
onChange: () => {
const value = getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED);
if (!value) {
StreamStats.getInstance().stop(true);
}
},
},
[StreamPref.STATS_POSITION]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.STATS_TEXT_SIZE]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.STATS_OPACITY_ALL]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.STATS_OPACITY_BACKGROUND]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.STATS_CONDITIONAL_FORMATTING]: {
onChange: StreamStats.refreshStyles,
},
[StreamPref.MKB_P1_MAPPING_PRESET_ID]: {
onChange: StreamSettings.refreshMkbSettings,
},
[StreamPref.MKB_P1_SLOT]: {
onChange: () => {
EmulatedMkbHandler.getInstance()?.resetXcloudGamepads();
},
},
[StreamPref.KEYBOARD_SHORTCUTS_IN_GAME_PRESET_ID]: {
onChange: StreamSettings.refreshKeyboardShortcuts,
},
};
constructor() {
// Trigger onChange event when a setting value is modified
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();
}
private updateStreamElement(key: StreamPref, onChanges?: Set<SettingType['onChange']>, onChangeUis?: Set<SettingType['onChangeUi']>) {
const info = this.SETTINGS[key];
// Add events
if (info.onChangeUi) {
if (onChangeUis) {
// Save to a Set()
onChangeUis.add(info.onChangeUi);
} else {
// Trigger onChangeUi()
info.onChangeUi();
}
}
if (info.onChange && STATES.isPlaying) {
if (onChanges) {
// Save to a Set()
onChanges.add(info.onChange);
} else {
// Trigger onChange()
info.onChange();
}
}
// Update element
const $elm = info.$element;
if (!$elm) {
return;
}
const value = getGamePref(this.targetGameId, key, true)!;
if ('setValue' in $elm) {
($elm as any).setValue(value);
} else {
($elm as HTMLInputElement).value = value.toString();
}
this.updateDataset($elm, key as StreamPref);
}
private switchGameSettings(id: number) {
setGameIdPref(id);
// Don't re-apply settings if the game is the same
if (this.targetGameId === id) {
return;
}
// Re-apply all stream settings
const onChanges: Set<SettingType['onChange']> = new Set();
const onChangeUis: Set<SettingType['onChangeUi']> = new Set();
const oldGameId = this.targetGameId;
this.targetGameId = id;
let key: AnyPref;
for (key in this.SETTINGS) {
if (!isStreamPref(key)) {
continue;
}
const oldValue = getGamePref(oldGameId, key, true);
const newValue = getGamePref(this.targetGameId, key, true);
if (oldValue === newValue) {
continue;
}
// Only apply Stream settings
this.updateStreamElement(key, onChanges, onChangeUis);
}
// Trigger onChange callbacks
onChangeUis.forEach(fn => fn && fn());
onChanges.forEach(fn => fn && fn());
// Toggle tips if not playing anything
this.$tips.classList.toggle('bx-gone', id < 0);
}
setElement(pref: AnyPref, $elm: HTMLElement) {
// Set empty object
if (!this.SETTINGS[pref]) {
this.SETTINGS[pref] = {};
}
this.updateDataset($elm, pref as StreamPref);
this.SETTINGS[pref].$element = $elm;
}
getElement(pref: AnyPref, params?: any) {
// Set empty object
if (!this.SETTINGS[pref]) {
this.SETTINGS[pref] = {};
}
let $elm = this.SETTINGS[pref].$element;
if (!$elm) {
// Render element
$elm = SettingElement.fromPref(pref, null, params)!;
this.SETTINGS[pref].$element = $elm;
}
this.updateDataset($elm, pref as StreamPref);
return $elm;
}
hasElement(pref: AnyPref) {
return !!this.SETTINGS[pref]?.$element;
}
private updateDataset($elm: HTMLElement, pref: StreamPref) {
if (this.targetGameId === this.playingGameId && hasGamePref(this.playingGameId, pref)) {
$elm.dataset.override = 'true';
} else {
delete $elm.dataset['override'];
}
}
private renderStreamSettingsSelection() {
this.$tips = CE('p', { class: 'bx-gone' }, ` ⟶: ${t('reset-highlighted-setting')}`);
const $select = BxSelectElement.create(CE('select', false,
CE('optgroup', { label: t('settings-for') },
CE('option', { value: -1 }, t('all-games')),
),
), true);
$select.addEventListener('input', e => {
const id = parseInt($select.value);
// $btn.disabled = id < 0;
BxEventBus.Stream.emit('gameSettings.switched', { id });
});
this.$streamSettingsSelection = CE('div', {
class: 'bx-stream-settings-selection bx-gone',
_nearby: { orientation: 'vertical' },
},
CE('div', false, $select ),
this.$tips,
);
BxEventBus.Stream.on('xboxTitleId.changed', async ({ id }) => {
this.playingGameId = id;
// Only switch to game settings if it's not empty
const gameSettings = STORAGE.Stream.getGameSettings(id);
const selectedId = (gameSettings && !gameSettings.isEmpty()) ? id : -1;
setGameIdPref(selectedId);
// Remove every options except the first one (All games)
const $optGroup = $select.querySelector('optgroup')!;
while ($optGroup.childElementCount > 1) {
$optGroup.lastElementChild?.remove();
}
// Add current game to the selection
if (id >= 0) {
const title = id === 0 ? 'Xbox' : await XboxApi.getProductTitle(id);
$optGroup.appendChild(CE('option', {
value: id,
}, title));
}
// Activate custom settings
$select.value = selectedId.toString();
BxEventBus.Stream.emit('gameSettings.switched', { id: selectedId });
});
}
getStreamSettingsSelection() {
return this.$streamSettingsSelection;
}
getTargetGameId() {
return this.targetGameId;
}
}

View File

@ -1,21 +1,21 @@
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { StreamPref } from "@/enums/pref-keys";
import { limitVideoPlayerFps } from "../stream/stream-settings-utils";
import { BxEvent } from "@/utils/bx-event";
import { BxEventBus } from "@/utils/bx-event-bus";
import { getStreamPref } from "@/utils/pref-utils";
export class RendererShortcut {
static toggleVisibility() {
const $mediaContainer = document.querySelector('#game-stream div[data-testid="media-container"]');
if (!$mediaContainer) {
BxEvent.dispatch(window, BxEvent.VIDEO_VISIBILITY_CHANGED, { isShowing: true });
BxEventBus.Stream.emit('video.visibility.changed', { isVisible: true });
return;
}
$mediaContainer.classList.toggle('bx-gone');
const isShowing = !$mediaContainer.classList.contains('bx-gone');
const isVisible = !$mediaContainer.classList.contains('bx-gone');
// Switch FPS
limitVideoPlayerFps(isShowing ? getPref(PrefKey.VIDEO_MAX_FPS) : 0);
BxEvent.dispatch(window, BxEvent.VIDEO_VISIBILITY_CHANGED, { isShowing });
limitVideoPlayerFps(isVisible ? getStreamPref(StreamPref.VIDEO_MAX_FPS) : 0);
BxEventBus.Stream.emit('video.visibility.changed', { isVisible });
}
}

View File

@ -1,7 +1,7 @@
import { PrefKey } from "@/enums/pref-keys";
import { GlobalPref } from "@/enums/pref-keys";
import { ShortcutAction } from "@/enums/shortcut-actions";
import { AppInterface, STATES } from "@/utils/global";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { getGlobalPref } from "@/utils/pref-utils";
import { t } from "@/utils/translation";
type ShortcutActions = {
@ -16,6 +16,17 @@ export const SHORTCUT_ACTIONS: ShortcutActions = {
[ShortcutAction.BETTER_XCLOUD_SETTINGS_SHOW]: [t('settings'), t('show')],
},
// MKB
...(STATES.browser.capabilities.mkb ? {
[t('mouse-and-keyboard')]: {
[ShortcutAction.MKB_TOGGLE]: [t('toggle')],
},
} : {}),
[t('controller')]: {
[ShortcutAction.CONTROLLER_XBOX_BUTTON_PRESS]: [t('button-xbox'), t('press')],
},
// Device
...(!!AppInterface ? {
[t('device')]: {
@ -35,7 +46,7 @@ export const SHORTCUT_ACTIONS: ShortcutActions = {
[ShortcutAction.STREAM_SOUND_TOGGLE]: [t('sound'), t('toggle')],
...(getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED) ? {
...(getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED) ? {
[ShortcutAction.STREAM_VOLUME_INC]: [t('volume'), t('increase')],
[ShortcutAction.STREAM_VOLUME_DEC]: [t('volume'), t('decrease')],
} : {}),
@ -45,13 +56,6 @@ export const SHORTCUT_ACTIONS: ShortcutActions = {
[ShortcutAction.STREAM_MICROPHONE_TOGGLE]: [t('microphone'), t('toggle')],
},
// MKB
...(STATES.browser.capabilities.mkb ? {
[t('mouse-and-keyboard')]: {
[ShortcutAction.MKB_TOGGLE]: [t('toggle')],
},
} : {}),
// Other
[t('other')]: {
[ShortcutAction.TRUE_ACHIEVEMENTS_OPEN]: [t('true-achievements'), t('show')],

View File

@ -2,9 +2,10 @@ import { t } from "@utils/translation";
import { STATES } from "@utils/global";
import { Toast } from "@utils/toast";
import { ceilToNearest, floorToNearest } from "@/utils/utils";
import { PrefKey } from "@/enums/pref-keys";
import { getPref, setPref } from "@/utils/settings-storages/global-settings-storage";
import { BxEvent } from "@/utils/bx-event";
import { GlobalPref, StreamPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { BxEventBus } from "@/utils/bx-event-bus";
import { getStreamPref, setStreamPref } from "@/utils/pref-utils";
export enum SpeakerState {
ENABLED,
@ -13,11 +14,11 @@ export enum SpeakerState {
export class SoundShortcut {
static adjustGainNodeVolume(amount: number): number {
if (!getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED)) {
if (!getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED)) {
return 0;
}
const currentValue = getPref<AudioVolume>(PrefKey.AUDIO_VOLUME);
const currentValue = getStreamPref(StreamPref.AUDIO_VOLUME);
let nearestValue: number;
if (amount > 0) { // Increase
@ -33,7 +34,7 @@ export class SoundShortcut {
newValue = currentValue + amount;
}
newValue = setPref(PrefKey.AUDIO_VOLUME, newValue, true);
newValue = setStreamPref(StreamPref.AUDIO_VOLUME, newValue, 'direct');
SoundShortcut.setGainNodeVolume(newValue);
// Show toast
@ -47,14 +48,14 @@ export class SoundShortcut {
}
static muteUnmute() {
if (getPref(PrefKey.AUDIO_VOLUME_CONTROL_ENABLED) && STATES.currentStream.audioGainNode) {
if (getGlobalPref(GlobalPref.AUDIO_VOLUME_CONTROL_ENABLED) && STATES.currentStream.audioGainNode) {
const gainValue = STATES.currentStream.audioGainNode.gain.value;
const settingValue = getPref<AudioVolume>(PrefKey.AUDIO_VOLUME);
const settingValue = getStreamPref(StreamPref.AUDIO_VOLUME);
let targetValue: number;
if (settingValue === 0) { // settingValue is 0 => set to 100
targetValue = 100;
setPref(PrefKey.AUDIO_VOLUME, targetValue, true);
setStreamPref(StreamPref.AUDIO_VOLUME, targetValue, 'direct');
} else if (gainValue === 0) { // is being muted => set to settingValue
targetValue = settingValue;
} else { // not being muted => mute
@ -71,8 +72,8 @@ export class SoundShortcut {
SoundShortcut.setGainNodeVolume(targetValue);
Toast.show(`${t('stream')} ${t('volume')}`, status, { instant: true });
BxEvent.dispatch(window, BxEvent.SPEAKER_STATE_CHANGED, {
speakerState: targetValue === 0 ? SpeakerState.MUTED : SpeakerState.ENABLED,
BxEventBus.Stream.emit('speaker.state.changed', {
state: targetValue === 0 ? SpeakerState.MUTED : SpeakerState.ENABLED,
});
return;
}
@ -84,9 +85,9 @@ export class SoundShortcut {
const status = $media.muted ? t('muted') : t('unmuted');
Toast.show(`${t('stream')} ${t('volume')}`, status, { instant: true });
BxEvent.dispatch(window, BxEvent.SPEAKER_STATE_CHANGED, {
speakerState: $media.muted ? SpeakerState.MUTED : SpeakerState.ENABLED,
})
BxEventBus.Stream.emit('speaker.state.changed', {
state: $media.muted ? SpeakerState.MUTED : SpeakerState.ENABLED,
});
}
}
}

View File

@ -0,0 +1,21 @@
import { generateVirtualControllerMapping } from "@/utils/gamepad";
export class VirtualControllerShortcut {
static pressXboxButton(): void {
const streamSession = window.BX_EXPOSED.streamSession;
if (!streamSession) {
return;
}
const released = generateVirtualControllerMapping(0);
const pressed = generateVirtualControllerMapping(0, {
Nexus: 1,
VirtualPhysicality: 1024, // Home
});
streamSession.onVirtualGamepadInput('systemMenu', performance.now(), [pressed]);
setTimeout(() => {
streamSession.onVirtualGamepadInput('systemMenu', performance.now(), [released]);
}, 100);
}
}

View File

@ -0,0 +1,191 @@
import { WebGL2Player } from "./player/webgl2/webgl2-player";
import { ScreenshotManager } from "@/utils/screenshot-manager";
import { STATES } from "@/utils/global";
import { StreamPref } from "@/enums/pref-keys";
import { BX_FLAGS } from "@/utils/bx-flags";
import { StreamPlayerType, VideoPosition } from "@/enums/pref-values";
import { getStreamPref } from "@/utils/pref-utils";
import type { BaseCanvasPlayer } from "./player/base-canvas-player";
import { VideoPlayer } from "./player/video/video-player";
import { StreamPlayerElement } from "./player/base-stream-player";
import { WebGPUPlayer } from "./player/webgpu/webgpu-player";
import type { StreamPlayerOptions } from "@/types/stream";
export class StreamPlayerManager {
private static instance: StreamPlayerManager;
public static getInstance = () => StreamPlayerManager.instance ?? (StreamPlayerManager.instance = new StreamPlayerManager());
private $video!: HTMLVideoElement;
private videoPlayer!: VideoPlayer;
private canvasPlayer: BaseCanvasPlayer | null | undefined;
private playerType: StreamPlayerType = StreamPlayerType.VIDEO;
private constructor() {}
setVideoElement($video: HTMLVideoElement) {
this.$video = $video;
this.videoPlayer = new VideoPlayer($video, 'VideoPlayer');
this.videoPlayer.init();
}
resizePlayer() {
const PREF_RATIO = getStreamPref(StreamPref.VIDEO_RATIO);
const $video = this.$video;
const isNativeTouchGame = STATES.currentStream.titleInfo?.details.hasNativeTouchSupport;
let targetWidth;
let targetHeight;
let targetObjectFit;
if (PREF_RATIO.includes(':')) {
const tmp = PREF_RATIO.split(':');
// Get preferred ratio
const videoRatio = parseFloat(tmp[0]) / parseFloat(tmp[1]);
let width = 0;
let height = 0;
// Get parent's ratio
const parentRect = $video.parentElement!.getBoundingClientRect();
const parentRatio = parentRect.width / parentRect.height;
// Get target width & height
if (parentRatio > videoRatio) {
height = parentRect.height;
width = height * videoRatio;
} else {
width = parentRect.width;
height = width / videoRatio;
}
// Avoid floating points
width = Math.ceil(Math.min(parentRect.width, width));
height = Math.ceil(Math.min(parentRect.height, height));
$video.dataset.width = width.toString();
$video.dataset.height = height.toString();
// Set position
const $parent = $video.parentElement!;
const position = getStreamPref(StreamPref.VIDEO_POSITION);
$parent.style.removeProperty('padding-top');
$parent.dataset.position = position;
if (position === VideoPosition.TOP_HALF || position === VideoPosition.BOTTOM_HALF) {
let padding = Math.floor((window.innerHeight - height) / 4);
if (padding > 0) {
if (position === VideoPosition.BOTTOM_HALF) {
padding *= 3;
}
$parent.style.paddingTop = padding + 'px';
}
}
// Update size
targetWidth = `${width}px`;
targetHeight = `${height}px`;
targetObjectFit = PREF_RATIO === '16:9' ? 'contain' : 'fill';
} else {
targetWidth = '100%';
targetHeight = '100%';
targetObjectFit = PREF_RATIO;
$video.dataset.width = window.innerWidth.toString();
$video.dataset.height = window.innerHeight.toString();
}
$video.style.width = targetWidth;
$video.style.height = targetHeight;
$video.style.objectFit = targetObjectFit;
if (this.canvasPlayer) {
const $canvas = this.canvasPlayer.getCanvas();
$canvas.style.width = targetWidth;
$canvas.style.height = targetHeight;
$canvas.style.objectFit = targetObjectFit;
$video.dispatchEvent(new Event('resize'));
}
// Update video dimensions
if (isNativeTouchGame && this.playerType !== StreamPlayerType.VIDEO) {
window.BX_EXPOSED.streamSession.updateDimensions();
}
}
switchPlayerType(type: StreamPlayerType, refreshPlayer: boolean = false) {
if (this.playerType !== type) {
const videoClass = BX_FLAGS.DeviceInfo.deviceType === 'android-tv' ? 'bx-pixel' : 'bx-gone';
// Destroy old player
this.cleanUpCanvasPlayer();
if (type === StreamPlayerType.VIDEO) {
// Switch from Canvas -> Video
this.$video.classList.remove(videoClass);
} else {
// Switch from Video -> Canvas
if (BX_FLAGS.EnableWebGPURenderer && type === StreamPlayerType.WEBGPU) {
this.canvasPlayer = new WebGPUPlayer(this.$video);
} else {
this.canvasPlayer = new WebGL2Player(this.$video);
}
this.canvasPlayer.init();
this.videoPlayer.clearFilters();
this.$video.classList.add(videoClass);
}
this.playerType = type;
}
refreshPlayer && this.refreshPlayer();
}
updateOptions(options: StreamPlayerOptions, refreshPlayer: boolean = false) {
(this.canvasPlayer || this.videoPlayer).updateOptions(options, refreshPlayer);
}
getPlayerElement(elementType?: StreamPlayerElement) {
if (typeof elementType === 'undefined') {
elementType = this.playerType === StreamPlayerType.VIDEO ? StreamPlayerElement.VIDEO : StreamPlayerElement.CANVAS;
}
if (elementType !== StreamPlayerElement.VIDEO) {
return this.canvasPlayer?.getCanvas();
}
return this.$video;
}
getCanvasPlayer() {
return this.canvasPlayer;
}
refreshPlayer() {
if (this.playerType === StreamPlayerType.VIDEO) {
this.videoPlayer.refreshPlayer();
} else {
ScreenshotManager.getInstance().updateCanvasFilters('none');
this.canvasPlayer?.refreshPlayer();
}
this.resizePlayer();
}
getVideoPlayerFilterStyle() {
throw new Error("Method not implemented.");
}
private cleanUpCanvasPlayer() {
this.canvasPlayer?.destroy();
this.canvasPlayer = null;
}
destroy() {
this.cleanUpCanvasPlayer();
}
}

View File

@ -1,303 +0,0 @@
import { isFullVersion } from "@macros/build" with { type: "macro" };
import { CE } from "@/utils/html";
import { WebGL2Player } from "./player/webgl2-player";
import { ScreenshotManager } from "@/utils/screenshot-manager";
import { STATES } from "@/utils/global";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { BX_FLAGS } from "@/utils/bx-flags";
import { StreamPlayerType, StreamVideoProcessing, VideoPosition, VideoRatio } from "@/enums/pref-values";
export type StreamPlayerOptions = Partial<{
processing: string,
sharpness: number,
saturation: number,
contrast: number,
brightness: number,
}>;
export class StreamPlayer {
private $video: HTMLVideoElement;
private playerType: StreamPlayerType = StreamPlayerType.VIDEO;
private options: StreamPlayerOptions = {};
private webGL2Player: WebGL2Player | null = null;
private $videoCss: HTMLStyleElement | null = null;
private $usmMatrix: SVGFEConvolveMatrixElement | null = null;
constructor($video: HTMLVideoElement, type: StreamPlayerType, options: StreamPlayerOptions) {
this.setupVideoElements();
this.$video = $video;
this.options = options || {};
this.setPlayerType(type);
}
private setupVideoElements() {
this.$videoCss = document.getElementById('bx-video-css') as HTMLStyleElement;
if (this.$videoCss) {
return;
}
const $fragment = document.createDocumentFragment();
this.$videoCss = CE<HTMLStyleElement>('style', { id: 'bx-video-css' });
$fragment.appendChild(this.$videoCss);
// Setup SVG filters
const $svg = CE('svg', {
id: 'bx-video-filters',
xmlns: 'http://www.w3.org/2000/svg',
class: 'bx-gone',
}, CE('defs', { xmlns: 'http://www.w3.org/2000/svg' },
CE('filter', {
id: 'bx-filter-usm',
xmlns: 'http://www.w3.org/2000/svg',
}, this.$usmMatrix = CE('feConvolveMatrix', {
id: 'bx-filter-usm-matrix',
order: '3',
xmlns: 'http://www.w3.org/2000/svg',
})),
),
);
$fragment.appendChild($svg);
document.documentElement.appendChild($fragment);
}
private getVideoPlayerFilterStyle() {
const filters = [];
const sharpness = this.options.sharpness || 0;
if (this.options.processing === StreamVideoProcessing.USM && sharpness != 0) {
const level = (7 - ((sharpness / 2) - 1) * 0.5).toFixed(1); // 5, 5.5, 6, 6.5, 7
const matrix = `0 -1 0 -1 ${level} -1 0 -1 0`;
this.$usmMatrix?.setAttributeNS(null, 'kernelMatrix', matrix);
filters.push(`url(#bx-filter-usm)`);
}
const saturation = this.options.saturation || 100;
if (saturation != 100) {
filters.push(`saturate(${saturation}%)`);
}
const contrast = this.options.contrast || 100;
if (contrast != 100) {
filters.push(`contrast(${contrast}%)`);
}
const brightness = this.options.brightness || 100;
if (brightness != 100) {
filters.push(`brightness(${brightness}%)`);
}
return filters.join(' ');
}
private resizePlayer() {
const PREF_RATIO = getPref<VideoRatio>(PrefKey.VIDEO_RATIO);
const $video = this.$video;
const isNativeTouchGame = STATES.currentStream.titleInfo?.details.hasNativeTouchSupport;
let $webGL2Canvas;
if (this.playerType == StreamPlayerType.WEBGL2) {
$webGL2Canvas = this.webGL2Player?.getCanvas()!;
}
let targetWidth;
let targetHeight;
let targetObjectFit;
if (PREF_RATIO.includes(':')) {
const tmp = PREF_RATIO.split(':');
// Get preferred ratio
const videoRatio = parseFloat(tmp[0]) / parseFloat(tmp[1]);
let width = 0;
let height = 0;
// Get parent's ratio
const parentRect = $video.parentElement!.getBoundingClientRect();
const parentRatio = parentRect.width / parentRect.height;
// Get target width & height
if (parentRatio > videoRatio) {
height = parentRect.height;
width = height * videoRatio;
} else {
width = parentRect.width;
height = width / videoRatio;
}
// Prevent floating points
width = Math.ceil(Math.min(parentRect.width, width));
height = Math.ceil(Math.min(parentRect.height, height));
$video.dataset.width = width.toString();
$video.dataset.height = height.toString();
// Set position
const $parent = $video.parentElement!;
const position = getPref<VideoPosition>(PrefKey.VIDEO_POSITION);
$parent.style.removeProperty('padding-top');
$parent.dataset.position = position;
if (position === VideoPosition.TOP_HALF || position === VideoPosition.BOTTOM_HALF) {
let padding = Math.floor((window.innerHeight - height) / 4);
if (padding > 0) {
if (position === VideoPosition.BOTTOM_HALF) {
padding *= 3;
}
$parent.style.paddingTop = padding + 'px';
}
}
// Update size
targetWidth = `${width}px`;
targetHeight = `${height}px`;
targetObjectFit = PREF_RATIO === '16:9' ? 'contain' : 'fill';
} else {
targetWidth = '100%';
targetHeight = '100%';
targetObjectFit = PREF_RATIO;
$video.dataset.width = window.innerWidth.toString();
$video.dataset.height = window.innerHeight.toString();
}
$video.style.width = targetWidth;
$video.style.height = targetHeight;
$video.style.objectFit = targetObjectFit;
// $video.style.padding = padding;
if ($webGL2Canvas) {
$webGL2Canvas.style.width = targetWidth;
$webGL2Canvas.style.height = targetHeight;
$webGL2Canvas.style.objectFit = targetObjectFit;
$video.dispatchEvent(new Event('resize'));
}
// Update video dimensions
if (isNativeTouchGame && this.playerType == StreamPlayerType.WEBGL2) {
window.BX_EXPOSED.streamSession.updateDimensions();
}
}
setPlayerType(type: StreamPlayerType, refreshPlayer: boolean = false) {
if (this.playerType !== type) {
const videoClass = BX_FLAGS.DeviceInfo.deviceType === 'android-tv' ? 'bx-pixel' : 'bx-gone';
// Switch from Video -> WebGL2
if (type === StreamPlayerType.WEBGL2) {
// Initialize WebGL2 player
if (!this.webGL2Player) {
this.webGL2Player = new WebGL2Player(this.$video);
} else {
this.webGL2Player.resume();
}
this.$videoCss!.textContent = '';
this.$video.classList.add(videoClass);
} else {
// Cleanup WebGL2 Player
this.webGL2Player?.stop();
this.$video.classList.remove(videoClass);
}
}
this.playerType = type;
refreshPlayer && this.refreshPlayer();
}
setOptions(options: StreamPlayerOptions, refreshPlayer: boolean = false) {
this.options = options;
refreshPlayer && this.refreshPlayer();
}
updateOptions(options: StreamPlayerOptions, refreshPlayer: boolean = false) {
this.options = Object.assign(this.options, options);
refreshPlayer && this.refreshPlayer();
}
getPlayerElement(playerType?: StreamPlayerType) {
if (typeof playerType === 'undefined') {
playerType = this.playerType;
}
if (playerType === StreamPlayerType.WEBGL2) {
return this.webGL2Player?.getCanvas();
}
return this.$video;
}
getWebGL2Player() {
return this.webGL2Player;
}
refreshPlayer() {
if (this.playerType === StreamPlayerType.WEBGL2) {
const options = this.options;
const webGL2Player = this.webGL2Player!;
if (options.processing === StreamVideoProcessing.USM) {
webGL2Player.setFilter(1);
} else {
webGL2Player.setFilter(2);
}
isFullVersion() && ScreenshotManager.getInstance().updateCanvasFilters('none');
webGL2Player.setSharpness(options.sharpness || 0);
webGL2Player.setSaturation(options.saturation || 100);
webGL2Player.setContrast(options.contrast || 100);
webGL2Player.setBrightness(options.brightness || 100);
} else {
let filters = this.getVideoPlayerFilterStyle();
let videoCss = '';
if (filters) {
videoCss += `filter: ${filters} !important;`;
}
// Apply video filters to screenshots
if (isFullVersion() && getPref(PrefKey.SCREENSHOT_APPLY_FILTERS)) {
ScreenshotManager.getInstance().updateCanvasFilters(filters);
}
let css = '';
if (videoCss) {
css = `#game-stream video { ${videoCss} }`;
}
this.$videoCss!.textContent = css;
}
this.resizePlayer();
}
reloadPlayer() {
this.cleanUpWebGL2Player();
this.playerType = StreamPlayerType.VIDEO;
this.setPlayerType(StreamPlayerType.WEBGL2, false);
}
private cleanUpWebGL2Player() {
// Clean up WebGL2 Player
this.webGL2Player?.destroy();
this.webGL2Player = null;
}
destroy() {
this.cleanUpWebGL2Player();
}
}

View File

@ -5,7 +5,7 @@ import { BxEvent } from "@utils/bx-event";
import { CE, createSvgIcon, humanFileSize } from "@utils/html";
import { STATES } from "@utils/global";
import { BxLogger } from "@/utils/bx-logger";
import { BxIcon } from "@/utils/bx-icon";
import { BxIcon, type BxIconRaw } from "@/utils/bx-icon";
import { GuideMenuTab } from "../ui/guide-menu";
import { StreamStatsCollector } from "@/utils/stream-stats-collector";
import { StreamStat } from "@/enums/pref-values";
@ -14,7 +14,7 @@ import { StreamStat } from "@/enums/pref-values";
type StreamBadgeInfo = {
name: string,
$element?: HTMLElement,
icon: typeof BxIcon,
icon: BxIconRaw,
color: string,
};
@ -253,8 +253,9 @@ export class StreamBadges {
const allAudioCodecs: Record<string, RTCBasicStat> = {};
let audioCodecId;
const allCandidates: Record<string, string> = {};
let candidateId;
const allCandidatePairs: Record<string, string> = {};
const allRemoteCandidates: Record<string, string> = {};
let candidatePairId;
stats.forEach((stat: RTCBasicStat) => {
if (stat.type === 'codec') {
@ -275,10 +276,12 @@ export class StreamBadges {
} else if (stat.kind === 'audio') {
audioCodecId = stat.codecId;
}
} else if (stat.type === 'candidate-pair' && stat.packetsReceived > 0 && stat.state === 'succeeded') {
candidateId = stat.remoteCandidateId;
} else if (stat.type === 'transport' && (stat as unknown as RTCTransportStats).selectedCandidatePairId) {
candidatePairId = (stat as unknown as RTCTransportStats).selectedCandidatePairId;
} else if (stat.type === 'candidate-pair') {
allCandidatePairs[stat.id] = (stat as unknown as RTCIceCandidatePairStats).remoteCandidateId;
} else if (stat.type === 'remote-candidate') {
allCandidates[stat.id] = stat.address;
allRemoteCandidates[stat.id] = stat.address;
}
});
@ -336,12 +339,12 @@ export class StreamBadges {
}
// Get server type
if (candidateId) {
BxLogger.info('candidate', candidateId, allCandidates);
if (candidatePairId) {
BxLogger.info('candidate', candidatePairId, allCandidatePairs);
// Server + Region
let text = '';
const isIpv6 = allCandidates[candidateId].includes(':');
const isIpv6 = allRemoteCandidates[allCandidatePairs[candidatePairId]].includes(':');
const server = this.serverInfo.server;
if (server && server.region) {

View File

@ -1,38 +1,39 @@
import { STATES } from "@utils/global";
import { UserAgent } from "@utils/user-agent";
import type { StreamPlayerOptions } from "../stream-player";
import { PrefKey } from "@/enums/pref-keys";
import { getPref, setPref } from "@/utils/settings-storages/global-settings-storage";
import { StreamPref } from "@/enums/pref-keys";
import { StreamVideoProcessing, StreamPlayerType } from "@/enums/pref-values";
import { escapeCssSelector } from "@/utils/html";
import { getStreamPref, setStreamPref } from "@/utils/pref-utils";
import { SettingsManager } from "../settings-manager";
import type { StreamPlayerOptions } from "@/types/stream";
export function onChangeVideoPlayerType() {
const playerType = getPref<StreamPlayerType>(PrefKey.VIDEO_PLAYER_TYPE);
const $videoProcessing = document.getElementById(`bx_setting_${escapeCssSelector(PrefKey.VIDEO_PROCESSING)}`) as HTMLSelectElement;
const $videoSharpness = document.getElementById(`bx_setting_${escapeCssSelector(PrefKey.VIDEO_SHARPNESS)}`) as HTMLElement;
const $videoPowerPreference = document.getElementById(`bx_setting_${escapeCssSelector(PrefKey.VIDEO_POWER_PREFERENCE)}`) as HTMLElement;
const $videoMaxFps = document.getElementById(`bx_setting_${escapeCssSelector(PrefKey.VIDEO_MAX_FPS)}`) as HTMLElement;
if (!$videoProcessing) {
const playerType = getStreamPref(StreamPref.VIDEO_PLAYER_TYPE);
const settingsManager = SettingsManager.getInstance();
if (!settingsManager.hasElement(StreamPref.VIDEO_PROCESSING)) {
return;
}
let isDisabled = false;
const $videoProcessing = settingsManager.getElement(StreamPref.VIDEO_PROCESSING) as HTMLSelectElement;
const $videoSharpness = settingsManager.getElement(StreamPref.VIDEO_SHARPNESS);
const $videoPowerPreference = settingsManager.getElement(StreamPref.VIDEO_POWER_PREFERENCE);
const $videoMaxFps = settingsManager.getElement(StreamPref.VIDEO_MAX_FPS);
const $optCas = $videoProcessing.querySelector<HTMLOptionElement>(`option[value=${StreamVideoProcessing.CAS}]`);
if (playerType === StreamPlayerType.WEBGL2) {
$optCas && ($optCas.disabled = false);
} else {
if (playerType === StreamPlayerType.VIDEO) {
// Only allow USM when player type is Video
$videoProcessing.value = StreamVideoProcessing.USM;
setPref(PrefKey.VIDEO_PROCESSING, StreamVideoProcessing.USM);
setStreamPref(StreamPref.VIDEO_PROCESSING, StreamVideoProcessing.USM, 'direct');
$optCas && ($optCas.disabled = true);
if (UserAgent.isSafari()) {
isDisabled = true;
}
} else {
$optCas && ($optCas.disabled = false);
}
$videoProcessing.disabled = isDisabled;
@ -40,37 +41,39 @@ export function onChangeVideoPlayerType() {
// Hide Power Preference setting if renderer isn't WebGL2
$videoPowerPreference.closest('.bx-settings-row')!.classList.toggle('bx-gone', playerType !== StreamPlayerType.WEBGL2);
$videoMaxFps.closest('.bx-settings-row')!.classList.toggle('bx-gone', playerType !== StreamPlayerType.WEBGL2);
updateVideoPlayer();
$videoMaxFps.closest('.bx-settings-row')!.classList.toggle('bx-gone', playerType === StreamPlayerType.VIDEO);
}
export function limitVideoPlayerFps(targetFps: number) {
const streamPlayer = STATES.currentStream.streamPlayer;
streamPlayer?.getWebGL2Player()?.setTargetFps(targetFps);
const streamPlayer = STATES.currentStream.streamPlayerManager;
streamPlayer?.getCanvasPlayer()?.setTargetFps(targetFps);
}
export function updateVideoPlayer() {
const streamPlayer = STATES.currentStream.streamPlayer;
if (!streamPlayer) {
const streamPlayerManager = STATES.currentStream.streamPlayerManager;
if (!streamPlayerManager) {
return;
}
limitVideoPlayerFps(getPref(PrefKey.VIDEO_MAX_FPS));
const options = {
processing: getPref(PrefKey.VIDEO_PROCESSING),
sharpness: getPref(PrefKey.VIDEO_SHARPNESS),
saturation: getPref(PrefKey.VIDEO_SATURATION),
contrast: getPref(PrefKey.VIDEO_CONTRAST),
brightness: getPref(PrefKey.VIDEO_BRIGHTNESS),
processing: getStreamPref(StreamPref.VIDEO_PROCESSING),
sharpness: getStreamPref(StreamPref.VIDEO_SHARPNESS),
saturation: getStreamPref(StreamPref.VIDEO_SATURATION),
contrast: getStreamPref(StreamPref.VIDEO_CONTRAST),
brightness: getStreamPref(StreamPref.VIDEO_BRIGHTNESS),
} satisfies StreamPlayerOptions;
streamPlayer.setPlayerType(getPref(PrefKey.VIDEO_PLAYER_TYPE));
streamPlayer.updateOptions(options);
streamPlayer.refreshPlayer();
streamPlayerManager.switchPlayerType(getStreamPref(StreamPref.VIDEO_PLAYER_TYPE));
limitVideoPlayerFps(getStreamPref(StreamPref.VIDEO_MAX_FPS));
streamPlayerManager.updateOptions(options);
streamPlayerManager.refreshPlayer();
}
window.addEventListener('resize', updateVideoPlayer);
function resizeVideoPlayer() {
const streamPlayerManager = STATES.currentStream.streamPlayerManager;
streamPlayerManager?.resizePlayer();
}
window.addEventListener('resize', resizeVideoPlayer);

View File

@ -1,12 +1,12 @@
import { BxEvent } from "@utils/bx-event"
import { CE } from "@utils/html"
import { t } from "@utils/translation"
import { STATES } from "@utils/global"
import { PrefKey } from "@/enums/pref-keys"
import { getPref } from "@/utils/settings-storages/global-settings-storage"
import { StreamStatsCollector, type StreamStatGrade } from "@/utils/stream-stats-collector"
import { StreamPref } from "@/enums/pref-keys"
import { StreamStatsCollector } from "@/utils/stream-stats-collector"
import { BxLogger } from "@/utils/bx-logger"
import { StreamStat } from "@/enums/pref-values"
import { BxEventBus } from "@/utils/bx-event-bus"
import { getStreamPref } from "@/utils/pref-utils";
export class StreamStats {
@ -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) => {
@ -164,7 +143,7 @@ export class StreamStats {
return;
}
const PREF_STATS_CONDITIONAL_FORMATTING = getPref(PrefKey.STATS_CONDITIONAL_FORMATTING);
const PREF_STATS_CONDITIONAL_FORMATTING = getStreamPref(StreamPref.STATS_CONDITIONAL_FORMATTING);
let grade: StreamStatGrade = '';
// Collect stats
@ -192,18 +171,27 @@ export class StreamStats {
}
refreshStyles() {
const PREF_ITEMS = getPref<StreamStat[]>(PrefKey.STATS_ITEMS);
const PREF_ITEMS = getStreamPref(StreamPref.STATS_ITEMS);
const PREF_OPACITY_BG = getStreamPref(StreamPref.STATS_OPACITY_BACKGROUND);
const $container = this.$container;
$container.dataset.stats = '[' + PREF_ITEMS.join('][') + ']';
$container.dataset.position = getPref(PrefKey.STATS_POSITION);
$container.dataset.transparent = getPref(PrefKey.STATS_TRANSPARENT);
$container.style.opacity = getPref(PrefKey.STATS_OPACITY) + '%';
$container.style.fontSize = getPref(PrefKey.STATS_TEXT_SIZE);
$container.dataset.position = getStreamPref(StreamPref.STATS_POSITION);
if (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(StreamPref.STATS_OPACITY_ALL) + '%';
$container.style.fontSize = getStreamPref(StreamPref.STATS_TEXT_SIZE);
}
hideSettingsUi() {
if (this.isGlancing() && !getPref(PrefKey.STATS_QUICK_GLANCE_ENABLED)) {
if (this.isGlancing() && !getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED)) {
this.stop();
}
}
@ -218,7 +206,7 @@ export class StreamStats {
class: `bx-stat-${statKey}`,
title: stat.name,
},
CE('label', {}, statKey.toUpperCase()),
CE('label', false, statKey.toUpperCase()),
stat.$element,
);
@ -230,9 +218,9 @@ export class StreamStats {
}
static setupEvents() {
window.addEventListener(BxEvent.STREAM_PLAYING, e => {
const PREF_STATS_QUICK_GLANCE = getPref(PrefKey.STATS_QUICK_GLANCE_ENABLED);
const PREF_STATS_SHOW_WHEN_PLAYING = getPref(PrefKey.STATS_SHOW_WHEN_PLAYING);
BxEventBus.Stream.on('state.playing', () => {
const PREF_STATS_QUICK_GLANCE = getStreamPref(StreamPref.STATS_QUICK_GLANCE_ENABLED);
const PREF_STATS_SHOW_WHEN_PLAYING = getStreamPref(StreamPref.STATS_SHOW_WHEN_PLAYING);
const streamStats = StreamStats.getInstance();
@ -240,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

@ -1,7 +1,6 @@
import { STATES } from "@utils/global.ts";
import { createSvgIcon } from "@utils/html.ts";
import { BxIcon } from "@utils/bx-icon";
import { BxEvent } from "@utils/bx-event.ts";
import { BxIcon, type BxIconRaw } from "@utils/bx-icon";
import { t } from "@utils/translation.ts";
import { StreamBadges } from "./stream-badges.ts";
import { StreamStats } from "./stream-stats.ts";
@ -13,9 +12,8 @@ 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: typeof BxIcon): HTMLElement | null {
private static cloneStreamHudButton($btnOrg: HTMLElement, label: string, svgIcon: BxIconRaw): HTMLElement | null {
if (!$btnOrg) {
return null;
}
@ -78,7 +76,7 @@ export class StreamUiHandler {
return $container;
}
private static cloneCloseButton($btnOrg: HTMLElement, icon: typeof BxIcon, className: string, onChange: any): HTMLElement | null {
private static cloneCloseButton($btnOrg: HTMLElement, icon: BxIconRaw, className: string, onChange: any): HTMLElement | null {
if (!$btnOrg) {
return null;
}
@ -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')) {
BxEvent.dispatch(window, BxEvent.STREAM_ERROR_PAGE);
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

@ -4,10 +4,11 @@ import { BxEvent } from "@utils/bx-event";
import { NATIVE_FETCH } from "@utils/bx-flags";
import { t } from "@utils/translation";
import { BxLogger } from "@utils/bx-logger";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { TouchControllerStyleCustom, TouchControllerStyleStandard } from "@/enums/pref-values";
import { GhPagesUtils } from "@/utils/gh-pages";
import { BxEventBus } from "@/utils/bx-event-bus";
const LOG_TAG = 'TouchController';
@ -208,7 +209,7 @@ export class TouchController {
}
if (!layoutId) {
BxLogger.error(LOG_TAG, 'Invalid layoutId, show default controller');
BxLogger.warning(LOG_TAG, 'Invalid layoutId, show default controller');
TouchController.#enabled && TouchController.#showDefault();
return;
}
@ -266,9 +267,13 @@ export class TouchController {
return TouchController.#customList;
}
static hasCustomControl(productId: string): boolean {
return TouchController.#customList?.includes(productId);
}
static setup() {
// Function for testing touch control
(window as any).testTouchLayout = (layout: any) => {
window.testTouchLayout = (layout: any) => {
const { touchLayoutManager } = window.BX_EXPOSED;
touchLayoutManager && touchLayoutManager.changeLayoutForScope({
@ -288,12 +293,12 @@ export class TouchController {
TouchController.#$style = $style;
const PREF_STYLE_STANDARD = getPref<TouchControllerStyleStandard>(PrefKey.TOUCH_CONTROLLER_STYLE_STANDARD);
const PREF_STYLE_CUSTOM = getPref<TouchControllerStyleCustom>(PrefKey.TOUCH_CONTROLLER_STYLE_CUSTOM);
const PREF_STYLE_STANDARD = getGlobalPref(GlobalPref.TOUCH_CONTROLLER_STYLE_STANDARD);
const PREF_STYLE_CUSTOM = getGlobalPref(GlobalPref.TOUCH_CONTROLLER_STYLE_CUSTOM);
window.addEventListener(BxEvent.DATA_CHANNEL_CREATED, e => {
const dataChannel = (e as any).dataChannel;
if (!dataChannel || dataChannel.label !== 'message') {
BxEventBus.Stream.on('dataChannelCreated', payload => {
const { dataChannel } = payload;
if (dataChannel?.label !== 'message') {
return;
}

View File

@ -1,11 +1,13 @@
import { isFullVersion } from "@macros/build" with { type: "macro" };
import { GamepadKey } from "@/enums/gamepad";
import { PrefKey } from "@/enums/pref-keys";
import { VIRTUAL_GAMEPAD_ID } from "@/modules/mkb/mkb-handler";
import { BxEvent } from "@/utils/bx-event";
import { BxEventBus } from "@/utils/bx-event-bus";
import { BxLogger } from "@/utils/bx-logger";
import { CE, isElementVisible } from "@/utils/html";
import { calculateSelectBoxes, CE, isElementVisible } from "@/utils/html";
import { setNearby } from "@/utils/navigation-utils";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { BxNumberStepper } from "@/web-components/bx-number-stepper";
export enum NavigationDirection {
UP = 1,
@ -20,10 +22,10 @@ export type NavigationNearbyElements = Partial<{
focus: NavigationElement | (() => boolean),
loop: ((direction: NavigationDirection) => boolean),
[NavigationDirection.UP]: NavigationElement | (() => void) | 'previous' | 'next',
[NavigationDirection.DOWN]: NavigationElement | (() => void) | 'previous' | 'next',
[NavigationDirection.LEFT]: NavigationElement | (() => void) | 'previous' | 'next',
[NavigationDirection.RIGHT]: NavigationElement | (() => void) | 'previous' | 'next',
[NavigationDirection.UP]: NavigationElement,
[NavigationDirection.DOWN]: NavigationElement,
[NavigationDirection.LEFT]: NavigationElement,
[NavigationDirection.RIGHT]: NavigationElement,
}>;
export interface NavigationElement extends HTMLElement {
@ -106,16 +108,18 @@ export class NavigationDialogManager {
private static readonly GAMEPAD_POLLING_INTERVAL = 50;
private static readonly GAMEPAD_KEYS = [
GamepadKey.UP,
GamepadKey.DOWN,
GamepadKey.LEFT,
GamepadKey.RIGHT,
GamepadKey.A,
GamepadKey.B,
GamepadKey.LB,
GamepadKey.RB,
GamepadKey.LT,
GamepadKey.RT,
GamepadKey.A, GamepadKey.B,
GamepadKey.X, GamepadKey.Y,
GamepadKey.UP, GamepadKey.RIGHT,
GamepadKey.DOWN, GamepadKey.LEFT,
GamepadKey.LB, GamepadKey.RB,
GamepadKey.LT, GamepadKey.RT,
GamepadKey.L3, GamepadKey.R3,
GamepadKey.SELECT, GamepadKey.START,
];
private static readonly GAMEPAD_DIRECTION_MAP = {
@ -171,61 +175,21 @@ export class NavigationDialogManager {
window.addEventListener(BxEvent.XCLOUD_GUIDE_MENU_SHOWN, e => this.hide());
// Calculate minimum width of controller-friendly <select> elements
if (getPref(PrefKey.UI_CONTROLLER_FRIENDLY)) {
const observer = new MutationObserver(mutationList => {
if (mutationList.length === 0 || mutationList[0].addedNodes.length === 0) {
return;
}
// Get dialog
const $dialog = mutationList[0].addedNodes[0];
if (!$dialog || !($dialog instanceof HTMLElement)) {
return;
}
// Find un-calculated <select> elements
this.calculateSelectBoxes($dialog);
});
observer.observe(this.$container, { childList: true });
}
}
calculateSelectBoxes($root: HTMLElement) {
const selects = Array.from($root.querySelectorAll('.bx-select:not([data-calculated]) select'));
for (const $select of selects) {
const $parent = $select.parentElement! as HTMLElement;
// Don't apply to select.bx-full-width elements
if ($parent.classList.contains('bx-full-width')) {
$parent.dataset.calculated = 'true';
const observer = new MutationObserver(mutationList => {
if (mutationList.length === 0 || mutationList[0].addedNodes.length === 0) {
return;
}
const rect = $select.getBoundingClientRect();
let $label: HTMLElement;
let width = Math.ceil(rect.width);
if (!width) {
// Get dialog
const $dialog = mutationList[0].addedNodes[0];
if (!$dialog || !($dialog instanceof HTMLElement)) {
return;
}
if (($select as HTMLSelectElement).multiple) {
$label = $parent.querySelector<HTMLElement>('.bx-select-value')!;
width += 20; // Add checkbox's width
} else {
$label = $parent.querySelector<HTMLElement>('div')!;
}
// Reduce width if it has <optgroup>
if ($select.querySelector('optgroup')) {
width -= 15;
}
// Set min-width
$label.style.minWidth = width + 'px';
$parent.dataset.calculated = 'true';
};
// Find un-calculated <select> elements
calculateSelectBoxes($dialog);
});
observer.observe(this.$container, { childList: true });
}
private updateActiveInput(input: 'keyboard' | 'gamepad' | 'mouse') {
@ -368,7 +332,7 @@ export class NavigationDialogManager {
}
this.clearGamepadHoldingInterval();
}, 200);
}, 100);
}
continue;
}
@ -417,8 +381,13 @@ export class NavigationDialogManager {
if (document.activeElement instanceof HTMLInputElement && document.activeElement.type === 'range') {
const $range = document.activeElement;
if (direction === NavigationDirection.LEFT || direction === NavigationDirection.RIGHT) {
$range.value = (parseInt($range.value) + parseInt($range.step) * (direction === NavigationDirection.LEFT ? -1 : 1)).toString();
$range.dispatchEvent(new InputEvent('input'));
const $numberStepper = $range.closest('.bx-number-stepper') as BxNumberStepper;
if ($numberStepper) {
BxNumberStepper.change.call($numberStepper, direction === NavigationDirection.LEFT ? 'dec' : 'inc');
} else {
$range.value = (parseInt($range.value) + parseInt($range.step) * (direction === NavigationDirection.LEFT ? -1 : 1)).toString();
$range.dispatchEvent(new InputEvent('input'));
}
handled = true;
}
}
@ -439,10 +408,10 @@ export class NavigationDialogManager {
show(dialog: NavigationDialog, configs={}, clearStack=false) {
this.clearGamepadHoldingInterval();
BxEvent.dispatch(window, BxEvent.XCLOUD_DIALOG_SHOWN);
BxEventBus.Script.emit('dialog.shown', {});
// Stop xCloud's navigation polling
(window as any).BX_EXPOSED.disableGamepadPolling = true;
window.BX_EXPOSED.disableGamepadPolling = true;
// Lock scroll bar
document.body.classList.add('bx-no-scroll');
@ -475,11 +444,14 @@ export class NavigationDialogManager {
hide() {
this.clearGamepadHoldingInterval();
if (!this.isShowing()) {
return;
}
// Unlock scroll bar
document.body.classList.remove('bx-no-scroll');
BxEvent.dispatch(window, BxEvent.XCLOUD_DIALOG_DISMISSED);
BxEventBus.Script.emit('dialog.dismissed', {});
// Hide content
this.$overlay.classList.add('bx-gone');
@ -504,7 +476,7 @@ export class NavigationDialogManager {
this.unmountCurrentDialog();
// Enable xCloud's navigation polling
(window as any).BX_EXPOSED.disableGamepadPolling = false;
window.BX_EXPOSED.disableGamepadPolling = false;
// Show the last dialog in dialogs stack
if (this.dialogsStack.length) {
@ -575,6 +547,16 @@ export class NavigationDialogManager {
const nearby = ($target as NavigationElement).nearby || {};
const orientation = this.getOrientation($target)!;
if (nearby[NavigationDirection.UP] && direction === NavigationDirection.UP) {
return nearby[NavigationDirection.UP];
} else if (nearby[NavigationDirection.DOWN] && direction === NavigationDirection.DOWN) {
return nearby[NavigationDirection.DOWN];
} else if (nearby[NavigationDirection.LEFT] && direction === NavigationDirection.LEFT) {
return nearby[NavigationDirection.LEFT];
} else if (nearby[NavigationDirection.RIGHT] && direction === NavigationDirection.RIGHT) {
return nearby[NavigationDirection.RIGHT];
}
// @ts-ignore
let siblingProperty = (NavigationDialogManager.SIBLING_PROPERTY_MAP[orientation])[direction];
if (siblingProperty) {
@ -661,7 +643,9 @@ export class NavigationDialogManager {
private startGamepadPolling() {
this.stopGamepadPolling();
this.gamepadPollingIntervalId = window.setInterval(this.pollGamepad, NavigationDialogManager.GAMEPAD_POLLING_INTERVAL);
if (isFullVersion()) {
this.gamepadPollingIntervalId = window.setInterval(this.pollGamepad, NavigationDialogManager.GAMEPAD_POLLING_INTERVAL);
}
}
private stopGamepadPolling() {

View File

@ -5,6 +5,7 @@ import { t } from "@/utils/translation";
import type { AllPresets, PresetRecord } from "@/types/presets";
import type { BasePresetsTable } from "@/utils/local-db/base-presets-table";
import { BxSelectElement } from "@/web-components/bx-select";
import { BxEvent } from "@/utils/bx-event";
export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends NavigationDialog {
$container!: HTMLElement;
@ -12,17 +13,17 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
private title: string;
protected presetsDb: BasePresetsTable<T>;
protected allPresets!: AllPresets<T>;
protected currentPresetId: number = 0;
protected currentPresetId: number | null = null;
protected activatedPresetId: number | null = null;
private $presets!: HTMLSelectElement;
private $header!: HTMLElement;
private $defaultNote!: HTMLElement;
protected $content!: HTMLElement;
private $btnRename!: HTMLButtonElement;
private $btnDelete!: HTMLButtonElement;
protected abstract readonly BLANK_PRESET_DATA: T['data'];
constructor(title: string, presetsDb: BasePresetsTable<T>) {
super();
@ -31,20 +32,24 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
}
protected abstract switchPreset(id: number): void;
async renderSummary(presetId: number): Promise<HTMLElement | DocumentFragment | null> {
return null;
}
protected updateButtonStates() {
const isDefaultPreset = this.currentPresetId <= 0;
const isDefaultPreset = this.currentPresetId === null || this.currentPresetId <= 0;
this.$btnRename.disabled = isDefaultPreset;
this.$btnDelete.disabled = isDefaultPreset;
this.$defaultNote.classList.toggle('bx-gone', !isDefaultPreset);
}
private async renderPresetsList() {
this.allPresets = await this.presetsDb.getPresets();
if (!this.currentPresetId) {
this.currentPresetId = this.allPresets.default[0];
if (this.currentPresetId === null) {
this.currentPresetId = this.allPresets.default[0];
}
renderPresetsList<T>(this.$presets, this.allPresets, this.currentPresetId);
renderPresetsList<T>(this.$presets, this.allPresets, this.activatedPresetId, { selectedIndicator: true });
}
private promptNewName(action: string,value='') {
@ -61,10 +66,12 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
};
private async renderDialog() {
this.$presets = CE<HTMLSelectElement>('select', { tabindex: -1 });
this.$presets = CE('select', {
class: 'bx-full-width',
tabindex: -1,
});
const $select = BxSelectElement.create(this.$presets);
$select.classList.add('bx-full-width');
$select.addEventListener('input', e => {
this.switchPreset(parseInt(($select as HTMLSelectElement).value));
});
@ -84,7 +91,7 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
icon: BxIcon.CURSOR_TEXT,
style: ButtonStyle.FOCUSABLE,
onClick: async () => {
const preset = this.allPresets.data[this.currentPresetId];
const preset = this.allPresets.data[this.currentPresetId!];
const newName = this.promptNewName(t('rename'), preset.name);
if (!newName) {
@ -109,8 +116,8 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
return;
}
await this.presetsDb.deletePreset(this.currentPresetId);
delete this.allPresets.data[this.currentPresetId];
await this.presetsDb.deletePreset(this.currentPresetId!);
delete this.allPresets.data[this.currentPresetId!];
this.currentPresetId = parseInt(Object.keys(this.allPresets.data)[0]);
await this.refresh();
@ -121,7 +128,7 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
createButton({
icon: BxIcon.NEW,
title: t('new'),
style: ButtonStyle.FOCUSABLE,
style: ButtonStyle.FOCUSABLE | ButtonStyle.PRIMARY,
onClick: async (e) => {
const newName = this.promptNewName(t('new'));
if (!newName) {
@ -129,7 +136,7 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
}
// Create new preset selected name
const newId = await this.presetsDb.newPreset(newName, this.BLANK_PRESET_DATA);
const newId = await this.presetsDb.newPreset(newName, this.presetsDb.BLANK_PRESET_DATA);
this.currentPresetId = newId;
await this.refresh();
@ -140,9 +147,9 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
createButton({
icon: BxIcon.COPY,
title: t('copy'),
style: ButtonStyle.FOCUSABLE,
style: ButtonStyle.FOCUSABLE | ButtonStyle.PRIMARY,
onClick: async (e) => {
const preset = this.allPresets.data[this.currentPresetId];
const preset = this.allPresets.data[this.currentPresetId!];
const newName = this.promptNewName(t('copy'), `${preset.name} (2)`);
if (!newName) {
@ -161,26 +168,43 @@ export abstract class BaseProfileManagerDialog<T extends PresetRecord> extends N
this.$container = CE('div', { class: 'bx-centered-dialog' },
CE('div', { class: 'bx-dialog-title' },
CE('p', {}, this.title),
CE('p', false, this.title),
createButton({
icon: BxIcon.CLOSE,
style: ButtonStyle.FOCUSABLE | ButtonStyle.CIRCULAR | ButtonStyle.GHOST,
onClick: e => this.hide(),
}),
),
$header,
CE('div', { class: 'bx-dialog-content bx-hide-scroll-bar' }, this.$content),
CE('div', false,
$header,
this.$defaultNote = CE('div', { class: 'bx-default-preset-note bx-gone' }, t('default-preset-note')),
),
CE('div', { class: 'bx-dialog-content' }, this.$content),
);
}
async refresh() {
await this.renderPresetsList();
this.switchPreset(this.currentPresetId);
this.$presets.value = this.currentPresetId!.toString();
BxEvent.dispatch(this.$presets, 'input', { manualTrigger: true });
}
async onBeforeMount(configs:{ id?: number }={}) {
if (configs?.id) {
this.currentPresetId = configs.id;
await this.renderPresetsList();
let valid = false;
if (typeof configs?.id === 'number') {
if (configs.id in this.allPresets.data) {
this.currentPresetId = configs.id;
this.activatedPresetId = configs.id;
valid = true;
}
}
// Invalid selected ID => get default ID;
if (!valid) {
this.currentPresetId = this.allPresets.default[0];
this.activatedPresetId = null;
}
// Select first preset

View File

@ -0,0 +1,413 @@
import type { ControllerCustomizationPresetData, ControllerCustomizationPresetRecord } from "@/types/presets";
import { BaseProfileManagerDialog } from "./base-profile-manager-dialog";
import { ControllerCustomizationsTable } from "@/utils/local-db/controller-customizations-table";
import { t } from "@/utils/translation";
import { GamepadKey, GamepadKeyName } from "@/enums/gamepad";
import { ButtonStyle, CE, createButton, createSettingRow } from "@/utils/html";
import { BxSelectElement } from "@/web-components/bx-select";
import { GlobalPref } from "@/enums/pref-keys";
import { getGlobalPref } from "@/utils/pref-utils";
import { BxEvent } from "@/utils/bx-event";
import { deepClone } from "@/utils/global";
import { StreamSettings } from "@/utils/stream-settings";
import { BxDualNumberStepper } from "@/web-components/bx-dual-number-stepper";
import { NavigationDirection, type NavigationElement } from "../navigation-dialog";
import { setNearby } from "@/utils/navigation-utils";
import type { DualNumberStepperParams } from "@/types/setting-definition";
import { BxNumberStepper } from "@/web-components/bx-number-stepper";
import { getGamepadPrompt } from "@/utils/gamepad";
export class ControllerCustomizationsManagerDialog extends BaseProfileManagerDialog<ControllerCustomizationPresetRecord> {
private static instance: ControllerCustomizationsManagerDialog;
public static getInstance = () => ControllerCustomizationsManagerDialog.instance ?? (ControllerCustomizationsManagerDialog.instance = new ControllerCustomizationsManagerDialog(t('controller-customization')));
declare protected $content: HTMLElement;
private $vibrationIntensity!: BxNumberStepper;
private $leftTriggerRange!: BxDualNumberStepper;
private $rightTriggerRange!: BxDualNumberStepper;
private $leftStickDeadzone!: BxDualNumberStepper;
private $rightStickDeadzone!: BxDualNumberStepper;
private $btnDetect!: HTMLButtonElement;
private selectsMap: PartialRecord<GamepadKey, HTMLSelectElement> = {};
private selectsOrder: GamepadKey[] = [];
private isDetectingButton: boolean = false;
private detectIntervalId: number | null = null;
static readonly BUTTONS_ORDER = [
GamepadKey.A, GamepadKey.B,
GamepadKey.X, GamepadKey.Y,
GamepadKey.UP, GamepadKey.RIGHT,
GamepadKey.DOWN, GamepadKey.LEFT,
GamepadKey.LB, GamepadKey.RB,
GamepadKey.LT, GamepadKey.RT,
GamepadKey.L3, GamepadKey.R3,
GamepadKey.LS, GamepadKey.RS,
GamepadKey.SELECT, GamepadKey.START,
GamepadKey.SHARE,
];
constructor(title: string) {
super(title, ControllerCustomizationsTable.getInstance());
this.render();
}
private render() {
const isControllerFriendly = getGlobalPref(GlobalPref.UI_CONTROLLER_FRIENDLY);
const $rows = CE('div', { class: 'bx-buttons-grid' });
const $baseSelect = CE('select', { class: 'bx-full-width' },
CE('option', { value: '' }, '---'),
CE('option', { value: 'false', _dataset: { label: '🚫' } }, isControllerFriendly ? '🚫' : t('off')),
);
const $baseButtonSelect = $baseSelect.cloneNode(true);
const $baseStickSelect = $baseSelect.cloneNode(true);
const onButtonChanged = (e: Event) => {
// Update preset
if (!(e as any).ignoreOnChange) {
this.updatePreset();
}
};
const boundUpdatePreset = this.updatePreset.bind(this);
for (const gamepadKey of ControllerCustomizationsManagerDialog.BUTTONS_ORDER) {
if (gamepadKey === GamepadKey.SHARE) {
continue;
}
const name = GamepadKeyName[gamepadKey][isControllerFriendly ? 1 : 0];
const $target = (gamepadKey === GamepadKey.LS || gamepadKey === GamepadKey.RS) ? $baseStickSelect : $baseButtonSelect;
$target.appendChild(CE('option', {
value: gamepadKey,
_dataset: { label: GamepadKeyName[gamepadKey][1] },
}, name));
}
for (const gamepadKey of ControllerCustomizationsManagerDialog.BUTTONS_ORDER) {
const [buttonName, buttonPrompt] = GamepadKeyName[gamepadKey];
const $sourceSelect = (gamepadKey === GamepadKey.LS || gamepadKey === GamepadKey.RS) ? $baseStickSelect : $baseButtonSelect;
// Remove current button from selection
const $clonedSelect = $sourceSelect.cloneNode(true) as HTMLSelectElement;
$clonedSelect.querySelector(`option[value="${gamepadKey}"]`)?.remove();
const $select = BxSelectElement.create($clonedSelect);
$select.dataset.index = gamepadKey.toString();
$select.addEventListener('input', onButtonChanged);
this.selectsMap[gamepadKey] = $select;
this.selectsOrder.push(gamepadKey);
const $row = CE('div', {
class: 'bx-controller-key-row',
_nearby: { orientation: 'horizontal' },
},
CE('label', { title: buttonName }, buttonPrompt),
$select,
);
$rows.append($row);
}
// Map nearby elenemts for controller-friendly UI
if (getGlobalPref(GlobalPref.UI_CONTROLLER_FRIENDLY)) {
for (let i = 0; i < this.selectsOrder.length; i++) {
const $select = this.selectsMap[this.selectsOrder[i] as unknown as GamepadKey] as NavigationElement;
const directions = {
[NavigationDirection.UP]: i - 2,
[NavigationDirection.DOWN]: i + 2,
[NavigationDirection.LEFT]: i - 1,
[NavigationDirection.RIGHT]: i + 1,
};
for (const dir in directions) {
const idx = directions[dir as unknown as NavigationDirection];
if (typeof this.selectsOrder[idx] === 'undefined') {
continue;
}
const $targetSelect = this.selectsMap[this.selectsOrder[idx] as unknown as GamepadKey];
setNearby($select, {
[dir]: $targetSelect,
});
}
}
}
const blankSettings = this.presetsDb.BLANK_PRESET_DATA.settings;
const params: DualNumberStepperParams = {
min: 0,
minDiff: 1,
max: 100,
steps: 1,
};
this.$content = CE('div', { class: 'bx-controller-customizations-container' },
// Detect button
this.$btnDetect = createButton({
label: t('detect-controller-button'),
classes: ['bx-btn-detect'],
style: ButtonStyle.NORMAL_CASE | ButtonStyle.FOCUSABLE | ButtonStyle.FULL_WIDTH,
onClick: () => {
this.startDetectingButton();
},
}),
// Mapping
$rows,
// Vibration intensity
createSettingRow(t('vibration-intensity'),
this.$vibrationIntensity = BxNumberStepper.create('controller_vibration_intensity', 50, 0, 100, {
steps: 10,
suffix: '%',
exactTicks: 20,
customTextValue: (value: any) => {
value = parseInt(value);
return value === 0 ? t('off') : value + '%';
},
}, boundUpdatePreset),
),
// Range settings
createSettingRow(t('left-trigger-range'),
this.$leftTriggerRange = BxDualNumberStepper.create('left-trigger-range', blankSettings.leftTriggerRange!, params, boundUpdatePreset),
),
createSettingRow(t('right-trigger-range'),
this.$rightTriggerRange = BxDualNumberStepper.create('right-trigger-range', blankSettings.rightTriggerRange!, params, boundUpdatePreset),
),
createSettingRow(t('left-stick-deadzone'),
this.$leftStickDeadzone = BxDualNumberStepper.create('left-stick-deadzone', blankSettings.leftStickDeadzone!, params, boundUpdatePreset),
),
createSettingRow(t('right-stick-deadzone'),
this.$rightStickDeadzone = BxDualNumberStepper.create('right-stick-deadzone', blankSettings.rightStickDeadzone!, params, boundUpdatePreset),
),
);
}
private startDetectingButton() {
this.isDetectingButton = true;
const { $btnDetect } = this;
$btnDetect.classList.add('bx-monospaced', 'bx-blink-me');
$btnDetect.disabled = true;
let count = 4;
$btnDetect.textContent = `[${count}] ${t('press-any-button')}`;
this.detectIntervalId = window.setInterval(() => {
count -= 1;
if (count === 0) {
this.stopDetectingButton();
// Re-focus the Detect button
$btnDetect.focus();
return;
}
$btnDetect.textContent = `[${count}] ${t('press-any-button')}`;
}, 1000);
}
private stopDetectingButton() {
const { $btnDetect } = this;
$btnDetect.classList.remove('bx-monospaced', 'bx-blink-me');
$btnDetect.textContent = t('detect-controller-button');
$btnDetect.disabled = false;
this.isDetectingButton = false;
this.detectIntervalId && window.clearInterval(this.detectIntervalId);
this.detectIntervalId = null;
}
async onBeforeMount() {
this.stopDetectingButton();
super.onBeforeMount(...arguments);
}
onBeforeUnmount(): void {
this.stopDetectingButton();
StreamSettings.refreshControllerSettings();
super.onBeforeUnmount();
}
handleGamepad(button: GamepadKey): boolean {
if (!this.isDetectingButton) {
return super.handleGamepad(button);
}
if (button in ControllerCustomizationsManagerDialog.BUTTONS_ORDER) {
this.stopDetectingButton();
const $select = this.selectsMap[button]!;
const $label = $select.previousElementSibling!;
$label.addEventListener('animationend', () => {
$label.classList.remove('bx-horizontal-shaking');
}, { once: true });
$label.classList.add('bx-horizontal-shaking');
// Focus select
if (getGlobalPref(GlobalPref.UI_CONTROLLER_FRIENDLY)) {
this.dialogManager.focus($select);
}
}
return true;
}
protected switchPreset(id: number): void {
const preset = this.allPresets.data[id];
if (!preset) {
this.currentPresetId = 0;
return;
}
const {
$btnDetect,
$vibrationIntensity,
$leftStickDeadzone,
$rightStickDeadzone,
$leftTriggerRange,
$rightTriggerRange,
selectsMap,
} = this;
const presetData = preset.data;
this.currentPresetId = id;
const isDefaultPreset = id <= 0;
this.updateButtonStates();
// Show/hide Detect button
$btnDetect.classList.toggle('bx-gone', isDefaultPreset);
// Set mappings
let buttonIndex: unknown;
for (buttonIndex in selectsMap) {
buttonIndex = buttonIndex as GamepadKey;
const $select = selectsMap[buttonIndex as GamepadKey];
if (!$select) {
continue;
}
const mappedButton = presetData.mapping[buttonIndex as GamepadKey];
$select.value = typeof mappedButton === 'undefined' ? '' : mappedButton.toString();
$select.disabled = isDefaultPreset;
BxEvent.dispatch($select, 'input', {
ignoreOnChange: true,
manualTrigger: true,
});
}
// Add missing settings
presetData.settings = Object.assign({}, this.presetsDb.BLANK_PRESET_DATA.settings, presetData.settings);
// Vibration intensity
$vibrationIntensity.value = presetData.settings.vibrationIntensity.toString();
$vibrationIntensity.dataset.disabled = isDefaultPreset.toString();
// Set extra settings
$leftStickDeadzone.dataset.disabled = $rightStickDeadzone.dataset.disabled = $leftTriggerRange.dataset.disabled = $rightTriggerRange.dataset.disabled = isDefaultPreset.toString();
$leftStickDeadzone.setValue(presetData.settings.leftStickDeadzone);
$rightStickDeadzone.setValue(presetData.settings.rightStickDeadzone);
$leftTriggerRange.setValue(presetData.settings.leftTriggerRange);
$rightTriggerRange.setValue(presetData.settings.rightTriggerRange);
}
private updatePreset() {
const newData: ControllerCustomizationPresetData = deepClone(this.presetsDb.BLANK_PRESET_DATA);
// Set mappings
let gamepadKey: unknown;
for (gamepadKey in this.selectsMap) {
const $select = this.selectsMap[gamepadKey as GamepadKey]!;
const value = $select.value;
if (!value) {
continue;
}
const mapTo = (value === 'false') ? false : parseInt(value);
newData.mapping[gamepadKey as GamepadKey] = mapTo;
}
// Set extra settings
Object.assign(newData.settings, {
vibrationIntensity: parseInt(this.$vibrationIntensity.value),
leftStickDeadzone: this.$leftStickDeadzone.getValue(),
rightStickDeadzone: this.$rightStickDeadzone.getValue(),
leftTriggerRange: this.$leftTriggerRange.getValue(),
rightTriggerRange: this.$rightTriggerRange.getValue(),
} satisfies typeof newData.settings);
// Update preset
const preset = this.allPresets.data[this.currentPresetId!];
preset.data = newData;
this.presetsDb.updatePreset(preset);
}
async renderSummary(presetId: number) {
const preset = await this.presetsDb.getPreset(presetId);
if (!preset) {
return null;
}
const presetData = preset.data;
let $content: HTMLElement | undefined;
let showNote = false;
if (Object.keys(presetData.mapping).length > 0) {
$content = CE('div', { class: 'bx-controller-customization-summary'});
for (const gamepadKey of ControllerCustomizationsManagerDialog.BUTTONS_ORDER) {
if (!(gamepadKey in presetData.mapping)) {
continue;
}
const mappedKey = presetData.mapping[gamepadKey]!;
$content.append(CE('span', { class: 'bx-prompt' }, getGamepadPrompt(gamepadKey) + ' > ' + (mappedKey === false ? '🚫' : getGamepadPrompt(mappedKey))));
}
showNote = true;
}
// Show note if it has settings other than 'vibrationIntensity'
let key: keyof typeof presetData.settings;
for (key in presetData.settings) {
if (key === 'vibrationIntensity') {
continue;
}
const value = presetData.settings[key];
// Non-default value
if (Array.isArray(value) && (value[0] !== 0 || value[1] !== 100)) {
showNote = true;
break;
}
}
const fragment = document.createDocumentFragment();
if (showNote) {
const $note = CE('div', { class: 'bx-settings-dialog-note' }, 'ⓘ ' + t('controller-customization-input-latency-note'));
fragment.appendChild($note);
}
if ($content) {
fragment.appendChild($content);
}
return fragment.childElementCount ? fragment : null;
}
}

Some files were not shown because too many files have changed in this diff Show More