Compare commits

...

232 Commits

Author SHA1 Message Date
5d177bd76c Fix "guideAchievementsDefaultLocked" patch 2024-11-18 22:01:24 +07:00
f18c5c14ed Bump version to 5.9.5 2024-11-06 19:22:07 +07:00
d0ceed00f8 Add "Server locations" link 2024-11-06 19:21:38 +07:00
fce8af4b3b Fix custom buttons disappearing in Guide Menu (#551) 2024-11-06 07:36:32 +07:00
57686f9d8e Bump version to 5.9.4 2024-11-01 20:08:15 +07:00
f0e7272a82 Use "brand" instead of "manufacturer" 2024-11-01 19:57:08 +07:00
b0ecc7171b Update device suggestion URL 2024-11-01 19:52:25 +07:00
17c08792e1 Redirect to /en-US/play if visiting from an unsupported region 2024-11-01 17:02:30 +07:00
e8376b52fe Add patch to modify __PRELOADED_STATE__ 2024-11-01 16:55:58 +07:00
f6581abe34 Show "Remote Play" on web's title instead of "Fortnite" 2024-11-01 08:53:24 +07:00
b090d325ae Migrate PatcherCache to singleton class 2024-11-01 07:22:21 +07:00
ec3daa09fd Use hash of client.js file for calculating patch's signature 2024-11-01 07:16:11 +07:00
b2a2e4d27e Add in-game language support for Bulgarian, Romanian and Thai 2024-10-30 08:45:59 +07:00
4f3430c43c Bump version to 5.9.3 2024-10-29 20:35:15 +07:00
15c6d3c74b Update dists 2024-10-29 20:24:04 +07:00
b170b95145 Fix bugs in NumberStepper 2024-10-29 20:20:34 +07:00
4217b89194 Reduce the amount of event listeners in NumberStepper 2024-10-29 20:11:54 +07:00
38211168e9 Reduce width of controller-friendly select box if it has <optgroup> 2024-10-29 16:56:34 +07:00
392dc2cf86 Categorize servers by continents 2024-10-29 16:51:29 +07:00
67de264aa9 Revert "Use gl.texSubImage2D()"
This reverts commit 3e2c1bb2a4.
2024-10-27 10:20:11 +07:00
3e2c1bb2a4 Use gl.texSubImage2D() 2024-10-27 09:36:34 +07:00
5653914d19 Move WebGL2's drawFrame() function to animate() function 2024-10-26 21:53:03 +07:00
4a8f66f2a1 Upgrade bun 2024-10-25 08:59:05 +07:00
70f43ba8f2 Add emoji flag for SwedenCentral server 2024-10-25 07:33:35 +07:00
4d49639622 Bump version to 5.9.2 2024-10-24 20:58:53 +07:00
22f1ebdd08 Fix Remote Play not working when using different network (#538) 2024-10-24 20:38:01 +07:00
bae51eff3d Bump version to 5.9.1 2024-10-23 21:09:26 +07:00
adc9897210 Update translations 2024-10-23 21:08:20 +07:00
53442557e1 Fix Virtual Controller Remapper's bug (contd) 2024-10-23 20:51:04 +07:00
5b67b4c37d Fix Virtual Controller Remapper's bug (contd) 2024-10-23 20:14:10 +07:00
5a06933143 Update dists 2024-10-23 20:03:26 +07:00
6440c91cdf Fix Virtual Controller Remapper's bug 2024-10-23 20:00:27 +07:00
b06dc6e219 Update polling rate's default text 2024-10-22 20:47:45 +07:00
540a50fb3a Bump version to 5.9.0 2024-10-22 20:14:16 +07:00
e5178830cb Update translations 2024-10-22 20:13:59 +07:00
75549bc477 Update dists 2024-10-22 20:08:18 +07:00
8a3d48d4a3 Optimize Game slug generator by using cached RegEx 2024-10-22 20:07:26 +07:00
33c3b2810a Update NumberStepper 2024-10-22 16:52:23 +07:00
95881dd241 Upgrade bun 2024-10-22 16:49:47 +07:00
c89ebb78a4 Update dists 2024-10-22 10:43:14 +07:00
222ad1c34e Remove "disableSendMetadata" patch 2024-10-22 10:42:43 +07:00
6cfff0274d Replace forEach() with for() 2024-10-22 10:42:09 +07:00
01502363ab Add "disableSendMetadata" patch 2024-10-22 09:14:11 +07:00
9ab63c4a53 Update polling rate in controller-shortcut.js 2024-10-21 22:16:18 +07:00
89a968d688 Update dists 2024-10-21 22:01:53 +07:00
5e98c756d4 Add Polling rate setting 2024-10-21 22:01:32 +07:00
831fd98d02 Remove CONTROLLER_ENABLE_SHORTCUTS 2024-10-21 20:53:27 +07:00
de76364a46 Optimize + refactor code 2024-10-21 20:50:12 +07:00
075b15aa48 Update better-xcloud.user.js 2024-10-21 17:16:45 +07:00
9388d7fbf4 Update better-xcloud.user.js 2024-10-21 11:04:44 +07:00
2d8361ba73 Update better-xcloud.user.js 2024-10-21 08:15:49 +07:00
79c7af10d4 Update better-xcloud.user.js 2024-10-20 21:33:05 +07:00
6bd658e8a6 Bump version to 5.8.6 2024-10-19 18:54:12 +07:00
7e6b89b357 Typo 2024-10-19 18:53:49 +07:00
4271583a5a Add MINIFY_SYNTAX flag in build.ts 2024-10-19 18:46:13 +07:00
1b2cf70248 Minor fix 2024-10-19 18:40:59 +07:00
87447df7fd Fix Server badge not updating between sessions 2024-10-19 18:40:47 +07:00
8664c1a60f Fix taking screenshot not working when limiting FPS 2024-10-19 18:04:05 +07:00
602c31dc7f Update dist 2024-10-19 16:56:02 +07:00
bbaea5f629 Fix Game Bar keep clearing focus even when not playing 2024-10-19 16:54:21 +07:00
03efa528c8 Android: add Shortcut & Wallpaper menu to Game Card's context menu 2024-10-19 16:53:55 +07:00
63aaca7d61 Fix crashing in "disableTouchContextMenu" patch 2024-10-18 22:19:06 +07:00
15ae88e9e6 Disable long touch activating context menu 2024-10-18 21:50:22 +07:00
7578671cc3 Remove "ui_home_context_menu_disabled" setting as it's no longer needed 2024-10-18 21:41:21 +07:00
82cfb11a6d Update dist 2024-10-18 17:32:08 +07:00
15700e736d Fix "Smart TV" User-Agent profile (#527) 2024-10-18 16:57:32 +07:00
b27cfc8215 Refactor utils/html 2024-10-18 16:54:29 +07:00
1e644504ec Upgrade bun 2024-10-18 16:52:41 +07:00
7206d11825 Test: hide <video> when using WebGL2 renderer 2024-10-17 20:19:27 +07:00
fa19a5a68e Bump version to 5.8.5 2024-10-15 19:48:18 +07:00
3f834f74b6 Update "skipFeedbackDialog" patch 2024-10-15 16:49:38 +07:00
749d5d720e Update dist 2024-10-14 21:08:35 +07:00
b969d52a3c Show max FPS value in Stats bar 2024-10-14 21:06:52 +07:00
e5bd7e64a7 Refactor xCloud & xHome interceptors 2024-10-14 20:08:47 +07:00
82ee00b4ae Update dist 2024-10-14 17:17:32 +07:00
8e88af5f8c Set indent of built scripts to 1 space 2024-10-14 17:14:43 +07:00
927eae3f2f Refactor getInstance() methods 2024-10-14 16:56:05 +07:00
9f440e9cf4 Don't call animate() when hiding renderer 2024-10-14 16:47:03 +07:00
1acb30e3af Refactor Game Bar 2024-10-14 16:45:57 +07:00
34159fad22 Update better-xcloud.lite.user.js 2024-10-13 20:04:42 +07:00
741538ebcf Bump version to 5.8.4 2024-10-13 20:00:36 +07:00
6d2e04aff1 Refactor Game Bar actions 2024-10-13 19:15:29 +07:00
f2bc98229f Update version 2024-10-13 17:46:48 +07:00
49fb8e2818 Refactor "data-enabled" to "data-activated" 2024-10-13 17:32:38 +07:00
d012d96675 Add Game Bar action to toggle renderer's visibility 2024-10-13 17:05:27 +07:00
c129feaf2d Refactor WebGL2Player 2024-10-13 16:26:33 +07:00
4f7b23912d Refactor BxLogger 2024-10-13 16:06:01 +07:00
e4d73f9e36 Replace "#" with "private" 2024-10-13 10:51:50 +07:00
2eea9ce8f5 Bump version to 5.8.3 2024-10-12 18:41:41 +07:00
27abab8473 Change "FPS" unit to "fps" 2024-10-12 18:41:28 +07:00
0c34173815 Add "Limit video player's FPS" feature 2024-10-12 16:15:51 +07:00
0164423e45 Test WebGL2 shader 2024-10-12 11:14:55 +07:00
71dcaf4b07 Optimize Clarity boost shader 2024-10-11 17:11:32 +07:00
8f49c48e74 Bump version to 5.8.2 2024-10-11 07:11:37 +07:00
6fa1f73702 Optimize built scripts 2024-10-10 21:43:42 +07:00
728abced45 Add jitter stat 2024-10-10 21:35:36 +07:00
411e43ceb0 Disable inputPollingDurationStats 2024-10-10 20:55:57 +07:00
baa22dbefc Optimize Clarity Boost shader 2024-10-10 17:28:19 +07:00
97fb7a114f Set Sharpness's suggested value to 2 2024-10-09 09:02:52 +07:00
39b2f814b6 Fix stream badge always show "IPv6" even when connecting to IPv4 server #517 2024-10-09 06:30:09 +07:00
3d34bb3edf Bump version to 5.8.1 2024-10-08 20:00:39 +07:00
ab1c93eb3a Upgrade bun 2024-10-08 19:59:53 +07:00
739adfce41 Update translations 2024-10-08 19:55:03 +07:00
2e77f19006 Update scripts 2024-10-08 07:19:20 +07:00
8a40d361d9 Add unsupportedNote property 2024-10-08 07:19:09 +07:00
98fa273b48 Don't render MKB settings on unsupported devices 2024-10-08 07:01:58 +07:00
1e6527413c Update scripts 2024-10-07 21:40:09 +07:00
b9134bc141 Add "MSFS2020: force native MKB support" setting 2024-10-07 21:39:42 +07:00
336a965653 Update translations 2024-10-07 21:21:37 +07:00
3a91210ba7 Bump version to 5.8.0 2024-10-06 20:35:56 +07:00
14f2d8a741 Upgrade bun 2024-10-06 20:35:08 +07:00
c24d1620b6 Update scripts 2024-10-06 20:34:25 +07:00
63f30111cb Update translations 2024-10-06 20:28:19 +07:00
d30a628fb1 Update scripts 2024-10-06 20:25:50 +07:00
5b80170c8b Fix Stream menu's grip handle 2024-10-06 20:20:11 +07:00
203346c0a1 Fix Quick glancing activated when using Touch control dialog 2024-10-06 20:16:08 +07:00
9719454ea1 Fix not hiding Stream menu's grip handle sometimes 2024-10-06 20:10:02 +07:00
59a178bb16 Fix Stats button in Stream menu not updating state 2024-10-06 20:01:53 +07:00
fd1494ebfa Remove Battery option in unsupported browser 2024-10-06 17:02:18 +07:00
8e6dec4b70 Update label's style in Stats bar 2024-10-06 16:15:52 +07:00
6e905621f6 Fix not able to click on checkbox in controller-friendly select box 2024-10-06 15:52:52 +07:00
76b205a65a New stats: clock, play time, battery, download, upload 2024-10-06 15:50:39 +07:00
af41dc7c5e Add build.sh 2024-10-05 10:41:18 +07:00
d0f43db1fd Bump version to 5.7.8 2024-10-02 21:24:23 +07:00
eed0aa9d9e Fix not disabling unsupported features in Settings dialog 2024-10-02 07:17:17 +07:00
9007663a3a Lite: remove NativeMkbHandler code in built script 2024-10-01 17:47:01 +07:00
8f6bc5cb1b Detach VIRTUAL_GAMEPAD_ID from EmulatedMkbHandler 2024-10-01 17:22:33 +07:00
12d8d766dc Lite: remove XhomeInterceptor and TouchController in built script 2024-10-01 17:09:07 +07:00
aeffccaf67 Update better-xcloud.lite.user.js 2024-10-01 16:51:44 +07:00
b2736d574d Disable PatcherCache in Lite version 2024-10-01 16:49:40 +07:00
98cf893956 Fix Settings dialog opening during gameplay 2024-09-30 17:18:40 +07:00
086afafedf Update dist 2024-09-30 17:12:22 +07:00
bd58355ef5 Create better-xcloud.lite.user.js 2024-09-30 17:11:05 +07:00
109cd63a7b Bump version to 5.7.7 2024-09-26 19:50:28 +07:00
8ea6b7f81a Update better-xcloud.user.js 2024-09-26 19:49:58 +07:00
e7c10d43f5 Fix buttons layout in product details page 2024-09-26 19:46:30 +07:00
2f7a57e084 Update translations 2024-09-26 19:22:51 +07:00
c99e38b097 Update better-xcloud.user.js 2024-09-25 20:20:45 +07:00
f6ec6d7c9b Fix not calculating controller-friendly <select>'s size when switching tab 2024-09-25 20:20:06 +07:00
e69fa19ef3 Update better-xcloud.user.js 2024-09-25 19:44:33 +07:00
cc422b31a4 build: collapse if/else blocks without curly braces 2024-09-25 19:43:19 +07:00
9609d0ae7b Fix duplicated CSS strings 2024-09-25 19:43:07 +07:00
506fd71433 Update better-xcloud.user.js 2024-09-25 08:48:57 +07:00
f40b8cb0b2 build: add more minify steps 2024-09-25 08:47:01 +07:00
49a6c036a3 Bump version to 5.7.6 2024-09-24 21:13:56 +07:00
f5a5a79a82 Check offscreen element in isElementVisible() 2024-09-24 20:58:32 +07:00
7ec449160a Update better-xcloud.user.js 2024-09-24 19:53:20 +07:00
fecc5411da Remote Play dialog: update styles 2024-09-24 19:53:02 +07:00
f704452171 Remote Play dialog: replace radio buttons with select box 2024-09-24 19:47:55 +07:00
135193813c Shorten language names 2024-09-24 19:34:20 +07:00
bb57f72e64 Calculate minimum width of controller-friendly <select> elements 2024-09-24 19:31:56 +07:00
69d7cbfffb Bump version to 5.7.5 2024-09-20 17:46:32 +07:00
92e6828cb2 Update better-xcloud.user.js 2024-09-20 17:25:12 +07:00
12ad81e9c7 Update translations 2024-09-20 17:16:32 +07:00
102e0bd318 Use "let" keyword in Patcher to reduce the size of generated script 2024-09-20 16:53:48 +07:00
9308963bc2 Remote Play: Prevent adding "Fortnite" to the "Jump back in" list 2024-09-20 16:42:27 +07:00
c90e013dc1 Upgrade bun 2024-09-20 16:42:03 +07:00
037927b9be Fix not able to control Remote Play dialog using controller (#509) 2024-09-20 07:05:39 +07:00
dabab9acb1 Bump version to 5.7.4 2024-09-19 19:59:12 +07:00
a4a52c6bc3 Update better-xcloud.user.js 2024-09-19 19:58:49 +07:00
eebd7434ea Remove Close icon in Remote Play dialog 2024-09-19 19:58:45 +07:00
ec1805f832 Refactor Remote Play 2024-09-19 18:01:27 +07:00
34f959d5ae Update better-xcloud.user.js 2024-09-18 20:15:02 +07:00
784a31ce43 Migrate Remote Play popup to Navigation dialog 2024-09-18 20:14:49 +07:00
df266d32fc Update better-xcloud.user.js 2024-09-12 22:03:35 +07:00
a6ccd6666e Check next Remote Play server when the console list is empty 2024-09-12 22:03:21 +07:00
fe609034d6 Remote Play: don't accept candidates with port 0 2024-09-11 08:24:50 +07:00
97ec29faa0 Upgrade bun 2024-09-11 08:09:27 +07:00
a34ae75131 Bump version to 5.7.3 2024-09-07 18:36:05 +07:00
139543aaa5 Update better-xcloud.user.js 2024-09-07 18:29:45 +07:00
8099115959 Set Achievements list's default filter to "Locked" 2024-09-07 18:15:04 +07:00
21efa5ffdc Minor fix in Game Bar 2024-09-07 17:27:23 +07:00
07ebf3926b Update script in app when clicking on the "Version x available" button 2024-09-07 16:43:56 +07:00
714178a82d Bump version to 5.7.2 2024-09-06 20:55:12 +07:00
5c2c13e0e6 Update better-xcloud.user.js 2024-09-06 20:52:35 +07:00
3f423325b9 Add Game Bar action to mute/unmute speaker (#491) 2024-09-06 20:44:28 +07:00
870a205ead Update better-xcloud.user.js 2024-09-06 18:17:39 +07:00
421af05882 Update TA button's logic & layout in the Guide Menu 2024-09-06 18:07:13 +07:00
756d105f74 Clear focus on Game Bar after activating it 2024-09-06 17:03:55 +07:00
4d90ebca68 Bump version to 5.7.1 2024-09-05 06:39:19 +07:00
1297230192 Update better-xcloud.user.js 2024-09-05 06:34:57 +07:00
a45d0f8b98 Update buttons layout in Guide Menu with TV layout (#492) 2024-09-05 06:34:30 +07:00
821904066b Fix no sound when using volume control feature (#490) 2024-09-05 06:17:23 +07:00
15b7869e5d Bump version to 5.7.0 2024-09-04 20:53:37 +07:00
2ed4e23c87 Update better-xcloud.user.js 2024-09-04 20:19:38 +07:00
e952bf07c8 Fix problem with "|" character in game title 2024-09-04 20:19:31 +07:00
8d44dab04d Update better-xcloud.user.js 2024-09-04 19:45:02 +07:00
6a792548fa Update TrueAchievements button in Guide Menu 2024-09-04 19:44:41 +07:00
29f6413306 Support suggesting boolean settings 2024-09-04 16:59:18 +07:00
53d67616c3 Fix not clearing states when quitting game while queueing 2024-09-04 16:43:39 +07:00
03ad02bd4d Don't show the "Close app" button in Guide Menu when playing 2024-09-04 16:42:52 +07:00
110106aa97 Update better-xcloud.user.js 2024-09-04 07:31:40 +07:00
7310700dbb Add button to download wallpapers in app 2024-09-03 19:56:34 +07:00
5a0ef88237 Update better-xcloud.user.js 2024-09-03 16:57:17 +07:00
a6e358479a Integrate TrueAchievements 2024-09-03 16:56:58 +07:00
4b02fec8ac Update better-xcloud.user.js 2024-09-03 16:50:32 +07:00
93e3f1fa49 Update better-xcloud.user.js 2024-09-03 10:19:43 +07:00
ae9a1a68d4 Update better-xcloud.user.js 2024-09-02 21:25:14 +07:00
adf6b05c10 Update better-xcloud.user.js 2024-09-02 21:18:32 +07:00
e0489d30bb Update better-xcloud.user.js 2024-09-02 20:22:08 +07:00
9f46eca956 Minify SVG in generated JS 2024-09-02 14:57:03 +07:00
4888c399f0 Upgrade bun 2024-09-02 10:44:36 +07:00
e372db8dd9 Update better-xcloud.user.js 2024-08-31 19:03:58 +07:00
5ba4a669e6 Compress Loading Screen's CSS 2024-08-31 19:02:36 +07:00
26b28564cc Optimize Guide Menu's buttons 2024-08-31 17:03:42 +07:00
ad0be634d2 Update better-xcloud.user.js 2024-08-31 10:25:58 +07:00
6f460302cf Fix Game Bar not showing sometimes 2024-08-31 09:57:49 +07:00
24f0cf18d9 Bump version to 5.6.1 2024-08-30 20:24:04 +07:00
2df8274233 Update better-xcloud.user.js 2024-08-30 20:18:18 +07:00
a095370ab8 Show the wait time of every games in the "Jump back in" section all at once 2024-08-30 20:04:40 +07:00
339447d29c Update Settings dialog's style 2024-08-30 20:04:11 +07:00
efe0caf02f Update better-xcloud.user.js 2024-08-29 21:34:17 +07:00
6daabea288 Add troubleshooting link 2024-08-29 21:30:27 +07:00
772a642283 Update translations 2024-08-29 21:03:42 +07:00
675fc8431c Don't build meta.js for beta version 2024-08-29 17:44:14 +07:00
9a97053662 Upgrade bun 2024-08-29 17:38:39 +07:00
9d6190668b Bump version to 5.6.0 2024-08-26 18:10:37 +07:00
ba0b804720 Update z-index 2024-08-26 17:49:45 +07:00
1fe1f74ad5 Update better-xcloud.user.js 2024-08-26 17:28:22 +07:00
4f7e0a4f7f Add "Suggest settings" feature 2024-08-26 17:27:34 +07:00
070113b764 Update better-xcloud.user.js 2024-08-26 07:52:38 +07:00
c669b80914 Update better-xcloud.user.js 2024-08-26 07:43:23 +07:00
1e8e7f0030 Update better-xcloud.user.js 2024-08-25 17:19:53 +07:00
edc26e366e Update better-xcloud.user.js 2024-08-25 16:02:03 +07:00
13bd258f2a Update better-xcloud.user.js 2024-08-25 10:10:11 +07:00
a1b6fc111c Update better-xcloud.user.js 2024-08-25 10:08:03 +07:00
366c7c8ea4 Update better-xcloud.user.js 2024-08-25 10:05:57 +07:00
7b5bb1e342 Update better-xcloud.user.js 2024-08-23 17:21:47 +07:00
131da53d25 Update better-xcloud.user.js 2024-08-22 07:37:15 +07:00
7ae90cb5b3 Update better-xcloud.user.js 2024-08-20 20:48:09 +07:00
812e2390d0 Update bun.lockb 2024-08-14 18:47:40 +07:00
4e133582e4 Bump version to 5.5.6 2024-08-14 18:47:13 +07:00
106 changed files with 19488 additions and 10850 deletions

16
build.sh Executable file
View File

@ -0,0 +1,16 @@
#!/bin/bash
build_all () {
# Clear screen
printf "\033c"
# Build all variants
bun build.ts --version $1 --variant full
bun build.ts --version $1 --variant lite
# Wait for key
read -p ">> Press Enter to build again..."
build_all $1
}
build_all $1

125
build.ts
View File

@ -5,6 +5,8 @@ import { sys } from "typescript";
// @ts-ignore
import txtScriptHeader from "./src/assets/header_script.txt" with { type: "text" };
// @ts-ignore
import txtScriptHeaderLite from "./src/assets/header_script.lite.txt" with { type: "text" };
// @ts-ignore
import txtMetaHeader from "./src/assets/header_meta.txt" with { type: "text" };
import { assert } from "node:console";
import { ESLint } from "eslint";
@ -16,6 +18,10 @@ enum BuildTarget {
WEBOS = 'webos',
}
type BuildVariant = 'full' | 'lite';
const MINIFY_SYNTAX = true;
const postProcess = (str: string): string => {
// Unescape unicode charaters
str = unescape((str.replace(/\\u/g, '%u')));
@ -35,6 +41,68 @@ const postProcess = (str: string): string => {
// Add ADDITIONAL CODE block
str = str.replace('var DEFAULT_FLAGS', '\n/* ADDITIONAL CODE */\n\nvar DEFAULT_FLAGS');
str = str.replaceAll('(e) => `', 'e => `');
// Simplify object definitions
// {[1]: "a"} => {1: "a"}
str = str.replaceAll(/\[(\d+)\]: /g, '$1: ');
// {["a"]: 1, ["b-c"]: 2} => {a: 1, "b-c": 2}
str = str.replaceAll(/\["([^"]+)"\]: /g, function(match, p1) {
if (p1.includes('-') || p1.match(/^\d/)) {
p1 = `"${p1}"`;
}
return p1 + ': ';
});
// Minify SVG import code
const svgMap = {}
str = str.replaceAll(/var ([\w_]+) = ("<svg.*?");\n\n/g, (match, p1, p2) => {
// Remove new lines in SVG
p2 = p2.replaceAll(/\\n*\s*/g, '');
svgMap[p1] = p2;
return '';
});
for (const name in svgMap) {
str = str.replace(`: ${name}`, `: ${svgMap[name]}`);
}
// Collapse empty brackets
str = str.replaceAll(/\{[\s\n]+\}/g, '{}');
// Remove blank lines
str = str.replaceAll(/\n([\s]*)\n/g, "\n");
// Minify WebGL shaders & JS strings
// Replace "\n " with "\n"
str = str.replaceAll(/\\n+\s*/g, '\\n');
// Remove comment line
str = str.replaceAll(/\\n\/\/.*?(?=\\n)/g, '');
// Replace ${"time".toUpperCase()} with "TIME"
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 = str.replaceAll(/\n(\s+)/g, (match, p1) => {
const len = p1.length / 2;
return '\n' + ' '.repeat(len);
});
}
// Fix unicode regex in Patcher.optimizeGameSlugGenerator
str = str.replaceAll('^\\™', '^\\\\u2122');
assert(str.includes('/* ADDITIONAL CODE */'));
assert(str.includes('window.BX_EXPOSED = BxExposed'));
assert(str.includes('window.BxEvent = BxEvent'));
@ -43,7 +111,7 @@ const postProcess = (str: string): string => {
return str;
}
const build = async (target: BuildTarget, version: string, config: any={}) => {
const build = async (target: BuildTarget, version: string, variant: BuildVariant, config: any={}) => {
console.log('-- Target:', target);
const startTime = performance.now();
@ -51,6 +119,11 @@ const build = async (target: BuildTarget, version: string, config: any={}) => {
if (target !== BuildTarget.ALL) {
outputScriptName += `.${target}`;
}
if (variant !== 'full') {
outputScriptName += `.${variant}`;
}
let outputMetaName = outputScriptName;
outputScriptName += '.user.js';
outputMetaName += '.meta.js';
@ -62,10 +135,11 @@ const build = async (target: BuildTarget, version: string, config: any={}) => {
outdir: outDir,
naming: outputScriptName,
minify: {
syntax: true,
syntax: MINIFY_SYNTAX,
},
define: {
'Bun.env.BUILD_TARGET': JSON.stringify(target),
'Bun.env.BUILD_VARIANT': JSON.stringify(variant),
'Bun.env.SCRIPT_VERSION': JSON.stringify(version),
},
});
@ -80,13 +154,21 @@ const build = async (target: BuildTarget, version: string, config: any={}) => {
let result = postProcess(await readFile(path, 'utf-8'));
// Replace [[VERSION]] with real value
const scriptHeader = txtScriptHeader.replace('[[VERSION]]', version);
let scriptHeader: string;
if (variant === 'full') {
scriptHeader = txtScriptHeader;
} else {
scriptHeader = txtScriptHeaderLite;
}
scriptHeader = scriptHeader.replace('[[VERSION]]', version);
// Save to script
await Bun.write(path, scriptHeader + result);
// Create meta file
await Bun.write(outDir + '/' + outputMetaName, txtMetaHeader.replace('[[VERSION]]', version));
// Create meta file (don't build if it's beta version)
if (!version.includes('beta') && variant === 'full') {
await Bun.write(outDir + '/' + outputMetaName, txtMetaHeader.replace('[[VERSION]]', version));
}
// Check with ESLint
const eslint = new ESLint();
@ -109,28 +191,44 @@ const buildTargets = [
const { values, positionals } = parseArgs({
args: Bun.argv,
options: {
version: {
type: 'string',
version: {
type: 'string',
},
},
variant: {
type: 'string',
default: 'full',
},
},
strict: true,
allowPositionals: true,
});
}) as {
values: {
version: string,
variant: BuildVariant,
},
positionals: string[],
};
if (!values['version']) {
console.log('Missing --version param');
sys.exit(-1);
}
if (values['variant'] !== 'full' && values['variant'] !== 'lite') {
console.log('--variant param must be either "full" or "lite"');
sys.exit(-1);
}
async function main() {
const config = {};
console.log('Building: ', values['version']);
console.log(`Building: VERSION=${values['version']}, VARIANT=${values['variant']}`);
for (const target of buildTargets) {
await build(target, values['version']!!, config);
await build(target, values['version']!!, values['variant'], config);
}
console.log('\n** Press Enter to build or Esc to exit');
console.log('')
// console.log('\n** Press Enter to build or Esc to exit');
}
function onKeyPress(data: any) {
@ -143,6 +241,9 @@ function onKeyPress(data: any) {
}
main();
/*
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.on('data', onKeyPress);
*/

BIN
bun.lockb

Binary file not shown.

6068
dist/better-xcloud.lite.user.js vendored Normal file

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 5.5.5
// @version 5.9.5
// ==/UserScript==

File diff suppressed because one or more lines are too long

View File

@ -2,6 +2,7 @@
"name": "better-xcloud",
"module": "src/index.ts",
"type": "module",
"sideEffects": false,
"browserslist": [
"Chrome >= 80"
],
@ -9,14 +10,14 @@
"build": "build.ts"
},
"devDependencies": {
"@types/bun": "^1.1.6",
"@types/node": "^20.14.15",
"@types/stylus": "^0.48.42",
"eslint": "^9.9.0",
"eslint-plugin-compat": "^6.0.0",
"stylus": "^0.63.0"
"@types/bun": "^1.1.12",
"@types/node": "^22.7.9",
"@types/stylus": "^0.48.43",
"eslint": "^9.13.0",
"eslint-plugin-compat": "^6.0.1",
"stylus": "^0.64.0"
},
"peerDependencies": {
"typescript": "^5.5.2"
"typescript": "^5.6.3"
}
}

View File

@ -179,15 +179,3 @@ button.bx-inactive {
opacity: 0.2;
background: transparent !important;
}
.bx-button-shortcut {
max-width: max-content;
margin: 10px 0 0 0;
flex: 1 0 auto;
}
@media (min-width: 568px) and (max-height: 480px) {
.bx-button-shortcut {
margin: 8px 0 0 10px;
}
}

View File

@ -76,21 +76,21 @@
}
/* Touch controller buttons */
div[data-enabled] {
div[data-activated] {
button {
display: none;
}
}
/* Show enabled button */
div[data-enabled='true'] {
/* Show default button */
div[data-activated='false'] {
button:first-of-type {
display: block;
}
}
/* Show enable button */
div[data-enabled='false'] {
/* Show activated button */
div[data-activated='true'] {
button:last-of-type {
display: block;
}

View File

@ -0,0 +1,65 @@
.bx-guide-home-achievements-progress {
display: flex;
gap: 10px;
flex-direction: row;
.bx-button {
margin-bottom: 0 !important;
}
html[data-xds-platform=tv] & {
flex-direction: column;
}
html:not([data-xds-platform=tv]) & {
flex-direction: row;
> button:first-of-type {
flex: 1;
}
> button:last-of-type {
width: 40px;
span {
display: none;
}
}
}
}
.bx-guide-home-buttons {
> div {
display: flex;
flex-direction: row;
gap: 12px;
html[data-xds-platform=tv] & {
flex-direction: column;
button {
margin-bottom: 0 !important;
}
}
html:not([data-xds-platform=tv]) & {
button {
span {
display: none;
}
}
}
}
&[data-is-playing="true"] {
button[data-state='normal'] {
display: none;
}
}
&[data-is-playing="false"] {
button[data-state='playing'] {
display: none;
}
}
}

21
src/assets/css/misc.styl Normal file
View File

@ -0,0 +1,21 @@
.bx-product-details-buttons {
display: flex;
gap: 10px;
flex-direction: row;
button {
max-width: max-content;
margin: 10px 0 0 0;
display: flex;
}
}
@media (min-width: 568px) and (max-height: 480px) {
.bx-product-details-buttons {
flex-direction: column;
button {
margin: 8px 0 0 10px;
}
}
}

View File

@ -1,6 +1,11 @@
.bx-navigation-dialog {
position: absolute;
z-index: var(--bx-navigation-dialog-z-index);
font-family: var(--bx-title-font);
*:focus {
outline: none !important;
}
}
.bx-navigation-dialog-overlay {

View File

@ -5,7 +5,7 @@
display: inline-block;
min-width: 40px;
font-family: var(--bx-monospaced-font);
font-size: 12px;
font-size: 13px;
margin: 0 4px;
}

View File

@ -1,36 +1,16 @@
.bx-remote-play-popup {
width: 100%;
max-width: 1920px;
margin: auto;
position: relative;
height: 0.1px;
overflow: visible;
z-index: var(--bx-remote-play-popup-z-index);
}
.bx-remote-play-container {
position: absolute;
right: 10px;
top: 0;
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;
box-shadow: #00000080 0px 0px 12px 0px;
@media (min-width:480px) and (min-height:calc(480px + 1px)) {
right: calc(env(safe-area-inset-right, 0px) + 32px);
}
@media (min-width:768px) and (min-height:calc(480px + 1px)) {
right: calc(env(safe-area-inset-right, 0px) + 48px);
}
@media (min-width:1920px) and (min-height:calc(480px + 1px)) {
right: calc(env(safe-area-inset-right, 0px) + 80px);
}
> .bx-button {
display: table;
@ -57,14 +37,6 @@
font-size: 12px;
}
}
span {
font-weight: bold;
font-size: 18px;
display: block;
margin-bottom: 8px;
text-align: center;
}
}
.bx-remote-play-resolution {
@ -114,10 +86,15 @@
.bx-remote-play-power-state {
color: #888;
font-size: 14px;
font-size: 12px;
}
.bx-remote-play-connect-button {
min-height: 100%;
margin: 4px 0;
}
.bx-remote-play-buttons {
display: flex;
justify-content: space-between;
}

View File

@ -26,22 +26,20 @@ button_color(name, normal, hover, active, disabled)
button_color('primary', #008746, #04b358, #044e2a, #448262);
button_color('danger', #c10404, #e61d1d, #a26c6c, #df5656);
--bx-fullscreen-text-z-index: 9999;
--bx-toast-z-index: 6000;
--bx-dialog-z-index: 5000;
--bx-fullscreen-text-z-index: 99999;
--bx-toast-z-index: 60000;
--bx-dialog-z-index: 50000;
--bx-dialog-overlay-z-index: 4020;
--bx-stats-bar-z-index: 4010;
--bx-mkb-pointer-lock-msg-z-index: 4000;
--bx-dialog-overlay-z-index: 40200;
--bx-stats-bar-z-index: 40100;
--bx-mkb-pointer-lock-msg-z-index: 40000;
--bx-navigation-dialog-z-index: 3010;
--bx-navigation-dialog-overlay-z-index: 3000;
--bx-navigation-dialog-z-index: 30100;
--bx-navigation-dialog-overlay-z-index: 30000;
--bx-remote-play-popup-z-index: 2000;
--bx-game-bar-z-index: 1000;
--bx-wait-time-box-z-index: 100;
--bx-screenshot-animation-z-index: 10;
--bx-game-bar-z-index: 10000;
--bx-screenshot-animation-z-index: 9000;
--bx-wait-time-box-z-index: 1000;
}
@font-face {
@ -59,7 +57,7 @@ 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 (max-width: 600px) {
@media screen and (max-width: 640px) {
header a[href="/play"] {
display: none;
}
@ -133,6 +131,13 @@ div[class^=HUDButton-module__hiddenContainer] ~ div:not([class^=HUDButton-module
text-transform: none !important;
}
.bx-normal-link {
text-transform: none !important;
text-align: left !important;
font-weight: 400 !important;
font-family: var(--bx-normal-font) !important;
}
select[multiple] {
overflow: auto;
}
@ -168,16 +173,11 @@ div[class*=SupportedInputsBadge] {
left: 0;
z-index: 1;
background: #0000008c;
display: none;
border-radius: 0 0 4px 0;
display: flex;
border-radius: 4px 0 4px 0;
align-items: center;
padding: 4px 8px;
a[class^=BaseItem-module__container]:focus &,
button[class^=BaseItem-module__container]:focus & {
display: flex;
}
svg {
width: 14px;
height: 16px;
@ -190,6 +190,7 @@ div[class*=SupportedInputsBadge] {
line-height: 16px;
font-size: 12px;
font-weight: bold;
margin-left: 2px;
}
}

View File

@ -31,6 +31,42 @@
font-weight: normal;
height: var(--bx-button-height);
}
input {
accent-color: var(--bx-primary-button-color);
&:focus {
accent-color: var(--bx-danger-button-color);
}
}
select:disabled {
-webkit-appearance: none;
background: transparent;
text-align-last: right;
border: none;
color: #fff;
}
select option:disabled {
display: none;
}
input[type=checkbox],
select {
&:focus {
filter: drop-shadow(1px 0 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 1px 0 #fff) drop-shadow(0 -1px 0 #fff);
}
}
a {
color: #1c9d1c;
text-decoration: none;
&:hover, &:focus {
color: #5dc21e;
}
}
}
.bx-settings-tabs-container {
@ -94,7 +130,6 @@
&:focus {
border-color: #fff;
outline: none;
}
&[data-group=global] {
@ -198,11 +233,6 @@
}
}
&:focus,
*:focus {
outline: none !important;
}
.bx-top-buttons {
display: flex;
flex-direction: column;
@ -258,13 +288,6 @@
flex-wrap: wrap;
}
input[type=checkbox],
select {
&:focus {
filter: drop-shadow(1px 0 0 #fff) drop-shadow(-1px 0 0 #fff) drop-shadow(0 1px 0 #fff) drop-shadow(0 -1px 0 #fff);
}
}
/*
&:has(input:focus), &:has(select:focus), &:has(button:focus) {
border-left-color: white;
@ -277,31 +300,12 @@
text-align: left;
align-self: center;
margin-bottom: 0 !important;
flex: 1;
+ * {
margin: 0 0 0 auto;
}
}
input {
accent-color: var(--bx-primary-button-color);
&:focus {
accent-color: var(--bx-danger-button-color);
}
}
select:disabled {
-webkit-appearance: none;
background: transparent;
text-align-last: right;
border: none;
color: #fff;
}
select option:disabled {
display: none;
}
}
.bx-settings-dialog-note {
@ -335,15 +339,6 @@
line-height: 20px;
font-size: 14px;
margin-top: 10px;
color: #5dc21e;
&:hover {
color: #6dd72b;
}
&:focus {
text-decoration: underline;
}
}
.bx-debug-info {
@ -404,3 +399,167 @@
}
}
}
.bx-suggest-toggler {
text-align: left;
display: flex;
border-radius: 4px;
overflow: hidden;
background: #003861;
label {
flex: 1;
margin-bottom: 0;
padding: 10px;
background: #004f87;
}
span {
display: inline-block;
align-self: center;
padding: 10px;
width: 40px;
text-align: center;
}
&:hover, &:focus {
cursor: pointer;
background: #005da1;
label {
background: #006fbe;
}
}
&[bx-open] {
span {
transform: rotate(90deg);
}
&+ .bx-suggest-box {
display: block;
}
}
}
.bx-suggest-box {
display: none;
background: #161616;
padding: 10px;
box-shadow: 0px 0px 12px #0f0f0f inset;
border-radius: 10px;
}
.bx-suggest-wrapper {
display: flex;
flex-direction: column;
gap: 10px;
margin: 10px;
}
.bx-suggest-note {
font-size: 11px;
color: #8c8c8c;
font-style: italic;
font-weight: 100;
}
.bx-suggest-link {
font-size: 14px;
display: inline-block;
margin-top: 4px;
padding: 4px;
}
.bx-suggest-row {
display: flex;
flex-direction: row;
gap: 10px;
label {
flex: 1;
overflow: overlay;
border-radius: 4px;
.bx-suggest-label {
background: #323232;
padding: 4px 10px;
font-size: 12px;
text-align: left;
}
.bx-suggest-value {
padding: 6px;
font-size: 14px;
&.bx-suggest-change {
background-color: var(--bx-warning-color);
}
}
}
&.bx-suggest-ok {
input {
visibility: hidden;
}
.bx-suggest-label {
background-color: #008114;
}
.bx-suggest-value {
background-color: #13a72a;
}
}
&.bx-suggest-change {
.bx-suggest-label {
background-color: #a65e08;
}
.bx-suggest-value {
background-color: #d57f18;
}
&:hover {
label {
cursor: pointer;
}
.bx-suggest-label {
background-color: #995707;
}
.bx-suggest-value {
background-color: #bd7115;
}
}
// Unchecked setting
input:not(:checked) + label {
opacity: 0.5;
.bx-suggest-label {
background-color: #2a2a2a;
}
.bx-suggest-value {
background-color: #393939;
}
}
&:hover {
input:not(:checked) + label {
opacity: 1;
.bx-suggest-label {
background-color: #202020;
}
.bx-suggest-value {
background-color: #303030;
}
}
}
}
}

View File

@ -71,7 +71,9 @@ div[class^=StreamMenu-module__container] .bx-badges {
/* STATS BAR */
.bx-stats-bar {
display: block;
display: flex;
flex-direction: row;
gap: 8px;
user-select: none;
-webkit-user-select: none;
position: fixed;
@ -84,22 +86,34 @@ div[class^=StreamMenu-module__container] .bx-badges {
z-index: var(--bx-stats-bar-z-index);
text-wrap: nowrap;
&[data-stats*="[time]"] > .bx-stat-time,
&[data-stats*="[play]"] > .bx-stat-play,
&[data-stats*="[batt]"] > .bx-stat-batt,
&[data-stats*="[fps]"] > .bx-stat-fps,
&[data-stats*="[ping]"] > .bx-stat-ping,
&[data-stats*="[jit]"] > .bx-stat-jit,
&[data-stats*="[btr]"] > .bx-stat-btr,
&[data-stats*="[dt]"] > .bx-stat-dt,
&[data-stats*="[pl]"] > .bx-stat-pl,
&[data-stats*="[fl]"] > .bx-stat-fl {
display: inline-block;
&[data-stats*="[fl]"] > .bx-stat-fl,
&[data-stats*="[dl]"] > .bx-stat-dl,
&[data-stats*="[ul]"] > .bx-stat-ul {
display: inline-flex;
align-items: baseline;
}
&[data-stats$="[time]"] > .bx-stat-time,
&[data-stats$="[play]"] > .bx-stat-play,
&[data-stats$="[batt]"] > .bx-stat-batt,
&[data-stats$="[fps]"] > .bx-stat-fps,
&[data-stats$="[ping]"] > .bx-stat-ping,
&[data-stats$="[jit]"] > .bx-stat-jit,
&[data-stats$="[btr]"] > .bx-stat-btr,
&[data-stats$="[dt]"] > .bx-stat-dt,
&[data-stats$="[pl]"] > .bx-stat-pl,
&[data-stats$="[fl]"] > .bx-stat-fl {
margin-right: 0;
&[data-stats$="[fl]"] > .bx-stat-fl,
&[data-stats$="[dl]"] > .bx-stat-dl,
&[data-stats$="[ul]"] > .bx-stat-ul {
border-right: none;
}
@ -137,7 +151,6 @@ div[class^=StreamMenu-module__container] .bx-badges {
> div {
display: none;
margin-right: 8px;
border-right: 1px solid #fff;
padding-right: 8px;
}
@ -145,7 +158,7 @@ div[class^=StreamMenu-module__container] .bx-badges {
label {
margin: 0 8px 0 0;
font-family: var(--bx-title-font);
font-size: inherit;
font-size: 70%;
font-weight: bold;
vertical-align: middle;
cursor: help;

View File

@ -9,9 +9,11 @@
@import 'loading-screen.styl';
@import 'remote-play.styl';
@import 'web-components.styl';
@import 'guide-menu.styl';
@import 'stream.styl';
@import 'number-stepper.styl';
@import 'game-bar.styl';
@import 'stream-stats.styl';
@import 'mkb.styl';
@import 'misc.styl';

View File

@ -4,12 +4,16 @@
flex: 0 1 auto;
select {
display: none !important;
// Render offscreen instead of "display: none" so we could get its size
position: absolute !important;
top: -9999px !important;
left: -9999px !important;
visibility: hidden !important;
}
> div, button.bx-select-value {
min-width: 110px;
text-align: center;
min-width: 120px;
text-align: left;
margin: 0 8px;
line-height: 24px;
vertical-align: middle;
@ -53,13 +57,14 @@
span {
flex: 1;
text-align: center;
text-align: left;
display: inline-block;
}
input {
margin: 0 4px;
accent-color: var(--bx-primary-button-color);
pointer-events: none;
}
&:hover,

View File

@ -0,0 +1,13 @@
// ==UserScript==
// @name Better xCloud (Lite)
// @namespace https://github.com/redphx
// @version [[VERSION]]
// @description Improve Xbox Cloud Gaming (xCloud) experience
// @author redphx
// @license MIT
// @match https://www.xbox.com/*/play*
// @match https://www.xbox.com/*/auth/msa?*loggedIn*
// @run-at document-end
// @grant none
// ==/UserScript==
"use strict";

View File

@ -0,0 +1,8 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='#fff' stroke='none ' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 32 32'>
<clipPath id='A'>
<path d='M0 0h32v32H0z'/>
</clipPath>
<g clip-path='url(#A)'>
<path d='M6.123 3.549a1.07 1.07 0 0 0-.798-.359c-.585 0-1.067.482-1.067 1.067 0 .27.102.53.286.727l2.565 2.823C2.267 10.779.184 15.36.092 15.568c-.123.276-.123.591 0 .867.047.105 1.176 2.609 3.687 5.12 3.345 3.344 7.57 5.112 12.221 5.112a16.97 16.97 0 0 0 6.943-1.444l2.933 3.228c.202.228.493.359.798.359.585 0 1.067-.482 1.067-1.067a1.07 1.07 0 0 0-.286-.727L6.123 3.549zm6.31 10.112l5.556 6.114c-.612.322-1.294.49-1.986.49a4.29 4.29 0 0 1-4.267-4.266c0-.831.242-1.643.697-2.338zM16 24.533c-4.104 0-7.689-1.492-10.657-4.433A17.73 17.73 0 0 1 2.267 16c.625-1.172 2.621-4.452 6.313-6.584l2.4 2.633c-.878 1.125-1.356 2.512-1.356 3.939 0 3.511 2.89 6.4 6.4 6.4 1.221 0 2.416-.349 3.444-1.005l1.964 2.16a14.92 14.92 0 0 1-5.432.99zm.8-12.724a1.07 1.07 0 0 1-.867-1.048c0-.585.482-1.067 1.067-1.067a1.12 1.12 0 0 1 .2.019c2.784.54 4.896 2.863 5.169 5.686a1.07 1.07 0 0 1-.962 1.161c-.034.002-.067.002-.1 0a1.07 1.07 0 0 1-1.067-.968 4.29 4.29 0 0 0-3.44-3.783zm15.104 4.626c-.056.125-1.407 3.116-4.448 5.84a1.07 1.07 0 0 1-.724.283c-.585 0-1.067-.482-1.067-1.067a1.07 1.07 0 0 1 .368-.806A17.7 17.7 0 0 0 29.74 16a17.73 17.73 0 0 0-3.083-4.103C23.689 8.959 20.104 7.467 16 7.467a15.82 15.82 0 0 0-2.581.209 1.06 1.06 0 0 1-.186.016 1.07 1.07 0 0 1-1.067-1.066 1.07 1.07 0 0 1 .901-1.054A17.89 17.89 0 0 1 16 5.333c4.651 0 8.876 1.768 12.221 5.114 2.511 2.51 3.64 5.016 3.687 5.121.123.276.123.591 0 .867h-.004z' fill-rule='nonzero'/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

8
src/assets/svg/eye.svg Normal file
View File

@ -0,0 +1,8 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='#fff' stroke='none ' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 32 32'>
<clipPath id='A'>
<path d='M0 0h32v32H0z'/>
</clipPath>
<g clip-path='url(#A)'>
<path d='M31.908 15.568c-.047-.105-1.176-2.611-3.687-5.121C24.876 7.101 20.651 5.333 16 5.333S7.124 7.101 3.779 10.447c-2.511 2.51-3.646 5.02-3.687 5.121-.123.276-.123.591 0 .867.047.105 1.176 2.609 3.687 5.12 3.345 3.344 7.57 5.112 12.221 5.112s8.876-1.768 12.221-5.112c2.511-2.511 3.64-5.015 3.687-5.12.123-.276.123-.591 0-.867zM16 24.533c-4.104 0-7.689-1.492-10.657-4.433-1.218-1.211-2.254-2.592-3.076-4.1.822-1.508 1.858-2.889 3.076-4.1C8.311 8.959 11.896 7.467 16 7.467s7.689 1.492 10.657 4.433c1.221 1.211 2.259 2.592 3.083 4.1-.961 1.795-5.149 8.533-13.74 8.533zM16 9.6c-3.511 0-6.4 2.889-6.4 6.4s2.889 6.4 6.4 6.4 6.4-2.889 6.4-6.4A6.44 6.44 0 0 0 16 9.6zm0 10.667A4.29 4.29 0 0 1 11.733 16 4.29 4.29 0 0 1 16 11.733 4.29 4.29 0 0 1 20.267 16 4.29 4.29 0 0 1 16 20.267z' fill-rule='nonzero'/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

3
src/assets/svg/power.svg Normal file
View File

@ -0,0 +1,3 @@
<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='M16 2.445v12.91m7.746-11.619C27.631 6.27 30.2 10.37 30.2 15.355c0 7.79-6.41 14.2-14.2 14.2s-14.2-6.41-14.2-14.2c0-4.985 2.569-9.085 6.454-11.619'/>
</svg>

After

Width:  |  Height:  |  Size: 339 B

View File

@ -0,0 +1,3 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='#fff' stroke='none' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 32 32'>
<path d='M5.462 3.4c-.205-.23-.499-.363-.808-.363-.592 0-1.079.488-1.079 1.08a1.08 1.08 0 0 0 .289.736l4.247 4.672H2.504a2.17 2.17 0 0 0-2.16 2.16v8.637a2.17 2.17 0 0 0 2.16 2.16h6.107l9.426 7.33a1.08 1.08 0 0 0 .662.227c.592 0 1.08-.487 1.08-1.079v-6.601l5.679 6.247a1.08 1.08 0 0 0 .808.363c.592 0 1.08-.487 1.08-1.079a1.08 1.08 0 0 0-.29-.736L5.462 3.4zm-2.958 8.285h5.398v8.637H2.504v-8.637zM17.62 26.752l-7.558-5.878V11.67l7.558 8.313v6.769zm5.668-8.607c1.072-1.218 1.072-3.063 0-4.281a1.08 1.08 0 0 1-.293-.74c0-.592.487-1.079 1.079-1.079a1.08 1.08 0 0 1 .834.393 5.42 5.42 0 0 1 0 7.137 1.08 1.08 0 0 1-.81.365c-.593 0-1.08-.488-1.08-1.08 0-.263.096-.517.27-.715zM12.469 7.888c-.147-.19-.228-.423-.228-.663a1.08 1.08 0 0 1 .417-.853l5.379-4.184a1.08 1.08 0 0 1 .662-.227c.593 0 1.08.488 1.08 1.08v10.105c0 .593-.487 1.08-1.08 1.08s-1.079-.487-1.079-1.08V5.255l-3.636 2.834c-.469.362-1.153.273-1.515-.196v-.005zm19.187 8.115a10.79 10.79 0 0 1-2.749 7.199 1.08 1.08 0 0 1-.793.347c-.593 0-1.08-.487-1.08-1.079 0-.26.094-.511.264-.708 2.918-3.262 2.918-8.253 0-11.516-.184-.2-.287-.461-.287-.733 0-.592.487-1.08 1.08-1.08a1.08 1.08 0 0 1 .816.373 10.78 10.78 0 0 1 2.749 7.197z' fill-rule='nonzero'/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1,3 @@
<svg xmlns='http://www.w3.org/2000/svg' fill='#fff' stroke='nons' fill-rule='evenodd' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 32 32'>
<path d='M2.497 14.127c.781-6.01 5.542-10.849 11.551-11.708V0C6.634.858.858 6.712 0 14.127h2.497zM17.952 2.419V0C25.366.858 31.142 6.712 32 14.127h-2.497c-.781-6.01-5.542-10.849-11.551-11.708zM2.497 17.873c.781 6.01 5.542 10.849 11.551 11.708V32C6.634 31.142.858 25.288 0 17.873h2.497zm27.006 0H32C31.142 25.288 25.366 31.142 17.952 32v-2.419c6.009-.859 10.77-5.698 11.551-11.708zm-19.2-4.527h2.028a.702.702 0 1 0 0-1.404h-2.107a1.37 1.37 0 0 1-1.326-1.327V9.21a.7.7 0 0 0-.703-.703c-.387 0-.703.316-.703.7v1.408c.079 1.483 1.25 2.731 2.811 2.731zm2.809 7.337h-2.888a1.37 1.37 0 0 1-1.326-1.327v-4.917c0-.387-.316-.703-.7-.703a.7.7 0 0 0-.706.703v4.917a2.77 2.77 0 0 0 2.732 2.732h2.81c.387 0 .702-.316.702-.7.078-.393-.234-.705-.624-.705zM25.6 19.2a.7.7 0 0 0-.702-.702c-.387 0-.703.316-.703.699v.081c0 .702-.546 1.326-1.248 1.326H19.98c-.702-.078-1.248-.624-1.248-1.326v-.312c0-.78.624-1.327 1.326-1.327h2.811a2.77 2.77 0 0 0 2.731-2.732v-.312a2.68 2.68 0 0 0-2.576-2.732h-4.76a.702.702 0 1 0 0 1.405h4.526a1.37 1.37 0 0 1 1.327 1.327v.234c0 .781-.624 1.327-1.327 1.327h-2.81a2.77 2.77 0 0 0-2.731 2.732v.312a2.77 2.77 0 0 0 2.731 2.732h2.967a2.74 2.74 0 0 0 2.575-2.732s.078.078.078 0z'/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -37,11 +37,11 @@ export enum PrefKey {
LOCAL_CO_OP_ENABLED = 'local_co_op_enabled',
// LOCAL_CO_OP_SEPARATE_TOUCH_CONTROLLER = 'local_co_op_separate_touch_controller',
CONTROLLER_ENABLE_SHORTCUTS = 'controller_enable_shortcuts',
CONTROLLER_ENABLE_VIBRATION = 'controller_enable_vibration',
CONTROLLER_DEVICE_VIBRATION = 'controller_device_vibration',
CONTROLLER_VIBRATION_INTENSITY = 'controller_vibration_intensity',
CONTROLLER_SHOW_CONNECTION_STATUS = 'controller_show_connection_status',
CONTROLLER_POLLING_RATE = 'controller_polling_rate',
NATIVE_MKB_ENABLED = 'native_mkb_enabled',
NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY = 'native_mkb_scroll_x_sensitivity',
@ -69,12 +69,12 @@ export enum PrefKey {
UI_SCROLLBAR_HIDE = 'ui_scrollbar_hide',
UI_HIDE_SECTIONS = 'ui_hide_sections',
UI_HOME_CONTEXT_MENU_DISABLED = 'ui_home_context_menu_disabled',
UI_GAME_CARD_SHOW_WAIT_TIME = 'ui_game_card_show_wait_time',
VIDEO_PLAYER_TYPE = 'video_player_type',
VIDEO_PROCESSING = 'video_processing',
VIDEO_POWER_PREFERENCE = 'video_power_preference',
VIDEO_MAX_FPS = 'video_max_fps',
VIDEO_SHARPNESS = 'video_sharpness',
VIDEO_RATIO = 'video_ratio',
VIDEO_BRIGHTNESS = 'video_brightness',
@ -98,4 +98,5 @@ export enum PrefKey {
REMOTE_PLAY_RESOLUTION = 'xhome_resolution',
GAME_FORTNITE_FORCE_CONSOLE = 'game_fortnite_force_console',
GAME_MSFS2020_FORCE_NATIVE_MKB = 'game_msfs2020_force_native_mkb',
}

View File

@ -1,3 +1,5 @@
import { compressCss, isFullVersion } from "@macros/build" with {type: "macro"};
import "@utils/global";
import { BxEvent } from "@utils/bx-event";
import { BX_FLAGS } from "@utils/bx-flags";
@ -5,28 +7,26 @@ import { BxExposed } from "@utils/bx-exposed";
import { t } from "@utils/translation";
import { interceptHttpRequests } from "@utils/network";
import { CE } from "@utils/html";
import { showGamepadToast } from "@utils/gamepad";
import { showGamepadToast, updatePollingRate } from "@utils/gamepad";
import { EmulatedMkbHandler } from "@modules/mkb/mkb-handler";
import { StreamBadges } from "@modules/stream/stream-badges";
import { StreamStats } from "@modules/stream/stream-stats";
import { addCss, preloadFonts } from "@utils/css";
import { Toast } from "@utils/toast";
import { LoadingScreen } from "@modules/loading-screen";
import { MouseCursorHider } from "@modules/mkb/mouse-cursor-hider";
import { TouchController } from "@modules/touch-controller";
import { checkForUpdate, disablePwa } from "@utils/utils";
import { checkForUpdate, disablePwa, productTitleToSlug } from "@utils/utils";
import { Patcher } from "@modules/patcher";
import { RemotePlay } from "@modules/remote-play";
import { RemotePlayManager } from "@/modules/remote-play-manager";
import { onHistoryChanged, patchHistoryMethod } from "@utils/history";
import { VibrationManager } from "@modules/vibration-manager";
import { overridePreloadState } from "@utils/preload-state";
import { disableAdobeAudienceManager, patchAudioContext, patchCanvasContext, patchMeControl, patchPointerLockApi, patchRtcCodecs, patchRtcPeerConnection, patchVideoApi } from "@utils/monkey-patches";
import { AppInterface, STATES } from "@utils/global";
import { BxLogger } from "@utils/bx-logger";
import { GameBar } from "./modules/game-bar/game-bar";
import { Screenshot } from "./utils/screenshot";
import { ScreenshotManager } from "./utils/screenshot-manager";
import { NativeMkbHandler } from "./modules/mkb/native-mkb-handler";
import { GuideMenu, GuideMenuTab } from "./modules/ui/guide-menu";
import { GuideMenu } from "./modules/ui/guide-menu";
import { updateVideoPlayer } from "./modules/stream/stream-settings-utils";
import { UiSection } from "./enums/ui-sections";
import { HeaderSection } from "./modules/ui/header";
@ -34,11 +34,13 @@ 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 { compressCss } from "@macros/build" with {type: "macro"};
import { getPref, StreamTouchController } from "./utils/settings-storages/global-settings-storage";
import { SettingsNavigationDialog } from "./modules/ui/dialog/settings-dialog";
import { StreamUiHandler } from "./modules/stream/stream-ui";
import { UserAgent } from "./utils/user-agent";
import { XboxApi } from "./utils/xbox-api";
import { StreamStatsCollector } from "./utils/stream-stats-collector";
import { RootDialogObserver } from "./utils/root-dialog-observer";
// Handle login page
if (window.location.pathname.includes('/auth/msa')) {
@ -61,35 +63,77 @@ if (window.location.pathname.includes('/auth/msa')) {
BxLogger.info('readyState', document.readyState);
if (BX_FLAGS.SafariWorkaround && document.readyState !== 'loading') {
if (isFullVersion() && BX_FLAGS.SafariWorkaround && document.readyState !== 'loading') {
// Stop loading
window.stop();
// Show the reloading overlay
const css = compressCss(`
// We need to set it to an empty string first to work around Bun's bug
// https://github.com/oven-sh/bun/issues/12067
let css = '';
css += compressCss(`
.bx-reload-overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
background: #000000cc;
z-index: 9999;
width: 100%;
line-height: 100vh;
color: #fff;
text-align: center;
font-weight: 400;
font-family: "Segoe UI", Arial, Helvetica, sans-serif;
font-size: 1.3rem;
}
.bx-reload-overlay *:focus {
outline: none !important;
}
.bx-reload-overlay > div {
margin: 0 auto;
}
.bx-reload-overlay a {
text-decoration: none;
display: inline-block;
background: #107c10;
color: white;
border-radius: 4px;
padding: 6px;
}
`);
const isSafari = UserAgent.isSafari();
let $secondaryAction: HTMLElement;
if (isSafari) {
$secondaryAction = CE('p', {}, t('settings-reloading'));
} else {
$secondaryAction = CE('a', {
href: 'https://better-xcloud.github.io/troubleshooting',
target: '_blank',
}, '🤓 ' + t('how-to-fix'));
}
// Show the reloading overlay
const $fragment = document.createDocumentFragment();
$fragment.appendChild(CE('style', {}, css));
$fragment.appendChild(CE('div', {'class': 'bx-reload-overlay'}, t('safari-failed-message')));
$fragment.appendChild(CE('div',{
class: 'bx-reload-overlay',
},
CE('div', {},
CE('p', {}, t('load-failed-message')),
$secondaryAction,
),
));
document.documentElement.appendChild($fragment);
// Reload the page
// Reload the page if using Safari
// @ts-ignore
window.location.reload(true);
isSafari && window.location.reload(true);
// Stop processing the script
throw new Error('[Better xCloud] Executing workaround for Safari');
@ -116,7 +160,7 @@ document.addEventListener('readystatechange', e => {
if (STATES.isSignedIn) {
// Preload Remote Play
getPref(PrefKey.REMOTE_PLAY_ENABLED) && RemotePlay.preload();
getPref(PrefKey.REMOTE_PLAY_ENABLED) && RemotePlayManager.getInstance().initialize();
} else {
// Show Settings button in the header when not signed in
window.setTimeout(HeaderSection.watchHeader, 2000);
@ -124,7 +168,7 @@ document.addEventListener('readystatechange', e => {
// Hide "Play with Friends" skeleton section
if (getPref(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.FRIENDS)) {
const $parent = document.querySelector('div[class*=PlayWithFriendsSkeleton]')?.closest('div[class*=HomePage-module]') as HTMLElement;
const $parent = document.querySelector('div[class*=PlayWithFriendsSkeleton]')?.closest<HTMLElement>('div[class*=HomePage-module]');
$parent && ($parent.style.display = 'none');
}
@ -148,8 +192,11 @@ window.addEventListener(BxEvent.XCLOUD_SERVERS_UNAVAILABLE, e => {
window.setTimeout(HeaderSection.watchHeader, 2000);
// Open Settings dialog on Unsupported page
SettingsNavigationDialog.getInstance().show();
});
const $unsupportedPage = document.querySelector<HTMLElement>('div[class^=UnsupportedMarketPage-module__container]');
if ($unsupportedPage) {
SettingsNavigationDialog.getInstance().show();
}
}, {once: true});
window.addEventListener(BxEvent.XCLOUD_SERVERS_READY, e => {
STATES.isSignedIn = true;
@ -158,15 +205,10 @@ window.addEventListener(BxEvent.XCLOUD_SERVERS_READY, e => {
window.addEventListener(BxEvent.STREAM_LOADING, e => {
// Get title ID for screenshot's name
if (window.location.pathname.includes('/launch/')) {
const matches = /\/launch\/(?<title_id>[^\/]+)\/(?<product_id>\w+)/.exec(window.location.pathname);
if (matches?.groups) {
STATES.currentStream.titleId = matches.groups.title_id;
STATES.currentStream.productId = matches.groups.product_id;
}
if (window.location.pathname.includes('/launch/') && STATES.currentStream.titleInfo) {
STATES.currentStream.titleSlug = productTitleToSlug(STATES.currentStream.titleInfo.product.title);
} else {
STATES.currentStream.titleId = 'remote-play';
STATES.currentStream.productId = '';
STATES.currentStream.titleSlug = 'remote-play';
}
});
@ -188,15 +230,17 @@ window.addEventListener(BxEvent.STREAM_PLAYING, e => {
STATES.isPlaying = true;
StreamUiHandler.observe();
if (getPref(PrefKey.GAME_BAR_POSITION) !== 'off') {
if (isFullVersion() && getPref(PrefKey.GAME_BAR_POSITION) !== 'off') {
const gameBar = GameBar.getInstance();
gameBar.reset();
gameBar.enable();
gameBar.showBar();
}
const $video = (e as any).$video as HTMLVideoElement;
Screenshot.updateCanvasSize($video.videoWidth, $video.videoHeight);
if (isFullVersion()) {
const $video = (e as any).$video as HTMLVideoElement;
ScreenshotManager.getInstance().updateCanvasSize($video.videoWidth, $video.videoHeight);
}
updateVideoPlayer();
});
@ -208,18 +252,52 @@ window.addEventListener(BxEvent.STREAM_ERROR_PAGE, e => {
window.addEventListener(BxEvent.XCLOUD_RENDERING_COMPONENT, e => {
const component = (e as any).component;
if (component === 'product-details') {
ProductDetailsPage.injectShortcutButton();
ProductDetailsPage.injectButtons();
}
});
// Detect game change
window.addEventListener(BxEvent.DATA_CHANNEL_CREATED, e => {
const dataChannel = (e as any).dataChannel;
if (!dataChannel || dataChannel.label !== 'message') {
return;
}
dataChannel.addEventListener('message', async (msg: MessageEvent) => {
if (msg.origin === 'better-xcloud' || typeof msg.data !== 'string') {
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;
// 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);
}
}
}
}
});
});
function unload() {
if (!STATES.isPlaying) {
return;
}
// Stop MKB listeners
EmulatedMkbHandler.getInstance().destroy();
NativeMkbHandler.getInstance().destroy();
if (isFullVersion()) {
// Stop MKB listeners
EmulatedMkbHandler.getInstance().destroy();
NativeMkbHandler.getInstance().destroy();
}
// Destroy StreamPlayer
STATES.currentStream.streamPlayer?.destroy();
@ -230,11 +308,14 @@ function unload() {
window.BX_EXPOSED.stopTakRendering = false;
NavigationDialogManager.getInstance().hide();
StreamStats.getInstance().onStoppedPlaying();
StreamStats.getInstance().destroy();
StreamBadges.getInstance().destroy();
MouseCursorHider.stop();
TouchController.reset();
GameBar.getInstance().disable();
if (isFullVersion()) {
MouseCursorHider.stop();
TouchController.reset();
(getPref(PrefKey.GAME_BAR_POSITION) !== 'off') && GameBar.getInstance().disable();
}
}
window.addEventListener(BxEvent.STREAM_STOPPED, unload);
@ -242,73 +323,15 @@ window.addEventListener('pagehide', e => {
BxEvent.dispatch(window, BxEvent.STREAM_STOPPED);
});
window.addEventListener(BxEvent.CAPTURE_SCREENSHOT, e => {
Screenshot.takeScreenshot();
isFullVersion() && window.addEventListener(BxEvent.CAPTURE_SCREENSHOT, e => {
ScreenshotManager.getInstance().takeScreenshot();
});
function observeRootDialog($root: HTMLElement) {
let currentShown = false;
const observer = new MutationObserver(mutationList => {
for (const mutation of mutationList) {
if (mutation.type !== 'childList') {
continue;
}
if (mutation.addedNodes.length === 1) {
const $addedElm = mutation.addedNodes[0];
if ($addedElm instanceof HTMLElement && $addedElm.className) {
if ($addedElm.className.startsWith('NavigationAnimation') || $addedElm.className.startsWith('DialogRoutes') || $addedElm.className.startsWith('Dialog-module__container')) {
// Make sure it's Guide dialog
if (document.querySelector('#gamepass-dialog-root div[class*=GuideDialog]')) {
// Find navigation bar
const $selectedTab = $addedElm.querySelector('div[class^=NavigationMenu] button[aria-selected=true');
if ($selectedTab) {
let $elm: Element | null = $selectedTab;
let index;
for (index = 0; ($elm = $elm?.previousElementSibling); index++);
if (index === 0) {
BxEvent.dispatch(window, BxEvent.XCLOUD_GUIDE_MENU_SHOWN, {where: GuideMenuTab.HOME});
}
}
}
}
}
}
const shown = ($root.firstElementChild && $root.firstElementChild.childElementCount > 0) || false;
if (shown !== currentShown) {
currentShown = shown;
BxEvent.dispatch(window, shown ? BxEvent.XCLOUD_DIALOG_SHOWN : BxEvent.XCLOUD_DIALOG_DISMISSED);
}
}
});
observer.observe($root, {subtree: true, childList: true});
}
function waitForRootDialog() {
const observer = new MutationObserver(mutationList => {
for (const mutation of mutationList) {
if (mutation.type !== 'childList') {
continue;
}
const $target = mutation.target as HTMLElement;
if ($target.id && $target.id === 'gamepass-dialog-root') {
observer.disconnect();
observeRootDialog($target);
break;
}
};
});
observer.observe(document.documentElement, {subtree: true, childList: true});
}
function main() {
waitForRootDialog();
if (getPref(PrefKey.GAME_MSFS2020_FORCE_NATIVE_MKB)) {
BX_FLAGS.ForceNativeMkbTitles.push('9PMQDM08SNK9');
}
// Monkey patches
patchRtcPeerConnection();
@ -316,7 +339,7 @@ function main() {
interceptHttpRequests();
patchVideoApi();
patchCanvasContext();
AppInterface && patchPointerLockApi();
isFullVersion() && AppInterface && patchPointerLockApi();
getPref(PrefKey.AUDIO_ENABLE_VOLUME_CONTROL) && patchAudioContext();
@ -325,52 +348,54 @@ function main() {
disableAdobeAudienceManager();
}
STATES.userAgent.capabilities.touch && TouchController.updateCustomList();
overridePreloadState();
VibrationManager.initialSetup();
// Check for Update
BX_FLAGS.CheckForUpdate && checkForUpdate();
RootDialogObserver.waitForRootDialog();
// Setup UI
addCss();
Toast.setup();
(getPref(PrefKey.GAME_BAR_POSITION) !== 'off') && GameBar.getInstance();
Screenshot.setup();
GuideMenu.observe();
GuideMenu.getInstance().addEventListeners();
StreamStatsCollector.setupEvents();
StreamBadges.setupEvents();
StreamStats.setupEvents();
EmulatedMkbHandler.setupEvents();
Patcher.init();
if (isFullVersion()) {
updatePollingRate();
STATES.userAgent.capabilities.touch && TouchController.updateCustomList();
disablePwa();
VibrationManager.initialSetup();
// Check for Update
BX_FLAGS.CheckForUpdate && checkForUpdate();
Patcher.init();
disablePwa();
// Preload Remote Play
if (getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
RemotePlayManager.detect();
}
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.ALL) {
TouchController.setup();
}
// Start PointerProviderServer
if (getPref(PrefKey.MKB_ENABLED) && AppInterface) {
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();
EmulatedMkbHandler.setupEvents();
}
// Show a toast when connecting/disconecting controller
if (getPref(PrefKey.CONTROLLER_SHOW_CONNECTION_STATUS)) {
window.addEventListener('gamepadconnected', e => showGamepadToast(e.gamepad));
window.addEventListener('gamepaddisconnected', e => showGamepadToast(e.gamepad));
}
// Preload Remote Play
if (getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
RemotePlay.detect();
}
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'all') {
TouchController.setup();
}
// Start PointerProviderServer
if (getPref(PrefKey.MKB_ENABLED) && AppInterface) {
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();
}
main();

View File

@ -1,5 +1,13 @@
import stylus from 'stylus';
export const isFullVersion = () => {
return Bun.env.BUILD_VARIANT === 'full';
};
export const isLiteVersion = () => {
return Bun.env.BUILD_VARIANT === 'lite';
};
export const renderStylus = async () => {
const file = Bun.file('./src/assets/css/styles.styl');
const cssStr = await file.text();
@ -14,6 +22,6 @@ export const renderStylus = async () => {
};
export const compressCss = async (css: string) => {
return await (stylus(css, {}).set('compress', true)).render();
export const compressCss = (css: string) => {
return (stylus(css, {}).set('compress', true)).render();
};

View File

@ -1,9 +1,8 @@
import { Screenshot } from "@utils/screenshot";
import { ScreenshotManager } from "@/utils/screenshot-manager";
import { GamepadKey } from "@enums/mkb";
import { PrompFont } from "@enums/prompt-font";
import { CE } from "@utils/html";
import { CE, removeChildElements } from "@utils/html";
import { t } from "@utils/translation";
import { EmulatedMkbHandler } from "./mkb/mkb-handler";
import { StreamStats } from "./stream/stream-stats";
import { MicrophoneShortcut } from "./shortcuts/shortcut-microphone";
import { StreamUiShortcut } from "./shortcuts/shortcut-stream-ui";
@ -15,6 +14,7 @@ import { setNearby } from "@/utils/navigation-utils";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { SettingsNavigationDialog } from "./ui/dialog/settings-dialog";
import { VIRTUAL_GAMEPAD_ID } from "./mkb/mkb-handler";
const enum ShortcutAction {
BETTER_XCLOUD_SETTINGS_SHOW = 'bx-settings-show',
@ -38,66 +38,67 @@ const enum ShortcutAction {
}
export class ControllerShortcut {
static readonly #STORAGE_KEY = 'better_xcloud_controller_shortcuts';
private static readonly STORAGE_KEY = 'better_xcloud_controller_shortcuts';
static #buttonsCache: {[key: string]: boolean[]} = {};
static #buttonsStatus: {[key: string]: boolean[]} = {};
private static buttonsCache: {[key: string]: boolean[]} = {};
private static buttonsStatus: {[key: string]: boolean[]} = {};
static #$selectProfile: HTMLSelectElement;
static #$selectActions: Partial<{[key in GamepadKey]: HTMLSelectElement}> = {};
static #$container: HTMLElement;
private static $selectProfile: HTMLSelectElement;
private static $selectActions: Partial<{[key in GamepadKey]: HTMLSelectElement}> = {};
private static $container: HTMLElement;
static #ACTIONS: {[key: string]: (ShortcutAction | null)[]} | null = null;
private static ACTIONS: {[key: string]: (ShortcutAction | null)[]} | null = null;
static reset(index: number) {
ControllerShortcut.#buttonsCache[index] = [];
ControllerShortcut.#buttonsStatus[index] = [];
ControllerShortcut.buttonsCache[index] = [];
ControllerShortcut.buttonsStatus[index] = [];
}
static handle(gamepad: Gamepad): boolean {
if (!ControllerShortcut.#ACTIONS) {
ControllerShortcut.#ACTIONS = ControllerShortcut.#getActionsFromStorage();
if (!ControllerShortcut.ACTIONS) {
ControllerShortcut.ACTIONS = ControllerShortcut.getActionsFromStorage();
}
const gamepadIndex = gamepad.index;
const actions = ControllerShortcut.#ACTIONS![gamepad.id];
const actions = ControllerShortcut.ACTIONS![gamepad.id];
if (!actions) {
return false;
}
// Move the buttons status from the previous frame to the cache
ControllerShortcut.#buttonsCache[gamepadIndex] = ControllerShortcut.#buttonsStatus[gamepadIndex].slice(0);
ControllerShortcut.buttonsCache[gamepadIndex] = ControllerShortcut.buttonsStatus[gamepadIndex].slice(0);
// Clear the buttons status
ControllerShortcut.#buttonsStatus[gamepadIndex] = [];
ControllerShortcut.buttonsStatus[gamepadIndex] = [];
const pressed: boolean[] = [];
let otherButtonPressed = false;
gamepad.buttons.forEach((button, index) => {
const entries = gamepad.buttons.entries();
for (const [index, button] of entries) {
// Only add the newly pressed button to the array (holding doesn't count)
if (button.pressed && index !== GamepadKey.HOME) {
otherButtonPressed = true;
pressed[index] = true;
// If this is newly pressed button -> run action
if (actions[index] && !ControllerShortcut.#buttonsCache[gamepadIndex][index]) {
setTimeout(() => ControllerShortcut.#runAction(actions[index]!), 0);
if (actions[index] && !ControllerShortcut.buttonsCache[gamepadIndex][index]) {
setTimeout(() => ControllerShortcut.runAction(actions[index]!), 0);
}
}
});
};
ControllerShortcut.#buttonsStatus[gamepadIndex] = pressed;
ControllerShortcut.buttonsStatus[gamepadIndex] = pressed;
return otherButtonPressed;
}
static #runAction(action: ShortcutAction) {
private static runAction(action: ShortcutAction) {
switch (action) {
case ShortcutAction.BETTER_XCLOUD_SETTINGS_SHOW:
SettingsNavigationDialog.getInstance().show();
break;
case ShortcutAction.STREAM_SCREENSHOT_CAPTURE:
Screenshot.takeScreenshot();
ScreenshotManager.getInstance().takeScreenshot();
break;
case ShortcutAction.STREAM_STATS_TOGGLE:
@ -134,8 +135,8 @@ export class ControllerShortcut {
}
}
static #updateAction(profile: string, button: GamepadKey, action: ShortcutAction | null) {
const actions = ControllerShortcut.#ACTIONS!;
private static updateAction(profile: string, button: GamepadKey, action: ShortcutAction | null) {
const actions = ControllerShortcut.ACTIONS!;
if (!(profile in actions)) {
actions[profile] = [];
}
@ -147,9 +148,9 @@ export class ControllerShortcut {
actions[profile][button] = action;
// Remove empty profiles
for (const key in ControllerShortcut.#ACTIONS) {
for (const key in ControllerShortcut.ACTIONS) {
let empty = true;
for (const value of ControllerShortcut.#ACTIONS[key]) {
for (const value of ControllerShortcut.ACTIONS[key]) {
if (!!value) {
empty = false;
break;
@ -157,26 +158,22 @@ export class ControllerShortcut {
}
if (empty) {
delete ControllerShortcut.#ACTIONS[key];
delete ControllerShortcut.ACTIONS[key];
}
}
// Save to storage
window.localStorage.setItem(ControllerShortcut.#STORAGE_KEY, JSON.stringify(ControllerShortcut.#ACTIONS));
console.log(ControllerShortcut.#ACTIONS);
window.localStorage.setItem(ControllerShortcut.STORAGE_KEY, JSON.stringify(ControllerShortcut.ACTIONS));
}
static #updateProfileList(e?: GamepadEvent) {
const $select = ControllerShortcut.#$selectProfile;
const $container = ControllerShortcut.#$container;
private static updateProfileList(e?: GamepadEvent) {
const $select = ControllerShortcut.$selectProfile;
const $container = ControllerShortcut.$container;
const $fragment = document.createDocumentFragment();
// Remove old profiles
while ($select.firstElementChild) {
$select.firstElementChild.remove();
}
removeChildElements($select);
const gamepads = navigator.getGamepads();
let hasGamepad = false;
@ -187,7 +184,7 @@ export class ControllerShortcut {
}
// Ignore emulated gamepad
if (gamepad.id === EmulatedMkbHandler.VIRTUAL_GAMEPAD_ID) {
if (gamepad.id === VIRTUAL_GAMEPAD_ID) {
continue;
}
@ -207,16 +204,16 @@ export class ControllerShortcut {
}
static #switchProfile(profile: string) {
let actions = ControllerShortcut.#ACTIONS![profile];
private static switchProfile(profile: string) {
let actions = ControllerShortcut.ACTIONS![profile];
if (!actions) {
actions = [];
}
// Reset selects' values
let button: any;
for (button in ControllerShortcut.#$selectActions) {
const $select = ControllerShortcut.#$selectActions[button as GamepadKey]!;
for (button in ControllerShortcut.$selectActions) {
const $select = ControllerShortcut.$selectActions[button as GamepadKey]!;
$select.value = actions[button] || '';
BxEvent.dispatch($select, 'input', {
@ -226,15 +223,15 @@ export class ControllerShortcut {
}
}
static #getActionsFromStorage() {
return JSON.parse(window.localStorage.getItem(ControllerShortcut.#STORAGE_KEY) || '{}');
private static getActionsFromStorage() {
return JSON.parse(window.localStorage.getItem(ControllerShortcut.STORAGE_KEY) || '{}');
}
static renderSettings() {
const PREF_CONTROLLER_FRIENDLY_UI = getPref(PrefKey.UI_CONTROLLER_FRIENDLY);
// Read actions from localStorage
ControllerShortcut.#ACTIONS = ControllerShortcut.#getActionsFromStorage();
ControllerShortcut.ACTIONS = ControllerShortcut.getActionsFromStorage();
const buttons: Map<GamepadKey, PrompFont> = new Map();
buttons.set(GamepadKey.Y, PrompFont.Y);
@ -316,6 +313,7 @@ export class ControllerShortcut {
const $selectProfile = CE<HTMLSelectElement>('select', {class: 'bx-shortcut-profile', autocomplete: 'off'});
const $profile = PREF_CONTROLLER_FRIENDLY_UI ? BxSelectElement.wrap($selectProfile) : $selectProfile;
$profile.classList.add('bx-full-width');
const $container = CE('div', {
'data-has-gamepad': 'false',
@ -341,7 +339,7 @@ export class ControllerShortcut {
);
$selectProfile.addEventListener('input', e => {
ControllerShortcut.#switchProfile($selectProfile.value);
ControllerShortcut.switchProfile($selectProfile.value);
});
const onActionChanged = (e: Event) => {
@ -362,7 +360,7 @@ export class ControllerShortcut {
($fakeSelect.firstElementChild as HTMLOptionElement).text = fakeText;
}
!(e as any).ignoreOnChange && ControllerShortcut.#updateAction(profile, button as GamepadKey, action);
!(e as any).ignoreOnChange && ControllerShortcut.updateAction(profile, button as GamepadKey, action);
};
@ -388,10 +386,12 @@ export class ControllerShortcut {
$select.dataset.button = button.toString();
$select.addEventListener('input', onActionChanged);
ControllerShortcut.#$selectActions[button] = $select;
ControllerShortcut.$selectActions[button] = $select;
if (PREF_CONTROLLER_FRIENDLY_UI) {
const $bxSelect = BxSelectElement.wrap($select);
$bxSelect.classList.add('bx-full-width');
$div.appendChild($bxSelect);
setNearby($row, {
focus: $bxSelect,
@ -411,14 +411,14 @@ export class ControllerShortcut {
$container.appendChild($remap);
ControllerShortcut.#$selectProfile = $selectProfile;
ControllerShortcut.#$container = $container;
ControllerShortcut.$selectProfile = $selectProfile;
ControllerShortcut.$container = $container;
// Detect when gamepad connected/disconnect
window.addEventListener('gamepadconnected', ControllerShortcut.#updateProfileList);
window.addEventListener('gamepaddisconnected', ControllerShortcut.#updateProfileList);
window.addEventListener('gamepadconnected', ControllerShortcut.updateProfileList);
window.addEventListener('gamepaddisconnected', ControllerShortcut.updateProfileList);
ControllerShortcut.#updateProfileList();
ControllerShortcut.updateProfileList();
return $container;
}

View File

@ -30,7 +30,7 @@ export class Dialog {
} = options;
// Create dialog overlay
const $overlay = document.querySelector('.bx-dialog-overlay') as HTMLElement;
const $overlay = document.querySelector<HTMLElement>('.bx-dialog-overlay');
if (!$overlay) {
this.$overlay = CE('div', {'class': 'bx-dialog-overlay bx-gone'});

View File

@ -1,6 +1,16 @@
import { BxEvent } from "@/utils/bx-event";
export abstract class BaseGameBarAction {
abstract $content: HTMLElement;
constructor() {}
reset() {}
abstract render(): HTMLElement;
onClick(e: Event) {
BxEvent.dispatch(window, BxEvent.GAME_BAR_ACTION_ACTIVATED);
};
render(): HTMLElement {
return this.$content;
};
}

View File

@ -1,7 +1,6 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { t } from "@utils/translation";
import { BaseGameBarAction } from "./action-base";
import { MicrophoneShortcut, MicrophoneState } from "../shortcuts/shortcut-microphone";
@ -9,58 +8,42 @@ import { MicrophoneShortcut, MicrophoneState } from "../shortcuts/shortcut-micro
export class MicrophoneAction extends BaseGameBarAction {
$content: HTMLElement;
visible: boolean = false;
constructor() {
super();
const onClick = (e: Event) => {
BxEvent.dispatch(window, BxEvent.GAME_BAR_ACTION_ACTIVATED);
const enabled = MicrophoneShortcut.toggle(false);
this.$content.setAttribute('data-enabled', enabled.toString());
};
const $btnDefault = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.MICROPHONE,
title: t('show-touch-controller'),
onClick: onClick,
onClick: this.onClick.bind(this),
classes: ['bx-activated'],
});
const $btnMuted = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.MICROPHONE_MUTED,
title: t('hide-touch-controller'),
onClick: onClick,
onClick: this.onClick.bind(this),
});
this.$content = CE('div', {},
$btnDefault,
$btnMuted,
);
this.reset();
this.$content = CE('div', {}, $btnMuted, $btnDefault);
window.addEventListener(BxEvent.MICROPHONE_STATE_CHANGED, e => {
const microphoneState = (e as any).microphoneState;
const enabled = microphoneState === MicrophoneState.ENABLED;
this.$content.setAttribute('data-enabled', enabled.toString());
this.$content.dataset.activated = enabled.toString();
// Show the button in Game Bar if the mic is enabled
this.$content.classList.remove('bx-gone');
});
}
render(): HTMLElement {
return this.$content;
onClick(e: Event) {
super.onClick(e);
const enabled = MicrophoneShortcut.toggle(false);
this.$content.dataset.activated = enabled.toString();
}
reset(): void {
this.visible = false;
this.$content.classList.add('bx-gone');
this.$content.setAttribute('data-enabled', 'false');
this.$content.dataset.activated = 'false';
}
}

View File

@ -0,0 +1,38 @@
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BaseGameBarAction } from "./action-base";
import { RendererShortcut } from "../shortcuts/shortcut-renderer";
export class RendererAction extends BaseGameBarAction {
$content: HTMLElement;
constructor() {
super();
const $btnDefault = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.EYE,
onClick: this.onClick.bind(this),
});
const $btnActivated = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.EYE_SLASH,
onClick: this.onClick.bind(this),
classes: ['bx-activated'],
});
this.$content = CE('div', {}, $btnDefault, $btnActivated);
}
onClick(e: Event) {
super.onClick(e);
const isVisible = RendererShortcut.toggleVisibility();
this.$content.dataset.activated = (!isVisible).toString();
}
reset(): void {
this.$content.dataset.activated = 'false';
}
}

View File

@ -1,9 +1,8 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle } from "@utils/html";
import { BaseGameBarAction } from "./action-base";
import { t } from "@utils/translation";
import { Screenshot } from "@/utils/screenshot";
import { ScreenshotManager } from "@/utils/screenshot-manager";
export class ScreenshotAction extends BaseGameBarAction {
$content: HTMLElement;
@ -11,20 +10,16 @@ export class ScreenshotAction extends BaseGameBarAction {
constructor() {
super();
const onClick = (e: Event) => {
BxEvent.dispatch(window, BxEvent.GAME_BAR_ACTION_ACTIVATED);
Screenshot.takeScreenshot();
};
this.$content = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.SCREENSHOT,
title: t('take-screenshot'),
onClick: onClick,
});
style: ButtonStyle.GHOST,
icon: BxIcon.SCREENSHOT,
title: t('take-screenshot'),
onClick: this.onClick.bind(this),
});
}
render(): HTMLElement {
return this.$content;
onClick(e: Event): void {
super.onClick(e);
ScreenshotManager.getInstance().takeScreenshot();
}
}

View File

@ -0,0 +1,45 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BaseGameBarAction } from "./action-base";
import { SoundShortcut, SpeakerState } from "../shortcuts/shortcut-sound";
export class SpeakerAction extends BaseGameBarAction {
$content: HTMLElement;
constructor() {
super();
const $btnEnable = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.AUDIO,
onClick: this.onClick.bind(this),
});
const $btnMuted = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.SPEAKER_MUTED,
onClick: this.onClick.bind(this),
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.dataset.activated = (!enabled).toString();
});
}
onClick(e: Event) {
super.onClick(e);
SoundShortcut.muteUnmute();
}
reset(): void {
this.$content.dataset.activated = 'false';
}
}

View File

@ -1,4 +1,3 @@
import { BxEvent } from "@utils/bx-event";
import { BxIcon } from "@utils/bx-icon";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { TouchController } from "@modules/touch-controller";
@ -11,44 +10,31 @@ export class TouchControlAction extends BaseGameBarAction {
constructor() {
super();
const onClick = (e: Event) => {
BxEvent.dispatch(window, BxEvent.GAME_BAR_ACTION_ACTIVATED);
const $parent = (e as any).target.closest('div[data-enabled]');
let enabled = $parent.getAttribute('data-enabled', 'true') === 'true';
$parent.setAttribute('data-enabled', (!enabled).toString());
TouchController.toggleVisibility(enabled);
};
const $btnEnable = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.TOUCH_CONTROL_ENABLE,
title: t('show-touch-controller'),
onClick: onClick,
classes: ['bx-activated'],
onClick: this.onClick.bind(this),
});
const $btnDisable = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.TOUCH_CONTROL_DISABLE,
title: t('hide-touch-controller'),
onClick: onClick,
onClick: this.onClick.bind(this),
classes: ['bx-activated'],
});
this.$content = CE('div', {},
$btnEnable,
$btnDisable,
);
this.reset();
this.$content = CE('div', {}, $btnEnable, $btnDisable);
}
render(): HTMLElement {
return this.$content;
onClick(e: Event) {
super.onClick(e);
const isVisible = TouchController.toggleVisibility();
this.$content.dataset.activated = (!isVisible).toString();
}
reset(): void {
this.$content.setAttribute('data-enabled', 'true');
this.$content.dataset.activated = 'false';
}
}

View File

@ -0,0 +1,23 @@
import { BxIcon } from "@/utils/bx-icon";
import { createButton, ButtonStyle } from "@/utils/html";
import { BaseGameBarAction } from "./action-base";
import { TrueAchievements } from "@/utils/true-achievements";
export class TrueAchievementsAction extends BaseGameBarAction {
$content: HTMLElement;
constructor() {
super();
this.$content = createButton({
style: ButtonStyle.GHOST,
icon: BxIcon.TRUE_ACHIEVEMENTS,
onClick: this.onClick.bind(this),
});
}
onClick(e: Event) {
super.onClick(e);
TrueAchievements.getInstance().open(false);
}
}

View File

@ -7,43 +7,46 @@ import type { BaseGameBarAction } from "./action-base";
import { STATES } from "@utils/global";
import { MicrophoneAction } from "./action-microphone";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { getPref, StreamTouchController, type GameBarPosition } from "@/utils/settings-storages/global-settings-storage";
import { TrueAchievementsAction } from "./action-true-achievements";
import { SpeakerAction } from "./action-speaker";
import { RendererAction } from "./action-renderer";
import { BxLogger } from "@/utils/bx-logger";
export class GameBar {
private static instance: GameBar;
public static getInstance(): GameBar {
if (!GameBar.instance) {
GameBar.instance = new GameBar();
}
return GameBar.instance;
}
public static getInstance = () => GameBar.instance ?? (GameBar.instance = new GameBar());
private readonly LOG_TAG = 'GameBar';
private static readonly VISIBLE_DURATION = 2000;
private $gameBar: HTMLElement;
private $container: HTMLElement;
private timeout: number | null = null;
private timeoutId: number | null = null;
private actions: BaseGameBarAction[] = [];
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
let $container;
const position = getPref(PrefKey.GAME_BAR_POSITION);
const position = getPref(PrefKey.GAME_BAR_POSITION) as GameBarPosition;
const $gameBar = CE('div', {id: 'bx-game-bar', class: 'bx-gone', 'data-position': position},
$container = CE('div', {class: 'bx-game-bar-container bx-offscreen'}),
createSvgIcon(position === 'bottom-left' ? BxIcon.CARET_RIGHT : BxIcon.CARET_LEFT),
);
$container = CE('div', {class: 'bx-game-bar-container bx-offscreen'}),
createSvgIcon(position === 'bottom-left' ? BxIcon.CARET_RIGHT : BxIcon.CARET_LEFT),
);
this.actions = [
new ScreenshotAction(),
...(STATES.userAgent.capabilities.touch && (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) !== 'off') ? [new TouchControlAction()] : []),
...(STATES.userAgent.capabilities.touch && (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) !== StreamTouchController.OFF) ? [new TouchControlAction()] : []),
new SpeakerAction(),
new RendererAction(),
new MicrophoneAction(),
new TrueAchievementsAction(),
];
// Reverse the action list if Game Bar's position is on the right side
@ -73,11 +76,7 @@ export class GameBar {
// Add animation when hiding game bar
$container.addEventListener('transitionend', e => {
const classList = $container.classList;
if (classList.contains('bx-hide')) {
classList.remove('bx-offscreen', 'bx-hide');
classList.add('bx-offscreen');
}
$container.classList.replace('bx-hide', 'bx-offscreen');
});
document.documentElement.appendChild($gameBar);
@ -86,58 +85,47 @@ export class GameBar {
// Enable/disable Game Bar when playing/pausing
getPref(PrefKey.GAME_BAR_POSITION) !== 'off' && window.addEventListener(BxEvent.XCLOUD_POLLING_MODE_CHANGED, ((e: Event) => {
if (!STATES.isPlaying) {
this.disable();
return;
}
// Toggle Game bar
const mode = (e as any).mode;
mode !== 'None' ? this.disable() : this.enable();
if (STATES.isPlaying) {
const mode = (e as any).mode;
mode !== 'none' ? this.disable() : this.enable();
}
}).bind(this));
}
private beginHideTimeout() {
this.clearHideTimeout();
this.timeout = window.setTimeout(() => {
this.timeout = null;
this.hideBar();
}, GameBar.VISIBLE_DURATION);
this.timeoutId = window.setTimeout(() => {
this.timeoutId = null;
this.hideBar();
}, GameBar.VISIBLE_DURATION);
}
private clearHideTimeout() {
this.timeout && clearTimeout(this.timeout);
this.timeout = null;
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = null;
}
enable() {
this.$gameBar && this.$gameBar.classList.remove('bx-gone');
this.$gameBar.classList.remove('bx-gone');
}
disable() {
this.hideBar();
this.$gameBar && this.$gameBar.classList.add('bx-gone');
this.$gameBar.classList.add('bx-gone');
}
showBar() {
if (!this.$container) {
return;
}
this.$container.classList.remove('bx-offscreen', 'bx-hide');
this.$container.classList.remove('bx-offscreen', 'bx-hide' , 'bx-gone');
this.$container.classList.add('bx-show');
this.beginHideTimeout();
}
hideBar() {
if (!this.$container) {
return;
}
this.$container.classList.remove('bx-show');
this.$container.classList.add('bx-hide');
this.clearHideTimeout();
this.$container.classList.replace('bx-show', 'bx-hide');
}
// Reset all states

View File

@ -4,15 +4,16 @@ 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 { compressCss } from "@macros/build" with {type: "macro"};
export class LoadingScreen {
static #$bgStyle: HTMLElement;
static #$waitTimeBox: HTMLElement;
private static $bgStyle: HTMLElement;
private static $waitTimeBox: HTMLElement;
static #waitTimeInterval?: number | null = null;
static #orgWebTitle: string;
private static waitTimeInterval?: number | null = null;
private static orgWebTitle: string;
static #secondsToString(seconds: number) {
private static secondsToString(seconds: number) {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
@ -27,23 +28,23 @@ export class LoadingScreen {
return;
}
if (!LoadingScreen.#$bgStyle) {
if (!LoadingScreen.$bgStyle) {
const $bgStyle = CE('style');
document.documentElement.appendChild($bgStyle);
LoadingScreen.#$bgStyle = $bgStyle;
LoadingScreen.$bgStyle = $bgStyle;
}
LoadingScreen.#setBackground(titleInfo.product.heroImageUrl || titleInfo.product.titledHeroImageUrl || titleInfo.product.tileImageUrl);
LoadingScreen.setBackground(titleInfo.product.heroImageUrl || titleInfo.product.titledHeroImageUrl || titleInfo.product.tileImageUrl);
if (getPref(PrefKey.UI_LOADING_SCREEN_ROCKET) === 'hide') {
LoadingScreen.#hideRocket();
LoadingScreen.hideRocket();
}
}
static #hideRocket() {
let $bgStyle = LoadingScreen.#$bgStyle;
private static hideRocket() {
let $bgStyle = LoadingScreen.$bgStyle;
const css = `
$bgStyle.textContent! += compressCss(`
#game-stream div[class*=RocketAnimation-module__container] > svg {
display: none;
}
@ -51,20 +52,18 @@ export class LoadingScreen {
#game-stream video[class*=RocketAnimationVideo-module__video] {
display: none;
}
`;
$bgStyle.textContent += css;
`);
}
static #setBackground(imageUrl: string) {
private static setBackground(imageUrl: string) {
// Setup style tag
let $bgStyle = LoadingScreen.#$bgStyle;
let $bgStyle = LoadingScreen.$bgStyle;
// Limit max width to reduce image size
imageUrl = imageUrl + '?w=1920';
const css = `
$bgStyle.textContent! += compressCss(`
#game-stream {
background-image: linear-gradient(#00000033, #000000e6), url(${imageUrl}) !important;
background-color: transparent !important;
background-position: center center !important;
background-repeat: no-repeat !important;
@ -74,16 +73,15 @@ export class LoadingScreen {
#game-stream rect[width="800"] {
transition: opacity 0.3s ease-in-out !important;
}
`;
$bgStyle.textContent += css;
`) + `#game-stream {background-image: linear-gradient(#00000033, #000000e6), url(${imageUrl}) !important;}`;
const bg = new Image();
bg.onload = e => {
$bgStyle.textContent += `
$bgStyle.textContent += compressCss(`
#game-stream rect[width="800"] {
opacity: 0 !important;
}
`;
`);
};
bg.src = imageUrl;
}
@ -91,14 +89,14 @@ export class LoadingScreen {
static setupWaitTime(waitTime: number) {
// Hide rocket when queing
if (getPref(PrefKey.UI_LOADING_SCREEN_ROCKET) === 'hide-queue') {
LoadingScreen.#hideRocket();
LoadingScreen.hideRocket();
}
let secondsLeft = waitTime;
let $countDown;
let $estimated;
LoadingScreen.#orgWebTitle = document.title;
LoadingScreen.orgWebTitle = document.title;
const endDate = new Date();
const timeZoneOffsetSeconds = endDate.getTimezoneOffset() * 60;
@ -106,9 +104,9 @@ export class LoadingScreen {
let endDateStr = endDate.toISOString().slice(0, 19);
endDateStr = endDateStr.substring(0, 10) + ' ' + endDateStr.substring(11, 19);
endDateStr += ` (${LoadingScreen.#secondsToString(waitTime)})`;
endDateStr += ` (${LoadingScreen.secondsToString(waitTime)})`;
let $waitTimeBox = LoadingScreen.#$waitTimeBox;
let $waitTimeBox = LoadingScreen.$waitTimeBox;
if (!$waitTimeBox) {
$waitTimeBox = CE('div', {'class': 'bx-wait-time-box'},
CE('label', {}, t('server')),
@ -120,7 +118,7 @@ export class LoadingScreen {
);
document.documentElement.appendChild($waitTimeBox);
LoadingScreen.#$waitTimeBox = $waitTimeBox;
LoadingScreen.$waitTimeBox = $waitTimeBox;
} else {
$waitTimeBox.classList.remove('bx-gone');
$estimated = $waitTimeBox.querySelector('.bx-wait-time-estimated')!;
@ -128,50 +126,50 @@ export class LoadingScreen {
}
$estimated.textContent = endDateStr;
$countDown.textContent = LoadingScreen.#secondsToString(secondsLeft);
document.title = `[${$countDown.textContent}] ${LoadingScreen.#orgWebTitle}`;
$countDown.textContent = LoadingScreen.secondsToString(secondsLeft);
document.title = `[${$countDown.textContent}] ${LoadingScreen.orgWebTitle}`;
LoadingScreen.#waitTimeInterval = window.setInterval(() => {
LoadingScreen.waitTimeInterval = window.setInterval(() => {
secondsLeft--;
$countDown.textContent = LoadingScreen.#secondsToString(secondsLeft);
document.title = `[${$countDown.textContent}] ${LoadingScreen.#orgWebTitle}`;
$countDown.textContent = LoadingScreen.secondsToString(secondsLeft);
document.title = `[${$countDown.textContent}] ${LoadingScreen.orgWebTitle}`;
if (secondsLeft <= 0) {
LoadingScreen.#waitTimeInterval && clearInterval(LoadingScreen.#waitTimeInterval);
LoadingScreen.#waitTimeInterval = null;
LoadingScreen.waitTimeInterval && clearInterval(LoadingScreen.waitTimeInterval);
LoadingScreen.waitTimeInterval = null;
}
}, 1000);
}
static hide() {
LoadingScreen.#orgWebTitle && (document.title = LoadingScreen.#orgWebTitle);
LoadingScreen.#$waitTimeBox && LoadingScreen.#$waitTimeBox.classList.add('bx-gone');
LoadingScreen.orgWebTitle && (document.title = LoadingScreen.orgWebTitle);
LoadingScreen.$waitTimeBox && LoadingScreen.$waitTimeBox.classList.add('bx-gone');
if (getPref(PrefKey.UI_LOADING_SCREEN_GAME_ART) && LoadingScreen.#$bgStyle) {
if (getPref(PrefKey.UI_LOADING_SCREEN_GAME_ART) && LoadingScreen.$bgStyle) {
const $rocketBg = document.querySelector('#game-stream rect[width="800"]');
$rocketBg && $rocketBg.addEventListener('transitionend', e => {
LoadingScreen.#$bgStyle.textContent += `
LoadingScreen.$bgStyle.textContent += compressCss(`
#game-stream {
background: #000 !important;
}
`;
`);
});
LoadingScreen.#$bgStyle.textContent += `
LoadingScreen.$bgStyle.textContent += compressCss(`
#game-stream rect[width="800"] {
opacity: 1 !important;
}
`;
`);
}
setTimeout(LoadingScreen.reset, 2000);
}
static reset() {
LoadingScreen.#$bgStyle && (LoadingScreen.#$bgStyle.textContent = '');
LoadingScreen.$bgStyle && (LoadingScreen.$bgStyle.textContent = '');
LoadingScreen.#$waitTimeBox && LoadingScreen.#$waitTimeBox.classList.add('bx-gone');
LoadingScreen.#waitTimeInterval && clearInterval(LoadingScreen.#waitTimeInterval);
LoadingScreen.#waitTimeInterval = null;
LoadingScreen.$waitTimeBox && LoadingScreen.$waitTimeBox.classList.add('bx-gone');
LoadingScreen.waitTimeInterval && clearInterval(LoadingScreen.waitTimeInterval);
LoadingScreen.waitTimeInterval = null;
}
}

View File

@ -1,10 +1,11 @@
import { isFullVersion } from "@macros/build" with {type: "macro"};
import { MkbPreset } from "./mkb-preset";
import { GamepadKey, MkbPresetKey, GamepadStick, MouseMapTo, WheelCode } from "@enums/mkb";
import { createButton, ButtonStyle, CE } from "@utils/html";
import { BxEvent } from "@utils/bx-event";
import { Toast } from "@utils/toast";
import { t } from "@utils/translation";
import { LocalDb } from "@utils/local-db";
import { KeyHelper } from "./key-helper";
import type { MkbStoredPreset } from "@/types/mkb";
import { AppInterface, STATES } from "@utils/global";
@ -17,8 +18,7 @@ import { SettingsNavigationDialog } from "../ui/dialog/settings-dialog";
import { NavigationDialogManager } from "../ui/dialog/navigation-dialog";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
const LOG_TAG = 'MkbHandler';
import { MkbPresetsDb } from "@/utils/local-db/mkb-presets-db";
const PointerToMouseButton = {
1: 0,
@ -26,6 +26,7 @@ const PointerToMouseButton = {
4: 1,
}
export const VIRTUAL_GAMEPAD_ID = 'Xbox 360 Controller';
class WebSocketMouseDataProvider extends MouseDataProvider {
#pointerClient: PointerClient | undefined
@ -121,14 +122,9 @@ This class uses some code from Yuzu emulator to handle mouse's movements
Source: https://github.com/yuzu-emu/yuzu-mainline/blob/master/src/input_common/drivers/mouse.cpp
*/
export class EmulatedMkbHandler extends MkbHandler {
static #instance: EmulatedMkbHandler;
public static getInstance(): EmulatedMkbHandler {
if (!EmulatedMkbHandler.#instance) {
EmulatedMkbHandler.#instance = new EmulatedMkbHandler();
}
return EmulatedMkbHandler.#instance;
}
private static instance: EmulatedMkbHandler;
public static getInstance = () => EmulatedMkbHandler.instance ?? (EmulatedMkbHandler.instance = new EmulatedMkbHandler());
private static readonly LOG_TAG = 'EmulatedMkbHandler';
#CURRENT_PRESET_DATA = MkbPreset.convert(MkbPreset.DEFAULT_PRESET);
@ -136,10 +132,8 @@ export class EmulatedMkbHandler extends MkbHandler {
static readonly DEFAULT_DEADZONE_COUNTERWEIGHT = 0.01;
static readonly MAXIMUM_STICK_RANGE = 1.1;
static VIRTUAL_GAMEPAD_ID = 'Xbox 360 Controller';
#VIRTUAL_GAMEPAD = {
id: EmulatedMkbHandler.VIRTUAL_GAMEPAD_ID,
id: VIRTUAL_GAMEPAD_ID,
index: 3,
connected: false,
hapticActuators: null,
@ -172,8 +166,9 @@ export class EmulatedMkbHandler extends MkbHandler {
#RIGHT_STICK_X: GamepadKey[] = [];
#RIGHT_STICK_Y: GamepadKey[] = [];
constructor() {
private constructor() {
super();
BxLogger.info(EmulatedMkbHandler.LOG_TAG, 'constructor()');
this.#STICK_MAP = {
[GamepadKey.LS_LEFT]: [this.#LEFT_STICK_X, 0, -1],
@ -436,7 +431,7 @@ export class EmulatedMkbHandler extends MkbHandler {
#getCurrentPreset = (): Promise<MkbStoredPreset> => {
return new Promise(resolve => {
const presetId = getPref(PrefKey.MKB_DEFAULT_PRESET_ID);
LocalDb.INSTANCE.getPreset(presetId).then((preset: MkbStoredPreset) => {
MkbPresetsDb.getInstance().getPreset(presetId).then((preset: MkbStoredPreset) => {
resolve(preset);
});
});
@ -459,7 +454,7 @@ export class EmulatedMkbHandler extends MkbHandler {
}
const mode = (e as any).mode;
if (mode === 'None') {
if (mode === 'none') {
this.#$message.classList.remove('bx-offscreen');
} else {
this.#$message.classList.add('bx-offscreen');
@ -678,14 +673,14 @@ export class EmulatedMkbHandler extends MkbHandler {
}
static setupEvents() {
window.addEventListener(BxEvent.STREAM_PLAYING, () => {
isFullVersion() && window.addEventListener(BxEvent.STREAM_PLAYING, () => {
if (STATES.currentStream.titleInfo?.details.hasMkbSupport) {
// Enable native MKB in Android app
if (AppInterface && getPref(PrefKey.NATIVE_MKB_ENABLED) === 'on') {
AppInterface && NativeMkbHandler.getInstance().init();
}
} else if (getPref(PrefKey.MKB_ENABLED) && (AppInterface || !UserAgent.isMobile())) {
BxLogger.info(LOG_TAG, 'Emulate MKB');
BxLogger.info(EmulatedMkbHandler.LOG_TAG, 'Emulate MKB');
EmulatedMkbHandler.getInstance().init();
}
});

View File

@ -130,7 +130,6 @@ export class MkbPreset {
mouse[MkbPresetKey.MOUSE_MAP_TO] = MkbPreset.MOUSE_SETTINGS[MkbPresetKey.MOUSE_MAP_TO].default;
}
console.log(obj);
return obj;
}
}

View File

@ -1,10 +1,9 @@
import { CE, createButton, ButtonStyle } from "@utils/html";
import { CE, createButton, ButtonStyle, removeChildElements } from "@utils/html";
import { t } from "@utils/translation";
import { Dialog } from "@modules/dialog";
import { KeyHelper } from "./key-helper";
import { MkbPreset } from "./mkb-preset";
import { EmulatedMkbHandler } from "./mkb-handler";
import { LocalDb } from "@utils/local-db";
import { BxIcon } from "@utils/bx-icon";
import type { MkbPresetData, MkbStoredPresets } from "@/types/mkb";
import { MkbPresetKey, GamepadKey, GamepadKeyName } from "@enums/mkb";
@ -12,18 +11,10 @@ import { deepClone } from "@utils/global";
import { SettingElement } from "@/utils/setting-element";
import { PrefKey } from "@/enums/pref-keys";
import { getPref, setPref } from "@/utils/settings-storages/global-settings-storage";
import { MkbPresetsDb } from "@/utils/local-db/mkb-presets-db";
import { BxLogger } from "@/utils/bx-logger";
type MkbRemapperElements = {
wrapper: HTMLElement | null;
presetsSelect: HTMLSelectElement | null;
activateButton: HTMLButtonElement | null;
currentBindingKey: HTMLElement | null;
allKeyElements: HTMLElement[];
allMouseElements: {[key in MkbPresetKey]?: HTMLElement};
};
type MkbRemapperStates = {
currentPresetId: number;
presets: MkbStoredPresets;
@ -33,7 +24,7 @@ type MkbRemapperStates = {
};
export class MkbRemapper {
readonly #BUTTON_ORDERS = [
private readonly BUTTON_ORDERS = [
GamepadKey.UP,
GamepadKey.DOWN,
GamepadKey.LEFT,
@ -66,169 +57,170 @@ export class MkbRemapper {
GamepadKey.RS_RIGHT,
];
static #instance: MkbRemapper;
static get INSTANCE() {
if (!MkbRemapper.#instance) {
MkbRemapper.#instance = new MkbRemapper();
}
private static instance: MkbRemapper;
public static getInstance = () => MkbRemapper.instance ?? (MkbRemapper.instance = new MkbRemapper());
private readonly LOG_TAG = 'MkbRemapper';
return MkbRemapper.#instance;
};
#STATE: MkbRemapperStates = {
private states: MkbRemapperStates = {
currentPresetId: 0,
presets: {},
editingPresetData: null,
isEditing: false,
};
#$: MkbRemapperElements = {
wrapper: null,
presetsSelect: null,
activateButton: null,
private $wrapper!: HTMLElement;
private $presetsSelect!: HTMLSelectElement;
private $activateButton!: HTMLButtonElement;
currentBindingKey: null,
private $currentBindingKey!: HTMLElement;
allKeyElements: [],
allMouseElements: {},
};
private allKeyElements: HTMLElement[] = [];
private allMouseElements: {[key in MkbPresetKey]?: HTMLElement} = {};
bindingDialog: Dialog;
constructor() {
this.#STATE.currentPresetId = getPref(PrefKey.MKB_DEFAULT_PRESET_ID);
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.states.currentPresetId = getPref(PrefKey.MKB_DEFAULT_PRESET_ID);
this.bindingDialog = new Dialog({
className: 'bx-binding-dialog',
content: CE('div', {},
CE('p', {}, t('press-to-bind')),
CE('i', {}, t('press-esc-to-cancel')),
),
CE('p', {}, t('press-to-bind')),
CE('i', {}, t('press-esc-to-cancel')),
),
hideCloseButton: true,
});
}
#clearEventListeners = () => {
window.removeEventListener('keydown', this.#onKeyDown);
window.removeEventListener('mousedown', this.#onMouseDown);
window.removeEventListener('wheel', this.#onWheel);
private clearEventListeners = () => {
window.removeEventListener('keydown', this.onKeyDown);
window.removeEventListener('mousedown', this.onMouseDown);
window.removeEventListener('wheel', this.onWheel);
};
#bindKey = ($elm: HTMLElement, key: any) => {
const buttonIndex = parseInt($elm.getAttribute('data-button-index')!);
const keySlot = parseInt($elm.getAttribute('data-key-slot')!);
private bindKey = ($elm: HTMLElement, key: any) => {
const buttonIndex = parseInt($elm.dataset.buttonIndex!);
const keySlot = parseInt($elm.dataset.keySlot!);
// Ignore if bind the save key to the same element
if ($elm.getAttribute('data-key-code') === key.code) {
if ($elm.dataset.keyCode! === key.code) {
return;
}
// Unbind duplicated keys
for (const $otherElm of this.#$.allKeyElements) {
if ($otherElm.getAttribute('data-key-code') === key.code) {
this.#unbindKey($otherElm);
for (const $otherElm of this.allKeyElements) {
if ($otherElm.dataset.keyCode === key.code) {
this.unbindKey($otherElm);
}
}
this.#STATE.editingPresetData!.mapping[buttonIndex][keySlot] = key.code;
this.states.editingPresetData!.mapping[buttonIndex][keySlot] = key.code;
$elm.textContent = key.name;
$elm.setAttribute('data-key-code', key.code);
$elm.dataset.keyCode = key.code;
}
#unbindKey = ($elm: HTMLElement) => {
const buttonIndex = parseInt($elm.getAttribute('data-button-index')!);
const keySlot = parseInt($elm.getAttribute('data-key-slot')!);
private unbindKey = ($elm: HTMLElement) => {
const buttonIndex = parseInt($elm.dataset.buttonIndex!);
const keySlot = parseInt($elm.dataset.keySlot!);
// Remove key from preset
this.#STATE.editingPresetData!.mapping[buttonIndex][keySlot] = null;
this.states.editingPresetData!.mapping[buttonIndex][keySlot] = null;
$elm.textContent = '';
$elm.removeAttribute('data-key-code');
delete $elm.dataset.keyCode;
}
#onWheel = (e: WheelEvent) => {
private onWheel = (e: WheelEvent) => {
e.preventDefault();
this.#clearEventListeners();
this.clearEventListeners();
this.#bindKey(this.#$.currentBindingKey!, KeyHelper.getKeyFromEvent(e));
this.bindKey(this.$currentBindingKey!, KeyHelper.getKeyFromEvent(e));
window.setTimeout(() => this.bindingDialog.hide(), 200);
};
#onMouseDown = (e: MouseEvent) => {
private onMouseDown = (e: MouseEvent) => {
e.preventDefault();
this.#clearEventListeners();
this.clearEventListeners();
this.#bindKey(this.#$.currentBindingKey!, KeyHelper.getKeyFromEvent(e));
this.bindKey(this.$currentBindingKey!, KeyHelper.getKeyFromEvent(e));
window.setTimeout(() => this.bindingDialog.hide(), 200);
};
#onKeyDown = (e: KeyboardEvent) => {
private onKeyDown = (e: KeyboardEvent) => {
e.preventDefault();
e.stopPropagation();
this.#clearEventListeners();
this.clearEventListeners();
if (e.code !== 'Escape') {
this.#bindKey(this.#$.currentBindingKey!, KeyHelper.getKeyFromEvent(e));
this.bindKey(this.$currentBindingKey!, KeyHelper.getKeyFromEvent(e));
}
window.setTimeout(() => this.bindingDialog.hide(), 200);
};
#onBindingKey = (e: MouseEvent) => {
if (!this.#STATE.isEditing || e.button !== 0) {
private onBindingKey = (e: MouseEvent) => {
if (!this.states.isEditing || e.button !== 0) {
return;
}
console.log(e);
this.#$.currentBindingKey = e.target as HTMLElement;
this.$currentBindingKey = e.target as HTMLElement;
window.addEventListener('keydown', this.#onKeyDown);
window.addEventListener('mousedown', this.#onMouseDown);
window.addEventListener('wheel', this.#onWheel);
window.addEventListener('keydown', this.onKeyDown);
window.addEventListener('mousedown', this.onMouseDown);
window.addEventListener('wheel', this.onWheel);
this.bindingDialog.show({title: this.#$.currentBindingKey.getAttribute('data-prompt')!});
this.bindingDialog.show({title: this.$currentBindingKey.dataset.prompt!});
};
#onContextMenu = (e: Event) => {
private onContextMenu = (e: Event) => {
e.preventDefault();
if (!this.#STATE.isEditing) {
if (!this.states.isEditing) {
return;
}
this.#unbindKey(e.target as HTMLElement);
this.unbindKey(e.target as HTMLElement);
};
#getPreset = (presetId: number) => {
return this.#STATE.presets[presetId];
private getPreset = (presetId: number) => {
return this.states.presets[presetId];
}
#getCurrentPreset = () => {
return this.#getPreset(this.#STATE.currentPresetId);
private getCurrentPreset = () => {
let preset = this.getPreset(this.states.currentPresetId);
if (!preset) {
// Get the first preset in the list
const firstPresetId = parseInt(Object.keys(this.states.presets)[0]);
preset = this.states.presets[firstPresetId];
this.states.currentPresetId = firstPresetId;
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, firstPresetId);
}
return preset;
}
#switchPreset = (presetId: number) => {
this.#STATE.currentPresetId = presetId;
const presetData = this.#getCurrentPreset().data;
private switchPreset = (presetId: number) => {
this.states.currentPresetId = presetId;
const presetData = this.getCurrentPreset().data;
for (const $elm of this.#$.allKeyElements) {
const buttonIndex = parseInt($elm.getAttribute('data-button-index')!);
const keySlot = parseInt($elm.getAttribute('data-key-slot')!);
for (const $elm of this.allKeyElements) {
const buttonIndex = parseInt($elm.dataset.buttonIndex!);
const keySlot = parseInt($elm.dataset.keySlot!);
const buttonKeys = presetData.mapping[buttonIndex];
if (buttonKeys && buttonKeys[keySlot]) {
$elm.textContent = KeyHelper.codeToKeyName(buttonKeys[keySlot]!);
$elm.setAttribute('data-key-code', buttonKeys[keySlot]!);
$elm.dataset.keyCode = buttonKeys[keySlot]!;
} else {
$elm.textContent = '';
$elm.removeAttribute('data-key-code');
delete $elm.dataset.keyCode;
}
}
let key: MkbPresetKey;
for (key in this.#$.allMouseElements) {
const $elm = this.#$.allMouseElements[key]!;
for (key in this.allMouseElements) {
const $elm = this.allMouseElements[key]!;
let value = presetData.mouse[key];
if (typeof value === 'undefined') {
value = MkbPreset.MOUSE_SETTINGS[key].default;
@ -238,74 +230,72 @@ export class MkbRemapper {
}
// Update state of Activate button
const activated = getPref(PrefKey.MKB_DEFAULT_PRESET_ID) === this.#STATE.currentPresetId;
this.#$.activateButton!.disabled = activated;
this.#$.activateButton!.querySelector('span')!.textContent = activated ? t('activated') : t('activate');
const activated = getPref(PrefKey.MKB_DEFAULT_PRESET_ID) === this.states.currentPresetId;
this.$activateButton.disabled = activated;
this.$activateButton.querySelector('span')!.textContent = activated ? t('activated') : t('activate');
}
#refresh() {
private async refresh() {
// Clear presets select
while (this.#$.presetsSelect!.firstChild) {
this.#$.presetsSelect!.removeChild(this.#$.presetsSelect!.firstChild);
removeChildElements(this.$presetsSelect);
const presets = await MkbPresetsDb.getInstance().getPresets();
this.states.presets = presets;
const fragment = document.createDocumentFragment();
let defaultPresetId;
if (this.states.currentPresetId === 0) {
this.states.currentPresetId = parseInt(Object.keys(presets)[0]);
defaultPresetId = this.states.currentPresetId;
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, defaultPresetId);
EmulatedMkbHandler.getInstance().refreshPresetData();
} else {
defaultPresetId = getPref(PrefKey.MKB_DEFAULT_PRESET_ID);
}
LocalDb.INSTANCE.getPresets().then(presets => {
this.#STATE.presets = presets;
const $fragment = document.createDocumentFragment();
let defaultPresetId;
if (this.#STATE.currentPresetId === 0) {
this.#STATE.currentPresetId = parseInt(Object.keys(presets)[0]);
defaultPresetId = this.#STATE.currentPresetId;
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, defaultPresetId);
EmulatedMkbHandler.getInstance().refreshPresetData();
} else {
defaultPresetId = getPref(PrefKey.MKB_DEFAULT_PRESET_ID);
for (let id in presets) {
const preset = presets[id];
let name = preset.name;
if (id === defaultPresetId) {
name = `🎮 ` + name;
}
for (let id in presets) {
const preset = presets[id];
let name = preset.name;
if (id === defaultPresetId) {
name = `🎮 ` + name;
}
const $options = CE<HTMLOptionElement>('option', {value: id}, name);
$options.selected = parseInt(id) === this.states.currentPresetId;
const $options = CE<HTMLOptionElement>('option', {value: id}, name);
$options.selected = parseInt(id) === this.#STATE.currentPresetId;
fragment.appendChild($options);
};
$fragment.appendChild($options);
};
this.$presetsSelect.appendChild(fragment);
this.#$.presetsSelect!.appendChild($fragment);
// Update state of Activate button
const activated = defaultPresetId === this.states.currentPresetId;
this.$activateButton.disabled = activated;
this.$activateButton.querySelector('span')!.textContent = activated ? t('activated') : t('activate');
// Update state of Activate button
const activated = defaultPresetId === this.#STATE.currentPresetId;
this.#$.activateButton!.disabled = activated;
this.#$.activateButton!.querySelector('span')!.textContent = activated ? t('activated') : t('activate');
!this.#STATE.isEditing && this.#switchPreset(this.#STATE.currentPresetId);
});
!this.states.isEditing && this.switchPreset(this.states.currentPresetId);
}
#toggleEditing = (force?: boolean) => {
this.#STATE.isEditing = typeof force !== 'undefined' ? force : !this.#STATE.isEditing;
this.#$.wrapper!.classList.toggle('bx-editing', this.#STATE.isEditing);
private toggleEditing = (force?: boolean) => {
this.states.isEditing = typeof force !== 'undefined' ? force : !this.states.isEditing;
this.$wrapper.classList.toggle('bx-editing', this.states.isEditing);
if (this.#STATE.isEditing) {
this.#STATE.editingPresetData = deepClone(this.#getCurrentPreset().data);
if (this.states.isEditing) {
this.states.editingPresetData = deepClone(this.getCurrentPreset().data);
} else {
this.#STATE.editingPresetData = null;
this.states.editingPresetData = null;
}
const childElements = this.#$.wrapper!.querySelectorAll('select, button, input');
const childElements = this.$wrapper.querySelectorAll('select, button, input');
for (const $elm of Array.from(childElements)) {
if ($elm.parentElement!.parentElement!.classList.contains('bx-mkb-action-buttons')) {
continue;
}
let disable = !this.#STATE.isEditing;
let disable = !this.states.isEditing;
if ($elm.parentElement!.classList.contains('bx-mkb-preset-tools')) {
disable = !disable;
@ -316,14 +306,14 @@ export class MkbRemapper {
}
render() {
this.#$.wrapper = CE('div', {'class': 'bx-mkb-settings'});
this.$wrapper = CE('div', {class: 'bx-mkb-settings'});
this.#$.presetsSelect = CE<HTMLSelectElement>('select', {tabindex: -1});
this.#$.presetsSelect!.addEventListener('change', e => {
this.#switchPreset(parseInt((e.target as HTMLSelectElement).value));
this.$presetsSelect = CE<HTMLSelectElement>('select', {tabindex: -1});
this.$presetsSelect.addEventListener('change', e => {
this.switchPreset(parseInt((e.target as HTMLSelectElement).value));
});
const promptNewName = (value?: string) => {
const promptNewName = (value: string) => {
let newName: string | null = '';
while (!newName) {
newName = prompt(t('prompt-preset-name'), value);
@ -336,15 +326,15 @@ export class MkbRemapper {
return newName ? newName : false;
};
const $header = CE('div', {'class': 'bx-mkb-preset-tools'},
this.#$.presetsSelect,
const $header = CE('div', {class: 'bx-mkb-preset-tools'},
this.$presetsSelect,
// Rename button
createButton({
title: t('rename'),
icon: BxIcon.CURSOR_TEXT,
tabIndex: -1,
onClick: e => {
const preset = this.#getCurrentPreset();
onClick: async () => {
const preset = this.getCurrentPreset();
let newName = promptNewName(preset.name);
if (!newName || newName === preset.name) {
@ -353,28 +343,30 @@ export class MkbRemapper {
// Update preset with new name
preset.name = newName;
LocalDb.INSTANCE.updatePreset(preset).then(id => this.#refresh());
await MkbPresetsDb.getInstance().updatePreset(preset);
await this.refresh();
},
}),
// New button
createButton({
icon: BxIcon.NEW,
title: t('new'),
tabIndex: -1,
onClick: e => {
let newName = promptNewName('');
if (!newName) {
return;
}
icon: BxIcon.NEW,
title: t('new'),
tabIndex: -1,
onClick: e => {
let newName = promptNewName('');
if (!newName) {
return;
}
// Create new preset selected name
LocalDb.INSTANCE.newPreset(newName, MkbPreset.DEFAULT_PRESET).then(id => {
this.#STATE.currentPresetId = id;
this.#refresh();
});
},
}),
// Create new preset selected name
MkbPresetsDb.getInstance().newPreset(newName, MkbPreset.DEFAULT_PRESET).then(id => {
this.states.currentPresetId = id;
this.refresh();
});
},
}),
// Copy button
createButton({
@ -382,7 +374,7 @@ export class MkbRemapper {
title: t('copy'),
tabIndex: -1,
onClick: e => {
const preset = this.#getCurrentPreset();
const preset = this.getCurrentPreset();
let newName = promptNewName(`${preset.name} (2)`);
if (!newName) {
@ -390,9 +382,9 @@ export class MkbRemapper {
}
// Create new preset selected name
LocalDb.INSTANCE.newPreset(newName, preset.data).then(id => {
this.#STATE.currentPresetId = id;
this.#refresh();
MkbPresetsDb.getInstance().newPreset(newName, preset.data).then(id => {
this.states.currentPresetId = id;
this.refresh();
});
},
}),
@ -408,23 +400,23 @@ export class MkbRemapper {
return;
}
LocalDb.INSTANCE.deletePreset(this.#STATE.currentPresetId).then(id => {
this.#STATE.currentPresetId = 0;
this.#refresh();
MkbPresetsDb.getInstance().deletePreset(this.states.currentPresetId).then(id => {
this.states.currentPresetId = 0;
this.refresh();
});
},
}),
);
this.#$.wrapper!.appendChild($header);
this.$wrapper.appendChild($header);
const $rows = CE('div', {'class': 'bx-mkb-settings-rows'},
CE('i', {'class': 'bx-mkb-note'}, t('right-click-to-unbind')),
const $rows = CE('div', {class: 'bx-mkb-settings-rows'},
CE('i', {class: 'bx-mkb-note'}, t('right-click-to-unbind')),
);
// Render keys
const keysPerButton = 2;
for (const buttonIndex of this.#BUTTON_ORDERS) {
for (const buttonIndex of this.BUTTON_ORDERS) {
const [buttonName, buttonPrompt] = GamepadKeyName[buttonIndex];
let $elm;
@ -437,22 +429,22 @@ export class MkbRemapper {
'data-key-slot': i,
}, ' ');
$elm.addEventListener('mouseup', this.#onBindingKey);
$elm.addEventListener('contextmenu', this.#onContextMenu);
$elm.addEventListener('mouseup', this.onBindingKey);
$elm.addEventListener('contextmenu', this.onContextMenu);
$fragment.appendChild($elm);
this.#$.allKeyElements.push($elm);
this.allKeyElements.push($elm);
}
const $keyRow = CE('div', {'class': 'bx-mkb-key-row'},
CE('label', {'title': buttonName}, buttonPrompt),
const $keyRow = CE('div', {class: 'bx-mkb-key-row'},
CE('label', {title: buttonName}, buttonPrompt),
$fragment,
);
$rows.appendChild($keyRow);
}
$rows.appendChild(CE('i', {'class': 'bx-mkb-note'}, t('mkb-adjust-ingame-settings')),);
$rows.appendChild(CE('i', {class: 'bx-mkb-note'}, t('mkb-adjust-ingame-settings')),);
// Render mouse settings
const $mouseSettings = document.createDocumentFragment();
@ -463,7 +455,7 @@ export class MkbRemapper {
let $elm;
const onChange = (e: Event, value: any) => {
(this.#STATE.editingPresetData!.mouse as any)[key] = value;
(this.states.editingPresetData!.mouse as any)[key] = value;
};
const $row = CE('label', {
class: 'bx-settings-row',
@ -474,32 +466,32 @@ export class MkbRemapper {
);
$mouseSettings.appendChild($row);
this.#$.allMouseElements[key as MkbPresetKey] = $elm;
this.allMouseElements[key as MkbPresetKey] = $elm;
}
$rows.appendChild($mouseSettings);
this.#$.wrapper!.appendChild($rows);
this.$wrapper.appendChild($rows);
// Render action buttons
const $actionButtons = CE('div', {'class': 'bx-mkb-action-buttons'},
const $actionButtons = CE('div', {class: 'bx-mkb-action-buttons'},
CE('div', {},
// Edit button
createButton({
label: t('edit'),
tabIndex: -1,
onClick: e => this.#toggleEditing(true),
onClick: e => this.toggleEditing(true),
}),
// Activate button
this.#$.activateButton = createButton({
this.$activateButton = createButton({
label: t('activate'),
style: ButtonStyle.PRIMARY,
tabIndex: -1,
onClick: e => {
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, this.#STATE.currentPresetId);
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, this.states.currentPresetId);
EmulatedMkbHandler.getInstance().refreshPresetData();
this.#refresh();
this.refresh();
},
}),
),
@ -512,8 +504,8 @@ export class MkbRemapper {
tabIndex: -1,
onClick: e => {
// Restore preset
this.#switchPreset(this.#STATE.currentPresetId);
this.#toggleEditing(false);
this.switchPreset(this.states.currentPresetId);
this.toggleEditing(false);
},
}),
@ -523,27 +515,27 @@ export class MkbRemapper {
style: ButtonStyle.PRIMARY,
tabIndex: -1,
onClick: e => {
const updatedPreset = deepClone(this.#getCurrentPreset());
updatedPreset.data = this.#STATE.editingPresetData as MkbPresetData;
const updatedPreset = deepClone(this.getCurrentPreset());
updatedPreset.data = this.states.editingPresetData as MkbPresetData;
LocalDb.INSTANCE.updatePreset(updatedPreset).then(id => {
MkbPresetsDb.getInstance().updatePreset(updatedPreset).then(id => {
// If this is the default preset => refresh preset data
if (id === getPref(PrefKey.MKB_DEFAULT_PRESET_ID)) {
EmulatedMkbHandler.getInstance().refreshPresetData();
}
this.#toggleEditing(false);
this.#refresh();
this.toggleEditing(false);
this.refresh();
});
},
}),
),
);
this.#$.wrapper!.appendChild($actionButtons);
this.$wrapper.appendChild($actionButtons);
this.#toggleEditing(false);
this.#refresh();
return this.#$.wrapper;
this.toggleEditing(false);
this.refresh();
return this.$wrapper;
}
}

View File

@ -7,6 +7,7 @@ import { BxEvent } from "@/utils/bx-event";
import { ButtonStyle, CE, createButton } from "@/utils/html";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { BxLogger } from "@/utils/bx-logger";
type NativeMouseData = {
X: number,
@ -23,6 +24,9 @@ type XcloudInputSink = {
export class NativeMkbHandler extends MkbHandler {
private static instance: NativeMkbHandler;
public static getInstance = () => NativeMkbHandler.instance ?? (NativeMkbHandler.instance = new NativeMkbHandler());
private readonly LOG_TAG = 'NativeMkbHandler';
#pointerClient: PointerClient | undefined;
#enabled: boolean = false;
@ -37,12 +41,9 @@ export class NativeMkbHandler extends MkbHandler {
#$message?: HTMLElement;
public static getInstance(): NativeMkbHandler {
if (!NativeMkbHandler.instance) {
NativeMkbHandler.instance = new NativeMkbHandler();
}
return NativeMkbHandler.instance;
private constructor() {
super();
BxLogger.info(this.LOG_TAG, 'constructor()');
}
#onKeyboardEvent(e: KeyboardEvent) {
@ -69,7 +70,7 @@ export class NativeMkbHandler extends MkbHandler {
}
const mode = (e as any).mode;
if (mode === 'None') {
if (mode === 'none') {
this.#$message.classList.remove('bx-offscreen');
} else {
this.#$message.classList.add('bx-offscreen');

View File

@ -2,8 +2,6 @@ import { BxLogger } from "@/utils/bx-logger";
import { Toast } from "@/utils/toast";
import type { MkbHandler } from "./base-mkb-handler";
const LOG_TAG = 'PointerClient';
enum PointerAction {
MOVE = 1,
BUTTON_PRESS = 2,
@ -15,45 +13,44 @@ enum PointerAction {
export class PointerClient {
private static instance: PointerClient;
public static getInstance(): PointerClient {
if (!PointerClient.instance) {
PointerClient.instance = new PointerClient();
}
public static getInstance = () => PointerClient.instance ?? (PointerClient.instance = new PointerClient());
private readonly LOG_TAG = 'PointerClient';
return PointerClient.instance;
private socket: WebSocket | undefined | null;
private mkbHandler: MkbHandler | undefined;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
}
#socket: WebSocket | undefined | null;
#mkbHandler: MkbHandler | undefined;
start(port: number, mkbHandler: MkbHandler) {
if (!port) {
throw new Error('PointerServer port is 0');
}
this.#mkbHandler = mkbHandler;
this.mkbHandler = mkbHandler;
// Create WebSocket connection.
this.#socket = new WebSocket(`ws://localhost:${port}`);
this.#socket.binaryType = 'arraybuffer';
this.socket = new WebSocket(`ws://localhost:${port}`);
this.socket.binaryType = 'arraybuffer';
// Connection opened
this.#socket.addEventListener('open', (event) => {
BxLogger.info(LOG_TAG, 'connected')
this.socket.addEventListener('open', (event) => {
BxLogger.info(this.LOG_TAG, 'connected')
});
// Error
this.#socket.addEventListener('error', (event) => {
BxLogger.error(LOG_TAG, event);
this.socket.addEventListener('error', (event) => {
BxLogger.error(this.LOG_TAG, event);
Toast.show('Cannot setup mouse: ' + event);
});
this.#socket.addEventListener('close', (event) => {
this.#socket = null;
this.socket.addEventListener('close', (event) => {
this.socket = null;
});
// Listen for messages
this.#socket.addEventListener('message', (event) => {
this.socket.addEventListener('message', (event) => {
const dataView = new DataView(event.data);
let messageType = dataView.getInt8(0);
@ -84,7 +81,7 @@ export class PointerClient {
offset += Int16Array.BYTES_PER_ELEMENT;
const y = dataView.getInt16(offset);
this.#mkbHandler?.handleMouseMove({
this.mkbHandler?.handleMouseMove({
movementX: x,
movementY: y,
});
@ -94,7 +91,7 @@ export class PointerClient {
onPress(messageType: PointerAction, dataView: DataView, offset: number) {
const button = dataView.getUint8(offset);
this.#mkbHandler?.handleMouseClick({
this.mkbHandler?.handleMouseClick({
pointerButton: button,
pressed: messageType === PointerAction.BUTTON_PRESS,
});
@ -108,7 +105,7 @@ export class PointerClient {
offset += Int16Array.BYTES_PER_ELEMENT;
const hScroll = dataView.getInt16(offset);
this.#mkbHandler?.handleMouseWheel({
this.mkbHandler?.handleMouseWheel({
vertical: vScroll,
horizontal: hScroll,
});
@ -118,13 +115,13 @@ export class PointerClient {
onPointerCaptureChanged(dataView: DataView, offset: number) {
const hasCapture = dataView.getInt8(offset) === 1;
!hasCapture && this.#mkbHandler?.stop();
!hasCapture && this.mkbHandler?.stop();
}
stop() {
try {
this.#socket?.close();
this.socket?.close();
} catch (e) {}
this.#socket = null;
this.socket = null;
}
}

View File

@ -15,8 +15,9 @@ import codeVibrationAdjust from "./patches/vibration-adjust.js" with { type: "te
import { FeatureGates } from "@/utils/feature-gates.js";
import { UiSection } from "@/enums/ui-sections.js";
import { PrefKey } from "@/enums/pref-keys.js";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { getPref, StreamTouchController } from "@/utils/settings-storages/global-settings-storage";
import { GamePassCloudGallery } from "@/enums/game-pass-gallery.js";
import { t } from "@/utils/translation.js";
type PatchArray = (keyof typeof PATCHES)[];
@ -54,7 +55,7 @@ const LOG_TAG = 'Patcher';
const PATCHES = {
// Disable ApplicationInsights.track() function
disableAiTrack(str: string) {
const text = '.track=function(';
let text = '.track=function(';
const index = str.indexOf(text);
if (index < 0) {
return false;
@ -69,7 +70,7 @@ const PATCHES = {
// Set disableTelemetry() to true
disableTelemetry(str: string) {
const text = '.disableTelemetry=function(){return!1}';
let text = '.disableTelemetry=function(){return!1}';
if (!str.includes(text)) {
return false;
}
@ -78,7 +79,7 @@ const PATCHES = {
},
disableTelemetryProvider(str: string) {
const text = 'this.enableLightweightTelemetry=!';
let text = 'this.enableLightweightTelemetry=!';
if (!str.includes(text)) {
return false;
}
@ -99,7 +100,7 @@ const PATCHES = {
// Disable IndexDB logging
disableIndexDbLogging(str: string) {
const text = ',this.logsDb=new';
let text = ',this.logsDb=new';
if (!str.includes(text)) {
return false;
}
@ -111,7 +112,7 @@ const PATCHES = {
// Set custom website layout
websiteLayout(str: string) {
const text = '?"tv":"default"';
let text = '?"tv":"default"';
if (!str.includes(text)) {
return false;
}
@ -131,7 +132,7 @@ const PATCHES = {
},
remotePlayKeepAlive(str: string) {
const text = 'onServerDisconnectMessage(e){';
let text = 'onServerDisconnectMessage(e){';
if (!str.includes(text)) {
return false;
}
@ -143,7 +144,7 @@ const PATCHES = {
// Enable Remote Play feature
remotePlayConnectMode(str: string) {
const text = 'connectMode:"cloud-connect",';
let text = 'connectMode:"cloud-connect",';
if (!str.includes(text)) {
return false;
}
@ -151,25 +152,43 @@ const PATCHES = {
return str.replace(text, codeRemotePlayEnable);
},
// Disable achievement toast in Remote Play
// Remote Play: Disable achievement toast
remotePlayDisableAchievementToast(str: string) {
const text = '.AchievementUnlock:{';
let text = '.AchievementUnlock:{';
if (!str.includes(text)) {
return false;
}
const newCode = `
if (!!window.BX_REMOTE_PLAY_CONFIG) {
return;
}
`;
const newCode = `if (!!window.BX_REMOTE_PLAY_CONFIG) 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) {
const text = 'this.shouldCollectStats=!0';
let text = 'this.shouldCollectStats=!0';
if (!str.includes(text)) {
return false;
}
@ -183,16 +202,22 @@ if (!!window.BX_REMOTE_PLAY_CONFIG) {
return false;
}
const nextIndex = str.indexOf('setTimeout(this.pollGamepads', index);
if (nextIndex === -1) {
const setTimeoutIndex = str.indexOf('setTimeout(this.pollGamepads', index);
if (setTimeoutIndex < 0) {
return false;
}
let codeBlock = str.substring(index, nextIndex);
let codeBlock = str.substring(index, setTimeoutIndex);
// Patch polling rate
const tmp = str.substring(setTimeoutIndex, setTimeoutIndex + 150);
const tmpPatched = tmp.replaceAll('Math.max(0,4-', 'Math.max(0,window.BX_CONTROLLER_POLLING_RATE-');
str = PatcherUtils.replaceWith(str, setTimeoutIndex, tmp, tmpPatched);
// Block gamepad stats collecting
if (getPref(PrefKey.BLOCK_TRACKING)) {
codeBlock = codeBlock.replaceAll('this.inputPollingIntervalStats.addValue', '');
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
@ -200,17 +225,18 @@ if (!!window.BX_REMOTE_PLAY_CONFIG) {
if (match) {
const gamepadVar = match[1];
const newCode = renderString(codeControllerShortcuts, {
gamepadVar,
});
gamepadVar,
});
codeBlock = codeBlock.replace('this.gamepadTimestamps.set', newCode + 'this.gamepadTimestamps.set');
}
return str.substring(0, index) + codeBlock + str.substring(nextIndex);
str = str.substring(0, index) + codeBlock + str.substring(setTimeoutIndex);
return str;
},
enableXcloudLogger(str: string) {
const text = 'this.telemetryProvider=e}log(e,t,r){';
let text = 'this.telemetryProvider=e}log(e,t,r){';
if (!str.includes(text)) {
return false;
}
@ -226,7 +252,7 @@ logFunc(logTag, '//', logMessage);
},
enableConsoleLogging(str: string) {
const text = 'static isConsoleLoggingAllowed(){';
let text = 'static isConsoleLoggingAllowed(){';
if (!str.includes(text)) {
return false;
}
@ -237,7 +263,7 @@ logFunc(logTag, '//', logMessage);
// Control controller vibration
playVibration(str: string) {
const text = '}playVibration(e){';
let text = '}playVibration(e){';
if (!str.includes(text)) {
return false;
}
@ -278,7 +304,7 @@ logFunc(logTag, '//', logMessage);
},
patchUpdateInputConfigurationAsync(str: string) {
const text = 'async updateInputConfigurationAsync(e){';
let text = 'async updateInputConfigurationAsync(e){';
if (!str.includes(text)) {
return false;
}
@ -291,7 +317,7 @@ logFunc(logTag, '//', logMessage);
// Add patches that are only needed when start playing
loadingEndingChunks(str: string) {
const text = '"FamilySagaManager"';
let text = '"FamilySagaManager"';
if (!str.includes(text)) {
return false;
}
@ -316,7 +342,7 @@ logFunc(logTag, '//', logMessage);
},
exposeTouchLayoutManager(str: string) {
const text = 'this._perScopeLayoutsStream=new';
let text = 'this._perScopeLayoutsStream=new';
if (!str.includes(text)) {
return false;
}
@ -363,7 +389,7 @@ if (window.BX_EXPOSED.stopTakRendering) {
},
supportLocalCoOp(str: string) {
const text = 'this.gamepadMappingsToSend=[],';
let text = 'this.gamepadMappingsToSend=[],';
if (!str.includes(text)) {
return false;
}
@ -375,7 +401,7 @@ if (window.BX_EXPOSED.stopTakRendering) {
},
forceFortniteConsole(str: string) {
const text = 'sendTouchInputEnabledMessage(e){';
let text = 'sendTouchInputEnabledMessage(e){';
if (!str.includes(text)) {
return false;
}
@ -387,13 +413,13 @@ if (window.BX_EXPOSED.stopTakRendering) {
},
disableTakRenderer(str: string) {
const text = 'const{TakRenderer:';
let text = 'const{TakRenderer:';
if (!str.includes(text)) {
return false;
}
let autoOffCode = '';
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'off') {
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.OFF) {
autoOffCode = 'return;';
} else if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF)) {
autoOffCode = `
@ -427,7 +453,7 @@ if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFak
},
streamCombineSources(str: string) {
const text = 'this.useCombinedAudioVideoStream=!!this.deviceInformation.isTizen';
let text = 'this.useCombinedAudioVideoStream=!!this.deviceInformation.isTizen';
if (!str.includes(text)) {
return false;
}
@ -437,7 +463,7 @@ if (titleInfo && !titleInfo.details.hasTouchSupport && !titleInfo.details.hasFak
},
patchStreamHud(str: string) {
const text = 'let{onCollapse';
let text = 'let{onCollapse';
if (!str.includes(text)) {
return false;
}
@ -450,7 +476,7 @@ e.guideUI = null;
`;
// Remove the TAK Edit button when the touch controller is disabled
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'off') {
if (getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.OFF) {
newCode += 'e.canShowTakHUD = false;';
}
@ -459,13 +485,13 @@ e.guideUI = null;
},
broadcastPollingMode(str: string) {
const text = '.setPollingMode=e=>{';
let text = '.setPollingMode=e=>{';
if (!str.includes(text)) {
return false;
}
const newCode = `
BxEvent.dispatch(window, BxEvent.XCLOUD_POLLING_MODE_CHANGED, {mode: e});
BxEvent.dispatch(window, BxEvent.XCLOUD_POLLING_MODE_CHANGED, {mode: e.toLowerCase()});
`;
str = str.replace(text, text + newCode);
return str;
@ -483,7 +509,7 @@ BxEvent.dispatch(window, BxEvent.XCLOUD_POLLING_MODE_CHANGED, {mode: e});
},
patchXcloudTitleInfo(str: string) {
const text = 'async cloudConnect';
let text = 'async cloudConnect';
let index = str.indexOf(text);
if (index < 0) {
return false;
@ -505,7 +531,7 @@ BxLogger.info('patchXcloudTitleInfo', ${titleInfoVar});
},
patchRemotePlayMkb(str: string) {
const text = 'async homeConsoleConnect';
let text = 'async homeConsoleConnect';
let index = str.indexOf(text);
if (index < 0) {
return false;
@ -533,7 +559,7 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
},
patchAudioMediaStream(str: string) {
const text = '.srcObject=this.audioMediaStream,';
let text = '.srcObject=this.audioMediaStream,';
if (!str.includes(text)) {
return false;
}
@ -545,7 +571,7 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
},
patchCombinedAudioVideoMediaStream(str: string) {
const text = '.srcObject=this.combinedAudioVideoStream';
let text = '.srcObject=this.combinedAudioVideoStream';
if (!str.includes(text)) {
return false;
}
@ -556,7 +582,7 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
},
patchTouchControlDefaultOpacity(str: string) {
const text = 'opacityMultiplier:1';
let text = 'opacityMultiplier:1';
if (!str.includes(text)) {
return false;
}
@ -568,7 +594,7 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
},
patchShowSensorControls(str: string) {
const text = '{shouldShowSensorControls:';
let text = '{shouldShowSensorControls:';
if (!str.includes(text)) {
return false;
}
@ -581,7 +607,7 @@ BxLogger.info('patchRemotePlayMkb', ${configsVar});
/*
exposeEventTarget(str: string) {
const text ='this._eventTarget=new EventTarget';
let text ='this._eventTarget=new EventTarget';
if (!str.includes(text)) {
return false;
}
@ -598,7 +624,7 @@ window.dispatchEvent(new Event('${BxEvent.STREAM_EVENT_TARGET_READY}'))
// Class with: connectAsync(), doConnectAsync(), setPlayClient()
exposeStreamSession(str: string) {
const text =',this._connectionType=';
let text =',this._connectionType=';
if (!str.includes(text)) {
return false;
}
@ -612,17 +638,17 @@ true` + text;
},
skipFeedbackDialog(str: string) {
const text = '&&this.shouldTransitionToFeedback(';
let text = 'shouldTransitionToFeedback(e){';
if (!str.includes(text)) {
return false;
}
str = str.replace(text, '&& false ' + text);
str = str.replace(text, text + 'return !1;');
return str;
},
enableNativeMkb(str: string) {
const text = 'e.mouseSupported&&e.keyboardSupported&&e.fullscreenSupported;';
let text = 'e.mouseSupported&&e.keyboardSupported&&e.fullscreenSupported;';
if ((!str.includes(text))) {
return false;
}
@ -632,7 +658,7 @@ true` + text;
},
patchMouseAndKeyboardEnabled(str: string) {
const text = 'get mouseAndKeyboardEnabled(){';
let text = 'get mouseAndKeyboardEnabled(){';
if (!str.includes(text)) {
return false;
}
@ -642,7 +668,7 @@ true` + text;
},
exposeInputSink(str: string) {
const text = 'this.controlChannel=null,this.inputChannel=null';
let text = 'this.controlChannel=null,this.inputChannel=null';
if (!str.includes(text)) {
return false;
}
@ -654,7 +680,7 @@ true` + text;
},
disableNativeRequestPointerLock(str: string) {
const text = 'async requestPointerLock(){';
let text = 'async requestPointerLock(){';
if (!str.includes(text)) {
return false;
}
@ -665,7 +691,7 @@ true` + text;
// Fix crashing when RequestInfo.origin is empty
patchRequestInfoCrash(str: string) {
const text = 'if(!e)throw new Error("RequestInfo.origin is falsy");';
let text = 'if(!e)throw new Error("RequestInfo.origin is falsy");';
if (!str.includes(text)) {
return false;
}
@ -675,7 +701,7 @@ true` + text;
},
exposeDialogRoutes(str: string) {
const text = 'return{goBack:function(){';
let text = 'return{goBack:function(){';
if (!str.includes(text)) {
return false;
}
@ -804,15 +830,15 @@ true` + text;
const PREF_HIDE_SECTIONS = getPref(PrefKey.UI_HIDE_SECTIONS) as UiSection[];
const siglIds: GamePassCloudGallery[] = [];
const sections: Partial<Record<UiSection, GamePassCloudGallery>> = {
const sections: PartialRecord<UiSection, GamePassCloudGallery> = {
[UiSection.NATIVE_MKB]: GamePassCloudGallery.NATIVE_MKB,
[UiSection.MOST_POPULAR]: GamePassCloudGallery.MOST_POPULAR,
};
PREF_HIDE_SECTIONS.forEach(section => {
for (const section of PREF_HIDE_SECTIONS) {
const galleryId = sections[section];
galleryId && siglIds.push(galleryId);
});
};
const checkSyntax = siglIds.map(item => `siglId === "${item}"`).join(' || ');
@ -830,7 +856,7 @@ if (e && e.id) {
// Override Storage.getSettings()
overrideStorageGetSettings(str: string) {
const text = '}getSetting(e){';
let text = '}getSetting(e){';
if (!str.includes(text)) {
return false;
}
@ -894,7 +920,7 @@ if (this.baseStorageKey in window.BX_EXPOSED.overrideSettings) {
},
detectBrowserRouterReady(str: string) {
const text = 'BrowserRouter:()=>';
let text = 'BrowserRouter:()=>';
if (!str.includes(text)) {
return false;
}
@ -912,6 +938,63 @@ if (this.baseStorageKey in window.BX_EXPOSED.overrideSettings) {
str = PatcherUtils.insertAt(str, index, 'window.BxEvent.dispatch(window, window.BxEvent.XCLOUD_ROUTER_HISTORY_READY, {history: this.history});');
return str;
},
// Set Achievements list's filter default to "Locked"
guideAchievementsDefaultLocked(str: string) {
let index = str.indexOf('FilterButton-module__container');
index >= 0 && (index = PatcherUtils.lastIndexOf(str, '"All"', index, 150));
if (index < 0) {
return false;
}
str = PatcherUtils.replaceWith(str, index, '"All"', '"Locked"');
index = str.indexOf('"Guide_Achievements_Unlocked_Empty","Guide_Achievements_Locked_Empty"');
index >= 0 && (index = PatcherUtils.indexOf(str, '"All"', index, 250));
if (index < 0) {
return false;
}
str = PatcherUtils.replaceWith(str, index, '"All"', '"Locked"');
return str;
},
// Disable long touch activating context menu
disableTouchContextMenu(str: string) {
let index = str.indexOf('"ContextualCardActions-module__container');
index >= 0 && (index = str.indexOf('addEventListener("touchstart"', index));
index >= 0 && (index = PatcherUtils.lastIndexOf(str, 'return ', index, 50));
if (index < 0) {
return false;
}
str = PatcherUtils.replaceWith(str, index, 'return', 'return () => {};');
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)) {
return false;
}
str = str.replace(text, '=window.BX_EXPOSED.modifyPreloadedState(window.__PRELOADED_STATE__);');
return str;
},
};
let PATCH_ORDERS: PatchArray = [
@ -922,6 +1005,10 @@ let PATCH_ORDERS: PatchArray = [
'exposeInputSink',
] : []),
'modifyPreloadedState',
'optimizeGameSlugGenerator',
'detectBrowserRouterReady',
'patchRequestInfoCrash',
@ -933,6 +1020,8 @@ let PATCH_ORDERS: PatchArray = [
'exposeStreamSession',
'exposeDialogRoutes',
'guideAchievementsDefaultLocked',
'enableTvRoutes',
AppInterface && 'detectProductDetailsPage',
@ -948,6 +1037,10 @@ let PATCH_ORDERS: PatchArray = [
getPref(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.TOUCH) && 'ignorePlayWithTouchSection',
(getPref(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.NATIVE_MKB) || getPref(PrefKey.UI_HIDE_SECTIONS).includes(UiSection.MOST_POPULAR)) && 'ignoreSiglSections',
...(STATES.userAgent.capabilities.touch ? [
'disableTouchContextMenu',
] : []),
...(getPref(PrefKey.BLOCK_TRACKING) ? [
'disableAiTrack',
'disableTelemetry',
@ -962,6 +1055,8 @@ let PATCH_ORDERS: PatchArray = [
'remotePlayKeepAlive',
'remotePlayDirectConnectUrl',
'remotePlayDisableAchievementToast',
'remotePlayRecentlyUsedTitleIds',
'remotePlayWebTitle',
STATES.userAgent.capabilities.touch && 'patchUpdateInputConfigurationAsync',
] : []),
@ -991,9 +1086,9 @@ let PLAYING_PATCH_ORDERS: PatchArray = [
getPref(PrefKey.STREAM_DISABLE_FEEDBACK_DIALOG) && 'skipFeedbackDialog',
...(STATES.userAgent.capabilities.touch ? [
getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'all' && 'patchShowSensorControls',
getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'all' && 'exposeTouchLayoutManager',
(getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === 'off' || getPref(PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF) || !STATES.userAgent.capabilities.touch) && 'disableTakRenderer',
getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.ALL && 'patchShowSensorControls',
getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.ALL && 'exposeTouchLayoutManager',
(getPref(PrefKey.STREAM_TOUCH_CONTROLLER) === StreamTouchController.OFF || getPref(PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF) || !STATES.userAgent.capabilities.touch) && 'disableTakRenderer',
getPref(PrefKey.STREAM_TOUCH_CONTROLLER_DEFAULT_OPACITY) !== 100 && 'patchTouchControlDefaultOpacity',
'patchBabylonRendererClass',
] : []),
@ -1034,7 +1129,7 @@ export class Patcher {
return nativeBind.apply(this, arguments);
}
PatcherCache.init();
PatcherCache.getInstance().init();
if (typeof arguments[1] === 'function') {
BxLogger.info(LOG_TAG, 'Restored Function.prototype.bind()');
@ -1059,11 +1154,12 @@ export class Patcher {
let appliedPatches: PatchArray;
const patchesMap: Record<string, PatchArray> = {};
const patcherCache = PatcherCache.getInstance();
for (let id in item[1]) {
appliedPatches = [];
const cachedPatches = PatcherCache.getPatches(id);
const cachedPatches = patcherCache.getPatches(id);
if (cachedPatches) {
patchesToCheck = cachedPatches.slice(0);
patchesToCheck.push(...PATCH_ORDERS);
@ -1130,7 +1226,7 @@ export class Patcher {
}
if (Object.keys(patchesMap).length) {
PatcherCache.saveToCache(patchesMap);
patcherCache.saveToCache(patchesMap);
}
}
@ -1140,51 +1236,65 @@ export class Patcher {
}
export class PatcherCache {
static #KEY_CACHE = 'better_xcloud_patches_cache';
static #KEY_SIGNATURE = 'better_xcloud_patches_cache_signature';
private static instance: PatcherCache;
public static getInstance = () => PatcherCache.instance ?? (PatcherCache.instance = new PatcherCache());
static #CACHE: any;
private readonly KEY_CACHE = 'better_xcloud_patches_cache';
private readonly KEY_SIGNATURE = 'better_xcloud_patches_cache_signature';
static #isInitialized = false;
private CACHE: any;
private isInitialized = false;
/**
* Get patch's signature
*/
static #getSignature(): number {
private getSignature(): number {
const scriptVersion = SCRIPT_VERSION;
const webVersion = (document.querySelector('meta[name=gamepass-app-version]') as HTMLMetaElement)?.content;
const patches = JSON.stringify(ALL_PATCHES);
// Get client.js's hash
let webVersion = '';
const $link = document.querySelector<HTMLLinkElement>('link[data-chunk="client"][href*="/client."]');
if ($link) {
const match = /\/client\.([^\.]+)\.js/.exec($link.href);
match && (webVersion = match[1]);
} else {
// Get version from <meta>
// Sometimes this value is missing
webVersion = (document.querySelector<HTMLMetaElement>('meta[name=gamepass-app-version]'))?.content ?? '';
}
// Calculate signature
const sig = hashCode(scriptVersion + webVersion + patches)
return sig;
}
static clear() {
clear() {
// Clear cache
window.localStorage.removeItem(PatcherCache.#KEY_CACHE);
PatcherCache.#CACHE = {};
window.localStorage.removeItem(this.KEY_CACHE);
this.CACHE = {};
}
static checkSignature() {
const storedSig = window.localStorage.getItem(PatcherCache.#KEY_SIGNATURE) || 0;
const currentSig = PatcherCache.#getSignature();
private checkSignature() {
const storedSig = window.localStorage.getItem(this.KEY_SIGNATURE) || 0;
const currentSig = this.getSignature();
if (currentSig !== parseInt(storedSig as string)) {
// Save new signature
BxLogger.warning(LOG_TAG, 'Signature changed');
window.localStorage.setItem(PatcherCache.#KEY_SIGNATURE, currentSig.toString());
window.localStorage.setItem(this.KEY_SIGNATURE, currentSig.toString());
PatcherCache.clear();
this.clear();
} else {
BxLogger.info(LOG_TAG, 'Signature unchanged');
}
}
static #cleanupPatches(patches: PatchArray): PatchArray {
private cleanupPatches(patches: PatchArray): PatchArray {
return patches.filter(item => {
for (const id in PatcherCache.#CACHE) {
const cached = PatcherCache.#CACHE[id];
for (const id in this.CACHE) {
const cached = this.CACHE[id];
if (cached.includes(item)) {
return false;
@ -1195,17 +1305,17 @@ export class PatcherCache {
});
}
static getPatches(id: string): PatchArray {
return PatcherCache.#CACHE[id];
getPatches(id: string): PatchArray {
return this.CACHE[id];
}
static saveToCache(subCache: Record<string, PatchArray>) {
saveToCache(subCache: Record<string, PatchArray>) {
for (const id in subCache) {
const patchNames = subCache[id];
let data = PatcherCache.#CACHE[id];
let data = this.CACHE[id];
if (!data) {
PatcherCache.#CACHE[id] = patchNames;
this.CACHE[id] = patchNames;
} else {
for (const patchName of patchNames) {
if (!data.includes(patchName)) {
@ -1216,20 +1326,20 @@ export class PatcherCache {
}
// Save to storage
window.localStorage.setItem(PatcherCache.#KEY_CACHE, JSON.stringify(PatcherCache.#CACHE));
window.localStorage.setItem(this.KEY_CACHE, JSON.stringify(this.CACHE));
}
static init() {
if (PatcherCache.#isInitialized) {
init() {
if (this.isInitialized) {
return;
}
PatcherCache.#isInitialized = true;
this.isInitialized = true;
PatcherCache.checkSignature();
this.checkSignature();
// Read cache from storage
PatcherCache.#CACHE = JSON.parse(window.localStorage.getItem(PatcherCache.#KEY_CACHE) || '{}');
BxLogger.info(LOG_TAG, PatcherCache.#CACHE);
this.CACHE = JSON.parse(window.localStorage.getItem(this.KEY_CACHE) || '{}');
BxLogger.info(LOG_TAG, this.CACHE);
if (window.location.pathname.includes('/play/')) {
PATCH_ORDERS.push(...PLAYING_PATCH_ORDERS);
@ -1238,8 +1348,8 @@ export class PatcherCache {
}
// Remove cached patches from PATCH_ORDERS & PLAYING_PATCH_ORDERS
PATCH_ORDERS = PatcherCache.#cleanupPatches(PATCH_ORDERS);
PLAYING_PATCH_ORDERS = PatcherCache.#cleanupPatches(PLAYING_PATCH_ORDERS);
PATCH_ORDERS = this.cleanupPatches(PATCH_ORDERS);
PLAYING_PATCH_ORDERS = this.cleanupPatches(PLAYING_PATCH_ORDERS);
BxLogger.info(LOG_TAG, PATCH_ORDERS.slice(0));
BxLogger.info(LOG_TAG, PLAYING_PATCH_ORDERS.slice(0));

View File

@ -85,7 +85,7 @@ if (btnHome) {
this.inputSink.onGamepadInput(performance.now() - intervalMs, fakeGamepadMappings);
} else {
intervalMs = 4;
intervalMs = window.BX_CONTROLLER_POLLING_RATE;
}
}

View File

@ -1,121 +1,100 @@
const int FILTER_UNSHARP_MASKING = 1;
const int FILTER_CAS = 2;
#version 300 es
precision highp float;
precision mediump float;
uniform sampler2D data;
uniform vec2 iResolution;
const int FILTER_UNSHARP_MASKING = 1;
// const int FILTER_CAS = 2;
// 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);
uniform int filterId;
uniform float sharpenFactor;
uniform float brightness;
uniform float contrast;
uniform float saturation;
vec3 textureAt(sampler2D tex, vec2 coord) {
return texture2D(tex, coord / iResolution.xy).rgb;
}
out vec4 fragColor;
vec3 clarityBoost(sampler2D tex, vec2 coord, vec3 e) {
vec2 texelSize = 1.0 / iResolution.xy;
vec3 clarityBoost(sampler2D tex, vec2 coord)
{
// Load a collection of samples in a 3x3 neighorhood, where e is the current pixel.
// a b c
// d e f
// g h i
vec3 a = textureAt(tex, coord + vec2(-1, 1));
vec3 b = textureAt(tex, coord + vec2(0, 1));
vec3 c = textureAt(tex, coord + vec2(1, 1));
vec3 a = texture(tex, coord + texelSize * vec2(-1, 1)).rgb;
vec3 b = texture(tex, coord + texelSize * vec2(0, 1)).rgb;
vec3 c = texture(tex, coord + texelSize * vec2(1, 1)).rgb;
vec3 d = textureAt(tex, coord + vec2(-1, 0));
vec3 e = textureAt(tex, coord);
vec3 f = textureAt(tex, coord + vec2(1, 0));
vec3 d = texture(tex, coord + texelSize * vec2(-1, 0)).rgb;
vec3 f = texture(tex, coord + texelSize * vec2(1, 0)).rgb;
vec3 g = textureAt(tex, coord + vec2(-1, -1));
vec3 h = textureAt(tex, coord + vec2(0, -1));
vec3 i = textureAt(tex, coord + vec2(1, -1));
vec3 g = texture(tex, coord + texelSize * vec2(-1, -1)).rgb;
vec3 h = texture(tex, coord + texelSize * vec2(0, -1)).rgb;
vec3 i = texture(tex, coord + texelSize * vec2(1, -1)).rgb;
if (filterId == FILTER_CAS) {
// Soft min and max.
// a b c b
// d e f * 0.5 + d e f * 0.5
// g h i h
// These are 2.0x bigger (factored out the extra multiply).
vec3 minRgb = min(min(min(d, e), min(f, b)), h);
vec3 minRgb2 = min(min(a, c), min(g, i));
minRgb += min(minRgb, minRgb2);
vec3 maxRgb = max(max(max(d, e), max(f, b)), h);
vec3 maxRgb2 = max(max(a, c), max(g, i));
maxRgb += max(maxRgb, maxRgb2);
// Smooth minimum distance to signal limit divided by smooth max.
vec3 reciprocalMaxRgb = 1.0 / maxRgb;
vec3 amplifyRgb = clamp(min(minRgb, 2.0 - maxRgb) * reciprocalMaxRgb, 0.0, 1.0);
// Shaping amount of sharpening.
amplifyRgb = inversesqrt(amplifyRgb);
float contrast = 0.8;
float peak = -3.0 * contrast + 8.0;
vec3 weightRgb = -(1.0 / (amplifyRgb * peak));
vec3 reciprocalWeightRgb = 1.0 / (4.0 * weightRgb + 1.0);
// 0 w 0
// Filter shape: w 1 w
// 0 w 0
vec3 window = (b + d) + (f + h);
vec3 outColor = clamp((window * weightRgb + e) * reciprocalWeightRgb, 0.0, 1.0);
outColor = mix(e, outColor, sharpenFactor / 2.0);
return outColor;
} else if (filterId == FILTER_UNSHARP_MASKING) {
vec3 gaussianBlur = (a * 1.0 + b * 2.0 + c * 1.0 +
d * 2.0 + e * 4.0 + f * 2.0 +
g * 1.0 + h * 2.0 + i * 1.0) / 16.0;
// USM
if (filterId == FILTER_UNSHARP_MASKING) {
vec3 gaussianBlur = (a + c + g + i) * 1.0 + (b + d + f + h) * 2.0 + e * 4.0;
gaussianBlur /= 16.0;
// Return edge detection
return e + (e - gaussianBlur) * sharpenFactor / 3.0;
}
return e;
}
// CAS
// Soft min and max.
// a b c b
// d e f * 0.5 + d e f * 0.5
// g h i h
// These are 2.0x bigger (factored out the extra multiply).
vec3 minRgb = min(min(min(d, e), min(f, b)), h);
minRgb += min(min(a, c), min(g, i));
vec3 adjustBrightness(vec3 color) {
return (1.0 + brightness) * color;
}
vec3 maxRgb = max(max(max(d, e), max(f, b)), h);
maxRgb += max(max(a, c), max(g, i));
vec3 adjustContrast(vec3 color) {
return 0.5 + (1.0 + contrast) * (color - 0.5);
}
// Smooth minimum distance to signal limit divided by smooth max.
vec3 reciprocalMaxRgb = 1.0 / maxRgb;
vec3 amplifyRgb = clamp(min(minRgb, 2.0 - maxRgb) * reciprocalMaxRgb, 0.0, 1.0);
vec3 adjustSaturation(vec3 color) {
const vec3 luminosityFactor = vec3(0.2126, 0.7152, 0.0722);
vec3 grayscale = vec3(dot(color, luminosityFactor));
// Shaping amount of sharpening.
amplifyRgb = inversesqrt(amplifyRgb);
return mix(grayscale, color, 1.0 + saturation);
vec3 weightRgb = -(1.0 / (amplifyRgb * CAS_CONTRAST_PEAK));
vec3 reciprocalWeightRgb = 1.0 / (4.0 * weightRgb + 1.0);
// 0 w 0
// Filter shape: w 1 w
// 0 w 0
vec3 window = b + d + f + h;
vec3 outColor = clamp((window * weightRgb + e) * reciprocalWeightRgb, 0.0, 1.0);
return mix(e, outColor, sharpenFactor / 2.0);
}
void main() {
vec3 color;
vec2 uv = gl_FragCoord.xy / iResolution.xy;
// Get current pixel
vec3 color = texture(data, uv).rgb;
if (sharpenFactor > 0.0) {
color = clarityBoost(data, gl_FragCoord.xy);
} else {
color = textureAt(data, gl_FragCoord.xy);
}
// Clarity boost
color = sharpenFactor > 0.0 ? clarityBoost(data, uv, color) : color;
if (saturation != 0.0) {
color = adjustSaturation(color);
}
// Saturation
color = saturation != 1.0 ? mix(vec3(dot(color, LUMINOSITY_FACTOR)), color, saturation) : color;
if (contrast != 0.0) {
color = adjustContrast(color);
}
// Contrast
color = contrast * (color - 0.5) + 0.5;
if (brightness != 0.0) {
color = adjustBrightness(color);
}
// Brightness
color = brightness * color;
gl_FragColor = vec4(color, 1.0);
fragColor = vec4(color, 1.0);
}

View File

@ -1,5 +1,7 @@
attribute vec2 position;
#version 300 es
in vec4 position;
void main() {
gl_Position = vec4(position, 0, 1);
gl_Position = position;
}

View File

@ -5,19 +5,19 @@ import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
const LOG_TAG = 'WebGL2Player';
export class WebGL2Player {
#$video: HTMLVideoElement;
#$canvas: HTMLCanvasElement;
private readonly LOG_TAG = 'WebGL2Player';
#gl: WebGL2RenderingContext | null = null;
#resources: Array<any> = [];
#program: WebGLProgram | null = null;
private $video: HTMLVideoElement;
private $canvas: HTMLCanvasElement;
#stopped: boolean = false;
private gl: WebGL2RenderingContext | null = null;
private resources: Array<any> = [];
private program: WebGLProgram | null = null;
#options = {
private stopped: boolean = false;
private options = {
filterId: 1,
sharpenFactor: 0,
brightness: 0.0,
@ -25,112 +25,133 @@ export class WebGL2Player {
saturation: 0.0,
};
#animFrameId: number | null = null;
private targetFps = 60;
private frameInterval = 0;
private lastFrameTime = 0;
private animFrameId: number | null = null;
constructor($video: HTMLVideoElement) {
BxLogger.info(LOG_TAG, 'Initialize');
this.#$video = $video;
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.$canvas = $canvas;
this.#setupShaders();
this.#setupRendering();
this.setupShaders();
this.setupRendering();
$video.insertAdjacentElement('afterend', $canvas);
}
setFilter(filterId: number, update = true) {
this.#options.filterId = filterId;
this.options.filterId = filterId;
update && this.updateCanvas();
}
setSharpness(sharpness: number, update = true) {
this.#options.sharpenFactor = sharpness;
this.options.sharpenFactor = sharpness;
update && this.updateCanvas();
}
setBrightness(brightness: number, update = true) {
this.#options.brightness = (brightness - 100) / 100;
this.options.brightness = 1 + (brightness - 100) / 100;
update && this.updateCanvas();
}
setContrast(contrast: number, update = true) {
this.#options.contrast = (contrast - 100) / 100;
this.options.contrast = 1 + (contrast - 100) / 100;
update && this.updateCanvas();
}
setSaturation(saturation: number, update = true) {
this.#options.saturation = (saturation - 100) / 100;
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;
return this.$canvas;
}
updateCanvas() {
const gl = this.#gl!;
const program = this.#program!;
const gl = this.gl!;
const program = this.program!;
gl.uniform2f(gl.getUniformLocation(program, 'iResolution'), this.#$canvas.width, this.#$canvas.height);
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);
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);
}
drawFrame() {
const gl = this.#gl!;
const $video = this.#$video;
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, $video);
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);
}
#setupRendering() {
let animate: any;
private setupRendering() {
let frameCallback: any;
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
const $video = this.#$video;
animate = () => {
if (this.#stopped) {
return;
}
this.drawFrame();
this.#animFrameId = $video.requestVideoFrameCallback(animate);
}
this.#animFrameId = $video.requestVideoFrameCallback(animate);
const $video = this.$video;
frameCallback = $video.requestVideoFrameCallback.bind($video);
} else {
animate = () => {
if (this.#stopped) {
return;
}
frameCallback = requestAnimationFrame;
}
this.drawFrame();
this.#animFrameId = requestAnimationFrame(animate);
let animate = () => {
if (this.stopped) {
return;
}
this.#animFrameId = requestAnimationFrame(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);
}
this.animFrameId = frameCallback(animate);
}
#setupShaders() {
BxLogger.info(LOG_TAG, 'Setting up', getPref(PrefKey.VIDEO_POWER_PREFERENCE));
private setupShaders() {
BxLogger.info(this.LOG_TAG, 'Setting up', getPref(PrefKey.VIDEO_POWER_PREFERENCE));
const gl = this.#$canvas.getContext('webgl', {
const gl = this.$canvas.getContext('webgl2', {
isBx: true,
antialias: true,
alpha: false,
powerPreference: getPref(PrefKey.VIDEO_POWER_PREFERENCE),
}) as WebGL2RenderingContext;
this.#gl = gl;
this.gl = gl;
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferWidth);
@ -145,7 +166,7 @@ export class WebGL2Player {
// Create and link program
const program = gl.createProgram()!;
this.#program = program;
this.program = program;
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
@ -162,24 +183,17 @@ export class WebGL2Player {
// Vertices: A screen-filling quad made from two triangles
const buffer = gl.createBuffer();
this.#resources.push(buffer);
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.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);
this.resources.push(texture);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
@ -197,40 +211,40 @@ export class WebGL2Player {
resume() {
this.stop();
this.#stopped = false;
BxLogger.info(LOG_TAG, 'Resume');
this.stopped = false;
BxLogger.info(this.LOG_TAG, 'Resume');
this.#$canvas.classList.remove('bx-gone');
this.#setupRendering();
this.$canvas.classList.remove('bx-gone');
this.setupRendering();
}
stop() {
BxLogger.info(LOG_TAG, 'Stop');
this.#$canvas.classList.add('bx-gone');
BxLogger.info(this.LOG_TAG, 'Stop');
this.$canvas.classList.add('bx-gone');
this.#stopped = true;
if (this.#animFrameId) {
this.stopped = true;
if (this.animFrameId) {
if ('requestVideoFrameCallback' in HTMLVideoElement.prototype) {
this.#$video.cancelVideoFrameCallback(this.#animFrameId);
this.$video.cancelVideoFrameCallback(this.animFrameId);
} else {
cancelAnimationFrame(this.#animFrameId);
cancelAnimationFrame(this.animFrameId);
}
this.#animFrameId = null;
this.animFrameId = null;
}
}
destroy() {
BxLogger.info(LOG_TAG, 'Destroy');
BxLogger.info(this.LOG_TAG, 'Destroy');
this.stop();
const gl = this.#gl;
const gl = this.gl;
if (gl) {
gl.getExtension('WEBGL_lose_context')?.loseContext();
gl.useProgram(null);
for (const resource of this.#resources) {
for (const resource of this.resources) {
if (resource instanceof WebGLProgram) {
gl.useProgram(null);
gl.deleteProgram(resource);
} else if (resource instanceof WebGLShader) {
gl.deleteShader(resource);
@ -241,14 +255,14 @@ export class WebGL2Player {
}
}
this.#gl = null;
this.gl = null;
}
if (this.#$canvas.isConnected) {
this.#$canvas.parentElement?.removeChild(this.#$canvas);
if (this.$canvas.isConnected) {
this.$canvas.parentElement?.removeChild(this.$canvas);
}
this.#$canvas.width = 1;
this.#$canvas.height = 1;
this.$canvas.width = 1;
this.$canvas.height = 1;
}
}

View File

@ -0,0 +1,229 @@
import { STATES, AppInterface } from "@utils/global";
import { Toast } from "@utils/toast";
import { BxEvent } from "@utils/bx-event";
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 { RemotePlayNavigationDialog } from "./ui/dialog/remote-play-dialog";
export const enum RemotePlayConsoleState {
ON = 'On',
OFF = 'Off',
STANDBY = 'ConnectedStandby',
UNKNOWN = 'Unknown',
}
type RemotePlayRegion = {
name: string;
baseUri: string;
isDefault: boolean;
};
type RemotePlayConsole = {
deviceName: string;
serverId: string;
powerState: RemotePlayConsoleState;
consoleType: string;
// playPath: string;
// outOfHomeWarning: string;
// wirelessWarning: string;
// isDevKit: string;
};
export class RemotePlayManager {
private static instance: RemotePlayManager;
public static getInstance = () => RemotePlayManager.instance ?? (RemotePlayManager.instance = new RemotePlayManager());
private readonly LOG_TAG = 'RemotePlayManager';
private isInitialized = false;
private XCLOUD_TOKEN!: string;
private XHOME_TOKEN!: string;
private consoles!: Array<RemotePlayConsole>;
private regions: Array<RemotePlayRegion> = [];
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
}
initialize() {
if (this.isInitialized) {
return;
}
this.isInitialized = true;
this.getXhomeToken(() => {
this.getConsolesList(() => {
BxLogger.info(this.LOG_TAG, 'Consoles', this.consoles);
STATES.supportedRegion && HeaderSection.getInstance().showRemotePlayButton();
BxEvent.dispatch(window, BxEvent.REMOTE_PLAY_READY);
});
});
}
get xcloudToken() {
return this.XCLOUD_TOKEN;
}
set xcloudToken(token: string) {
this.XCLOUD_TOKEN = token;
}
get xhomeToken() {
return this.XHOME_TOKEN;
}
getConsoles() {
return this.consoles;
}
private getXhomeToken(callback: any) {
if (this.XHOME_TOKEN) {
callback();
return;
}
let GSSV_TOKEN;
try {
GSSV_TOKEN = JSON.parse(localStorage.getItem('xboxcom_xbl_user_info')!).tokens['http://gssv.xboxlive.com/'].token;
} catch (e) {
for (let i = 0; i < localStorage.length; i++){
const key = localStorage.key(i)!;
if (!key.startsWith('Auth.User.')) {
continue;
}
const json = JSON.parse(localStorage.getItem(key)!);
for (const token of json.tokens) {
if (!token.relyingParty.includes('gssv.xboxlive.com')) {
continue;
}
GSSV_TOKEN = token.tokenData.token;
break;
}
break;
}
}
const request = new Request('https://xhome.gssv-play-prod.xboxlive.com/v2/login/user', {
method: 'POST',
body: JSON.stringify({
offeringId: 'xhome',
token: GSSV_TOKEN,
}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
fetch(request).then(resp => resp.json())
.then(json => {
this.regions = json.offeringSettings.regions;
this.XHOME_TOKEN = json.gsToken;
callback();
});
}
private async getConsolesList(callback: any) {
if (this.consoles) {
callback();
return;
}
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.XHOME_TOKEN}`,
},
};
// Test servers one by one
for (const region of this.regions) {
try {
const request = new Request(`${region.baseUri}/v6/servers/home?mr=50`, options);
const resp = await fetch(request);
const json = await resp.json();
if (json.results.length === 0) {
continue;
}
this.consoles = json.results;
// Store working server
STATES.remotePlay.server = region.baseUri;
break;
} catch (e) {}
}
// None of the servers worked
if (!STATES.remotePlay.server) {
this.consoles = [];
}
callback();
}
play(serverId: string, resolution?: string) {
if (resolution) {
setPref(PrefKey.REMOTE_PLAY_RESOLUTION, resolution);
}
STATES.remotePlay.config = {
serverId: serverId,
};
window.BX_REMOTE_PLAY_CONFIG = STATES.remotePlay.config;
localRedirect('/launch/fortnite/BT5P2X999VH2#remote-play');
}
togglePopup(force = null) {
if (!this.isReady()) {
Toast.show(t('getting-consoles-list'));
return;
}
if (this.consoles.length === 0) {
Toast.show(t('no-consoles-found'), '', {instant: true});
return;
}
// Show native dialog in Android app
if (AppInterface && AppInterface.showRemotePlayDialog) {
AppInterface.showRemotePlayDialog(JSON.stringify(this.consoles));
(document.activeElement as HTMLElement).blur();
return;
}
RemotePlayNavigationDialog.getInstance().show();
}
static detect() {
if (!getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
return;
}
STATES.remotePlay.isPlaying = window.location.pathname.includes('/launch/') && window.location.hash.startsWith('#remote-play');
if (STATES.remotePlay?.isPlaying) {
window.BX_REMOTE_PLAY_CONFIG = STATES.remotePlay.config;
// Remove /launch/... from URL
window.history.replaceState({origin: 'better-xcloud'}, '', 'https://www.xbox.com/' + location.pathname.substring(1, 6) + '/play');
} else {
window.BX_REMOTE_PLAY_CONFIG = null;
}
}
isReady() {
return this.consoles !== null;
}
}

View File

@ -1,364 +0,0 @@
import { STATES, AppInterface } from "@utils/global";
import { CE, createButton, ButtonStyle } from "@utils/html";
import { BxIcon } from "@utils/bx-icon";
import { Toast } from "@utils/toast";
import { BxEvent } from "@utils/bx-event";
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";
const LOG_TAG = 'RemotePlay';
const enum RemotePlayConsoleState {
ON = 'On',
OFF = 'Off',
STANDBY = 'ConnectedStandby',
UNKNOWN = 'Unknown',
}
type RemotePlayRegion = {
name: string;
baseUri: string;
isDefault: boolean;
};
type RemotePlayConsole = {
deviceName: string;
serverId: string;
powerState: RemotePlayConsoleState;
consoleType: string;
// playPath: string;
// outOfHomeWarning: string;
// wirelessWarning: string;
// isDevKit: string;
};
export class RemotePlay {
static XCLOUD_TOKEN: string;
static XHOME_TOKEN: string;
static #CONSOLES: Array<RemotePlayConsole>;
static #REGIONS: Array<RemotePlayRegion>;
static readonly #STATE_LABELS: {[key in RemotePlayConsoleState]: string} = {
[RemotePlayConsoleState.ON]: t('powered-on'),
[RemotePlayConsoleState.OFF]: t('powered-off'),
[RemotePlayConsoleState.STANDBY]: t('standby'),
[RemotePlayConsoleState.UNKNOWN]: t('unknown'),
};
static readonly BASE_DEVICE_INFO = {
appInfo: {
env: {
clientAppId: window.location.host,
clientAppType: 'browser',
clientAppVersion: '24.17.36',
clientSdkVersion: '10.1.14',
httpEnvironment: 'prod',
sdkInstallId: '',
},
},
dev: {
displayInfo: {
dimensions: {
widthInPixels: 1920,
heightInPixels: 1080,
},
pixelDensity: {
dpiX: 1,
dpiY: 1,
},
},
hw: {
make: 'Microsoft',
model: 'unknown',
sdktype: 'web',
},
os: {
name: 'windows',
ver: '22631.2715',
platform: 'desktop',
},
browser: {
browserName: 'chrome',
browserVersion: '125.0',
},
},
};
static #$content: HTMLElement;
static #initialize() {
if (RemotePlay.#$content) {
return;
}
RemotePlay.#$content = CE('div', {}, t('getting-consoles-list'));
RemotePlay.#getXhomeToken(() => {
RemotePlay.#getConsolesList(() => {
BxLogger.info(LOG_TAG, 'Consoles', RemotePlay.#CONSOLES);
if (RemotePlay.#CONSOLES && RemotePlay.#CONSOLES.length > 0) {
STATES.supportedRegion && HeaderSection.showRemotePlayButton();
}
RemotePlay.#renderConsoles();
BxEvent.dispatch(window, BxEvent.REMOTE_PLAY_READY);
});
});
}
static #renderConsoles() {
const $fragment = CE('div', {'class': 'bx-remote-play-container'});
if (!RemotePlay.#CONSOLES || RemotePlay.#CONSOLES.length === 0) {
$fragment.appendChild(CE('span', {}, t('no-consoles-found')));
RemotePlay.#$content = CE('div', {}, $fragment);
return;
}
const $settingNote = CE('p', {});
const resolutions = [1080, 720];
const currentResolution = getPref(PrefKey.REMOTE_PLAY_RESOLUTION);
const $resolutionGroup = CE('div', {});
for (const resolution of resolutions) {
const value = `${resolution}p`;
const id = `bx_radio_xhome_resolution_${resolution}`;
const $radio = CE<HTMLInputElement>('input', {
'type': 'radio',
'value': value,
'id': id,
'name': 'bx_radio_xhome_resolution',
}, value);
$radio.addEventListener('change', e => {
const value = (e.target as HTMLInputElement).value;
$settingNote.textContent = value === '1080p' ? '✅ ' + t('can-stream-xbox-360-games') : '❌ ' + t('cant-stream-xbox-360-games');
setPref(PrefKey.REMOTE_PLAY_RESOLUTION, value);
});
const $label = CE('label', {
'for': id,
'class': 'bx-remote-play-resolution',
}, $radio, `${resolution}p`);
$resolutionGroup.appendChild($label);
if (currentResolution === value) {
$radio.checked = true;
$radio.dispatchEvent(new Event('change'));
}
}
const $qualitySettings = CE('div', {'class': 'bx-remote-play-settings'},
CE('div', {},
CE('label', {}, t('target-resolution'), $settingNote),
$resolutionGroup,
)
);
$fragment.appendChild($qualitySettings);
// Render concoles list
for (let con of RemotePlay.#CONSOLES) {
const $child = CE('div', {'class': 'bx-remote-play-device-wrapper'},
CE('div', {'class': 'bx-remote-play-device-info'},
CE('div', {},
CE('span', {'class': 'bx-remote-play-device-name'}, con.deviceName),
CE('span', {'class': 'bx-remote-play-console-type'}, con.consoleType.replace('Xbox', ''))
),
CE('div', {'class': 'bx-remote-play-power-state'}, RemotePlay.#STATE_LABELS[con.powerState]),
),
// Connect button
createButton({
classes: ['bx-remote-play-connect-button'],
label: t('console-connect'),
style: ButtonStyle.PRIMARY | ButtonStyle.FOCUSABLE,
onClick: e => {
RemotePlay.play(con.serverId);
},
}),
);
$fragment.appendChild($child);
}
// Add Help button
$fragment.appendChild(createButton({
icon: BxIcon.QUESTION,
style: ButtonStyle.GHOST | ButtonStyle.FOCUSABLE,
url: 'https://better-xcloud.github.io/remote-play',
label: t('help'),
}));
RemotePlay.#$content = CE('div', {}, $fragment);
}
static #getXhomeToken(callback: any) {
if (RemotePlay.XHOME_TOKEN) {
callback();
return;
}
let GSSV_TOKEN;
try {
GSSV_TOKEN = JSON.parse(localStorage.getItem('xboxcom_xbl_user_info')!).tokens['http://gssv.xboxlive.com/'].token;
} catch (e) {
for (let i = 0; i < localStorage.length; i++){
const key = localStorage.key(i)!;
if (!key.startsWith('Auth.User.')) {
continue;
}
const json = JSON.parse(localStorage.getItem(key)!);
for (const token of json.tokens) {
if (!token.relyingParty.includes('gssv.xboxlive.com')) {
continue;
}
GSSV_TOKEN = token.tokenData.token;
break;
}
break;
}
}
const request = new Request('https://xhome.gssv-play-prod.xboxlive.com/v2/login/user', {
method: 'POST',
body: JSON.stringify({
offeringId: 'xhome',
token: GSSV_TOKEN,
}),
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
fetch(request).then(resp => resp.json())
.then(json => {
RemotePlay.#REGIONS = json.offeringSettings.regions;
RemotePlay.XHOME_TOKEN = json.gsToken;
callback();
});
}
static async #getConsolesList(callback: any) {
if (RemotePlay.#CONSOLES) {
callback();
return;
}
const options = {
method: 'GET',
headers: {
'Authorization': `Bearer ${RemotePlay.XHOME_TOKEN}`,
},
};
// Test servers one by one
for (const region of RemotePlay.#REGIONS) {
try {
const request = new Request(`${region.baseUri}/v6/servers/home?mr=50`, options);
const resp = await fetch(request);
const json = await resp.json();
RemotePlay.#CONSOLES = json.results;
// Store working server
STATES.remotePlay.server = region.baseUri;
callback();
} catch (e) {}
if (RemotePlay.#CONSOLES) {
break;
}
}
// None of the servers worked
if (!STATES.remotePlay.server) {
RemotePlay.#CONSOLES = [];
}
}
static play(serverId: string, resolution?: string) {
if (resolution) {
setPref(PrefKey.REMOTE_PLAY_RESOLUTION, resolution);
}
STATES.remotePlay.config = {
serverId: serverId,
};
window.BX_REMOTE_PLAY_CONFIG = STATES.remotePlay.config;
localRedirect('/launch/fortnite/BT5P2X999VH2#remote-play');
RemotePlay.detachPopup();
}
static preload() {
RemotePlay.#initialize();
}
static detachPopup() {
// Detach popup from body
const $popup = document.querySelector('.bx-remote-play-popup');
$popup && $popup.remove();
}
static togglePopup(force = null) {
if (!getPref(PrefKey.REMOTE_PLAY_ENABLED) || !RemotePlay.isReady()) {
Toast.show(t('getting-consoles-list'));
return;
}
RemotePlay.#initialize();
if (AppInterface && AppInterface.showRemotePlayDialog) {
AppInterface.showRemotePlayDialog(JSON.stringify(RemotePlay.#CONSOLES));
(document.activeElement as HTMLElement).blur();
return;
}
if (document.querySelector('.bx-remote-play-popup')) {
if (force === false) {
RemotePlay.#$content.classList.add('bx-gone');
} else {
RemotePlay.#$content.classList.toggle('bx-gone');
}
return;
}
const $header = document.querySelector('#gamepass-root header')!;
const group = $header.firstElementChild!.getAttribute('data-group')!;
RemotePlay.#$content.setAttribute('data-group', group);
RemotePlay.#$content.classList.add('bx-remote-play-popup');
RemotePlay.#$content.classList.remove('bx-gone');
$header.insertAdjacentElement('afterend', RemotePlay.#$content);
}
static detect() {
if (!getPref(PrefKey.REMOTE_PLAY_ENABLED)) {
return;
}
STATES.remotePlay.isPlaying = window.location.pathname.includes('/launch/') && window.location.hash.startsWith('#remote-play');
if (STATES.remotePlay?.isPlaying) {
window.BX_REMOTE_PLAY_CONFIG = STATES.remotePlay.config;
// Remove /launch/... from URL
window.history.replaceState({origin: 'better-xcloud'}, '', 'https://www.xbox.com/' + location.pathname.substring(1, 6) + '/play');
} else {
window.BX_REMOTE_PLAY_CONFIG = null;
}
}
static isReady() {
return RemotePlay.#CONSOLES !== null && RemotePlay.#CONSOLES.length > 0;
}
}

View File

@ -0,0 +1,18 @@
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { limitVideoPlayerFps } from "../stream/stream-settings-utils";
export class RendererShortcut {
static toggleVisibility(): boolean {
const $mediaContainer = document.querySelector('#game-stream div[data-testid="media-container"]');
if (!$mediaContainer) {
return true;
}
$mediaContainer.classList.toggle('bx-gone');
const isShowing = !$mediaContainer.classList.contains('bx-gone');
// Switch FPS
limitVideoPlayerFps(isShowing ? getPref(PrefKey.VIDEO_MAX_FPS) : 0);
return isShowing;
}
}

View File

@ -4,6 +4,12 @@ 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";
export enum SpeakerState {
ENABLED,
MUTED,
}
export class SoundShortcut {
static adjustGainNodeVolume(amount: number): number {
@ -64,21 +70,23 @@ 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,
})
return;
}
let $media: HTMLMediaElement;
$media = document.querySelector('div[data-testid=media-container] audio') as HTMLAudioElement;
if (!$media) {
$media = document.querySelector('div[data-testid=media-container] video') as HTMLAudioElement;
}
const $media = document.querySelector<HTMLAudioElement>('div[data-testid=media-container] audio') ?? document.querySelector<HTMLAudioElement>('div[data-testid=media-container] video');
if ($media) {
$media.muted = !$media.muted;
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,
})
}
}
}

View File

@ -1,10 +1,13 @@
import { isFullVersion } from "@macros/build" with {type: "macro"};
import { CE } from "@/utils/html";
import { WebGL2Player } from "./player/webgl2-player";
import { Screenshot } from "@/utils/screenshot";
import { ScreenshotManager } from "@/utils/screenshot-manager";
import { StreamPlayerType, StreamVideoProcessing } from "@enums/stream-player";
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";
export type StreamPlayerOptions = Partial<{
processing: string,
@ -15,35 +18,35 @@ export type StreamPlayerOptions = Partial<{
}>;
export class StreamPlayer {
#$video: HTMLVideoElement;
#playerType: StreamPlayerType = StreamPlayerType.VIDEO;
private $video: HTMLVideoElement;
private playerType: StreamPlayerType = StreamPlayerType.VIDEO;
#options: StreamPlayerOptions = {};
private options: StreamPlayerOptions = {};
#webGL2Player: WebGL2Player | null = null;
private webGL2Player: WebGL2Player | null = null;
#$videoCss: HTMLStyleElement | null = null;
#$usmMatrix: SVGFEConvolveMatrixElement | null = null;
private $videoCss: HTMLStyleElement | null = null;
private $usmMatrix: SVGFEConvolveMatrixElement | null = null;
constructor($video: HTMLVideoElement, type: StreamPlayerType, options: StreamPlayerOptions) {
this.#setupVideoElements();
this.setupVideoElements();
this.#$video = $video;
this.#options = options || {};
this.$video = $video;
this.options = options || {};
this.setPlayerType(type);
}
#setupVideoElements() {
this.#$videoCss = document.getElementById('bx-video-css') as HTMLStyleElement;
if (this.#$videoCss) {
this.#$usmMatrix = this.#$videoCss.querySelector('#bx-filter-usm-matrix') as any;
private setupVideoElements() {
this.$videoCss = document.getElementById('bx-video-css') as HTMLStyleElement;
if (this.$videoCss) {
this.$usmMatrix = this.$videoCss.querySelector('#bx-filter-usm-matrix') as any;
return;
}
const $fragment = document.createDocumentFragment();
this.#$videoCss = CE<HTMLStyleElement>('style', {id: 'bx-video-css'});
$fragment.appendChild(this.#$videoCss);
this.$videoCss = CE<HTMLStyleElement>('style', {id: 'bx-video-css'});
$fragment.appendChild(this.$videoCss);
// Setup SVG filters
const $svg = CE('svg', {
@ -54,7 +57,7 @@ export class StreamPlayer {
CE('filter', {
id: 'bx-filter-usm',
xmlns: 'http://www.w3.org/2000/svg',
}, this.#$usmMatrix = CE('feConvolveMatrix', {
}, this.$usmMatrix = CE('feConvolveMatrix', {
id: 'bx-filter-usm-matrix',
order: '3',
xmlns: 'http://www.w3.org/2000/svg',
@ -65,29 +68,29 @@ export class StreamPlayer {
document.documentElement.appendChild($fragment);
}
#getVideoPlayerFilterStyle() {
private getVideoPlayerFilterStyle() {
const filters = [];
const sharpness = this.#options.sharpness || 0;
if (this.#options.processing === StreamVideoProcessing.USM && sharpness != 0) {
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);
this.$usmMatrix?.setAttributeNS(null, 'kernelMatrix', matrix);
filters.push(`url(#bx-filter-usm)`);
}
const saturation = this.#options.saturation || 100;
const saturation = this.options.saturation || 100;
if (saturation != 100) {
filters.push(`saturate(${saturation}%)`);
}
const contrast = this.#options.contrast || 100;
const contrast = this.options.contrast || 100;
if (contrast != 100) {
filters.push(`contrast(${contrast}%)`);
}
const brightness = this.#options.brightness || 100;
const brightness = this.options.brightness || 100;
if (brightness != 100) {
filters.push(`brightness(${brightness}%)`);
}
@ -95,14 +98,14 @@ export class StreamPlayer {
return filters.join(' ');
}
#resizePlayer() {
private resizePlayer() {
const PREF_RATIO = getPref(PrefKey.VIDEO_RATIO);
const $video = this.#$video;
const $video = this.$video;
const isNativeTouchGame = STATES.currentStream.titleInfo?.details.hasNativeTouchSupport;
let $webGL2Canvas;
if (this.#playerType == StreamPlayerType.WEBGL2) {
$webGL2Canvas = this.#webGL2Player?.getCanvas()!;
if (this.playerType == StreamPlayerType.WEBGL2) {
$webGL2Canvas = this.webGL2Player?.getCanvas()!;
}
let targetWidth;
@ -164,67 +167,69 @@ export class StreamPlayer {
}
// Update video dimensions
if (isNativeTouchGame && this.#playerType == StreamPlayerType.WEBGL2) {
if (isNativeTouchGame && this.playerType == StreamPlayerType.WEBGL2) {
window.BX_EXPOSED.streamSession.updateDimensions();
}
}
setPlayerType(type: StreamPlayerType, refreshPlayer: boolean = false) {
if (this.#playerType !== type) {
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);
if (!this.webGL2Player) {
this.webGL2Player = new WebGL2Player(this.$video);
} else {
this.#webGL2Player.resume();
this.webGL2Player.resume();
}
this.#$videoCss!.textContent = '';
this.$videoCss!.textContent = '';
this.#$video.classList.add('bx-pixel');
this.$video.classList.add(videoClass);
} else {
// Cleanup WebGL2 Player
this.#webGL2Player?.stop();
this.webGL2Player?.stop();
this.#$video.classList.remove('bx-pixel');
this.$video.classList.remove(videoClass);
}
}
this.#playerType = type;
this.playerType = type;
refreshPlayer && this.refreshPlayer();
}
setOptions(options: StreamPlayerOptions, refreshPlayer: boolean = false) {
this.#options = options;
this.options = options;
refreshPlayer && this.refreshPlayer();
}
updateOptions(options: StreamPlayerOptions, refreshPlayer: boolean = false) {
this.#options = Object.assign(this.#options, options);
this.options = Object.assign(this.options, options);
refreshPlayer && this.refreshPlayer();
}
getPlayerElement(playerType?: StreamPlayerType) {
if (typeof playerType === 'undefined') {
playerType = this.#playerType;
playerType = this.playerType;
}
if (playerType === StreamPlayerType.WEBGL2) {
return this.#webGL2Player?.getCanvas();
return this.webGL2Player?.getCanvas();
}
return this.#$video;
return this.$video;
}
getWebGL2Player() {
return this.#webGL2Player;
return this.webGL2Player;
}
refreshPlayer() {
if (this.#playerType === StreamPlayerType.WEBGL2) {
const options = this.#options;
const webGL2Player = this.#webGL2Player!;
if (this.playerType === StreamPlayerType.WEBGL2) {
const options = this.options;
const webGL2Player = this.webGL2Player!;
if (options.processing === StreamVideoProcessing.USM) {
webGL2Player.setFilter(1);
@ -232,22 +237,22 @@ export class StreamPlayer {
webGL2Player.setFilter(2);
}
Screenshot.updateCanvasFilters('none');
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 filters = this.getVideoPlayerFilterStyle();
let videoCss = '';
if (filters) {
videoCss += `filter: ${filters} !important;`;
}
// Apply video filters to screenshots
if (getPref(PrefKey.SCREENSHOT_APPLY_FILTERS)) {
Screenshot.updateCanvasFilters(filters);
if (isFullVersion() && getPref(PrefKey.SCREENSHOT_APPLY_FILTERS)) {
ScreenshotManager.getInstance().updateCanvasFilters(filters);
}
let css = '';
@ -255,26 +260,26 @@ export class StreamPlayer {
css = `#game-stream video { ${videoCss} }`;
}
this.#$videoCss!.textContent = css;
this.$videoCss!.textContent = css;
}
this.#resizePlayer();
this.resizePlayer();
}
reloadPlayer() {
this.#cleanUpWebGL2Player();
this.cleanUpWebGL2Player();
this.#playerType = StreamPlayerType.VIDEO;
this.playerType = StreamPlayerType.VIDEO;
this.setPlayerType(StreamPlayerType.WEBGL2, false);
}
#cleanUpWebGL2Player() {
private cleanUpWebGL2Player() {
// Clean up WebGL2 Player
this.#webGL2Player?.destroy();
this.#webGL2Player = null;
this.webGL2Player?.destroy();
this.webGL2Player = null;
}
destroy() {
this.#cleanUpWebGL2Player();
this.cleanUpWebGL2Player();
}
}

View File

@ -1,126 +1,154 @@
import { isLiteVersion } from "@macros/build" with {type: "macro"};
import { t } from "@utils/translation";
import { BxEvent } from "@utils/bx-event";
import { CE, createSvgIcon } from "@utils/html";
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 { GuideMenuTab } from "../ui/guide-menu";
import { StreamStat, StreamStatsCollector } from "@/utils/stream-stats-collector";
type StreamBadgeInfo = {
name: string,
$element?: HTMLElement,
icon: typeof BxIcon,
color: string,
};
type StreamServerInfo = {
server?: {
region?: string,
},
video?: {
width: number,
height: number,
codec: string,
profile?: string,
},
audio?: {
codec: string,
bitrate: number,
},
};
enum StreamBadge {
PLAYTIME = 'playtime',
BATTERY = 'battery',
DOWNLOAD = 'in',
UPLOAD = 'out',
DOWNLOAD = 'download',
UPLOAD = 'upload',
SERVER = 'server',
VIDEO = 'video',
AUDIO = 'audio',
}
const StreamBadgeIcon: Partial<{[key in StreamBadge]: any}> = {
[StreamBadge.PLAYTIME]: BxIcon.PLAYTIME,
[StreamBadge.VIDEO]: BxIcon.DISPLAY,
[StreamBadge.BATTERY]: BxIcon.BATTERY,
[StreamBadge.DOWNLOAD]: BxIcon.DOWNLOAD,
[StreamBadge.UPLOAD]: BxIcon.UPLOAD,
[StreamBadge.SERVER]: BxIcon.SERVER,
[StreamBadge.AUDIO]: BxIcon.AUDIO,
}
export class StreamBadges {
private static instance: StreamBadges;
public static getInstance(): StreamBadges {
if (!StreamBadges.instance) {
StreamBadges.instance = new StreamBadges();
}
public static getInstance = () => StreamBadges.instance ?? (StreamBadges.instance = new StreamBadges());
private readonly LOG_TAG = 'StreamBadges';
return StreamBadges.instance;
private serverInfo: StreamServerInfo = {};
private badges: Record<StreamBadge, StreamBadgeInfo> = {
[StreamBadge.PLAYTIME]: {
name: t('playtime'),
icon: BxIcon.PLAYTIME,
color: '#ff004d',
},
[StreamBadge.BATTERY]: {
name: t('battery'),
icon: BxIcon.BATTERY,
color: '#00b543',
},
[StreamBadge.DOWNLOAD]: {
name: t('download'),
icon: BxIcon.DOWNLOAD,
color: '#29adff',
},
[StreamBadge.UPLOAD]: {
name: t('upload'),
icon: BxIcon.UPLOAD,
color: '#ff77a8',
},
[StreamBadge.SERVER]: {
name: t('server'),
icon: BxIcon.SERVER,
color: '#ff6c24',
},
[StreamBadge.VIDEO]: {
name: t('video'),
icon: BxIcon.DISPLAY,
color: '#742f29',
},
[StreamBadge.AUDIO]: {
name: t('audio'),
icon: BxIcon.AUDIO,
color: '#5f574f',
},
};
private $container: HTMLElement | undefined;
private intervalId?: number | null;
private readonly REFRESH_INTERVAL = 3 * 1000;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
}
#ipv6 = false;
#resolution?: {width: number, height: number} | null = null;
#video?: {codec: string, profile?: string | null} | null = null;
#audio?: {codec: string, bitrate: number} | null = null;
#region = '';
startBatteryLevel = 100;
startTimestamp = 0;
#$container: HTMLElement | undefined;
#cachedDoms: Partial<{[key in StreamBadge]: HTMLElement}> = {};
#interval?: number | null;
readonly #REFRESH_INTERVAL = 3000;
setRegion(region: string) {
this.#region = region;
this.serverInfo.server = {
region: region,
};
}
#renderBadge(name: StreamBadge, value: string, color: string) {
renderBadge(name: StreamBadge, value: string) {
const badgeInfo = this.badges[name];
let $badge;
if (this.#cachedDoms[name]) {
$badge = this.#cachedDoms[name]!;
if (badgeInfo.$element) {
$badge = badgeInfo.$element;
$badge.lastElementChild!.textContent = value;
return $badge;
}
$badge = CE('div', {'class': 'bx-badge', 'title': t(`badge-${name}`)},
CE('span', {'class': 'bx-badge-name'}, createSvgIcon(StreamBadgeIcon[name])),
CE('span', {'class': 'bx-badge-value', 'style': `background-color: ${color}`}, value),
$badge = CE('div', {class: 'bx-badge', title: badgeInfo.name},
CE('span', {class: 'bx-badge-name'}, createSvgIcon(badgeInfo.icon)),
CE('span', {class: 'bx-badge-value', style: `background-color: ${badgeInfo.color}`}, value),
);
if (name === StreamBadge.BATTERY) {
$badge.classList.add('bx-badge-battery');
}
this.#cachedDoms[name] = $badge;
this.badges[name].$element = $badge;
return $badge;
}
async #updateBadges(forceUpdate = false) {
if (!this.#$container || (!forceUpdate && !this.#$container.isConnected)) {
this.#stop();
private async updateBadges(forceUpdate = false) {
if (!this.$container || (!forceUpdate && !this.$container.isConnected)) {
this.stop();
return;
}
// Playtime
let now = +new Date;
const diffSeconds = Math.ceil((now - this.startTimestamp) / 1000);
const playtime = this.#secondsToHm(diffSeconds);
const statsCollector = StreamStatsCollector.getInstance();
await statsCollector.collect();
// Battery
let batteryLevel = '100%';
let batteryLevelInt = 100;
let isCharging = false;
if (STATES.browser.capabilities.batteryApi) {
try {
const bm = await (navigator as NavigatorBattery).getBattery();
isCharging = bm.charging;
batteryLevelInt = Math.round(bm.level * 100);
batteryLevel = `${batteryLevelInt}%`;
if (batteryLevelInt != this.startBatteryLevel) {
const diffLevel = Math.round(batteryLevelInt - this.startBatteryLevel);
const sign = diffLevel > 0 ? '+' : '';
batteryLevel += ` (${sign}${diffLevel}%)`;
}
} catch(e) {}
}
const stats = await STATES.currentStream.peerConnection?.getStats()!;
let totalIn = 0;
let totalOut = 0;
stats.forEach(stat => {
if (stat.type === 'candidate-pair' && stat.packetsReceived > 0 && stat.state === 'succeeded') {
totalIn += stat.bytesReceived;
totalOut += stat.bytesSent;
}
});
const play = statsCollector.getStat(StreamStat.PLAYTIME);
const batt = statsCollector.getStat(StreamStat.BATTERY);
const dl = statsCollector.getStat(StreamStat.DOWNLOAD);
const ul = statsCollector.getStat(StreamStat.UPLOAD);
const badges = {
[StreamBadge.DOWNLOAD]: totalIn ? this.#humanFileSize(totalIn) : null,
[StreamBadge.UPLOAD]: totalOut ? this.#humanFileSize(totalOut) : null,
[StreamBadge.PLAYTIME]: playtime,
[StreamBadge.BATTERY]: batteryLevel,
[StreamBadge.DOWNLOAD]: dl.toString(),
[StreamBadge.UPLOAD]: ul.toString(),
[StreamBadge.PLAYTIME]: play.toString(),
[StreamBadge.BATTERY]: batt.toString(),
};
let name: keyof typeof badges;
@ -130,97 +158,49 @@ export class StreamBadges {
continue;
}
const $elm = this.#cachedDoms[name]!;
$elm && ($elm.lastElementChild!.textContent = value);
const $elm = this.badges[name].$element;
if (!$elm) {
continue;
}
$elm.lastElementChild!.textContent = value;
if (name === StreamBadge.BATTERY) {
if (this.startBatteryLevel === 100 && batteryLevelInt === 100) {
if (batt.current === 100 && batt.start === 100) {
// Hide battery badge when the battery is 100%
$elm.classList.add('bx-gone');
} else {
// Show charging status
$elm.dataset.charging = isCharging.toString()
$elm.dataset.charging = batt.isCharging.toString();
$elm.classList.remove('bx-gone');
}
}
}
}
async #start() {
await this.#updateBadges(true);
this.#stop();
this.#interval = window.setInterval(this.#updateBadges.bind(this), this.#REFRESH_INTERVAL);
private async start() {
await this.updateBadges(true);
this.stop();
this.intervalId = window.setInterval(this.updateBadges.bind(this), this.REFRESH_INTERVAL);
}
#stop() {
this.#interval && clearInterval(this.#interval);
this.#interval = null;
private stop() {
this.intervalId && clearInterval(this.intervalId);
this.intervalId = null;
}
#secondsToHm(seconds: number) {
let h = Math.floor(seconds / 3600);
let m = Math.floor(seconds % 3600 / 60) + 1;
if (m === 60) {
h += 1;
m = 0;
}
const output = [];
h > 0 && output.push(`${h}h`);
m > 0 && output.push(`${m}m`);
return output.join(' ');
}
// https://stackoverflow.com/a/20732091
#humanFileSize(size: number) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024));
return (size / Math.pow(1024, i)).toFixed(2) + ' ' + units[i];
destroy() {
this.serverInfo = {};
delete this.$container;
}
async render() {
if (this.#$container) {
this.#start();
return this.#$container;
if (this.$container) {
this.start();
return this.$container;
}
await this.#getServerStats();
// Video
let video = '';
if (this.#resolution) {
video = `${this.#resolution.height}p`;
}
if (this.#video) {
video && (video += '/');
video += this.#video.codec;
if (this.#video.profile) {
const profile = this.#video.profile;
let quality = profile;
if (profile.startsWith('4d')) {
quality = t('visual-quality-high');
} else if (profile.startsWith('42e')) {
quality = t('visual-quality-normal');
} else if (profile.startsWith('420')) {
quality = t('visual-quality-low');
}
video += ` (${quality})`;
}
}
// Audio
let audio;
if (this.#audio) {
audio = this.#audio.codec;
const bitrate = this.#audio.bitrate / 1000;
audio += ` (${bitrate} kHz)`;
}
await this.getServerStats();
// Battery
let batteryLevel = '';
@ -228,46 +208,51 @@ export class StreamBadges {
batteryLevel = '100%';
}
// Server + Region
let server = this.#region;
server += '@' + (this.#ipv6 ? 'IPv6' : 'IPv4');
const BADGES = [
[StreamBadge.PLAYTIME, '1m', '#ff004d'],
[StreamBadge.BATTERY, batteryLevel, '#00b543'],
[StreamBadge.DOWNLOAD, this.#humanFileSize(0), '#29adff'],
[StreamBadge.UPLOAD, this.#humanFileSize(0), '#ff77a8'],
[StreamBadge.SERVER, server, '#ff6c24'],
video ? [StreamBadge.VIDEO, video, '#742f29'] : null,
audio ? [StreamBadge.AUDIO, audio, '#5f574f'] : null,
[StreamBadge.PLAYTIME, '1m'],
[StreamBadge.BATTERY, batteryLevel],
[StreamBadge.DOWNLOAD, humanFileSize(0)],
[StreamBadge.UPLOAD, humanFileSize(0)],
this.badges.server.$element ?? [StreamBadge.SERVER, '?'],
this.serverInfo.video ? this.badges.video.$element : [StreamBadge.VIDEO, '?'],
this.serverInfo.audio ? this.badges.audio.$element : [StreamBadge.AUDIO, '?'],
];
const $container = CE('div', {'class': 'bx-badges'});
BADGES.forEach(item => {
const $container = CE('div', {class: 'bx-badges'});
for (const item of BADGES) {
if (!item) {
return;
continue;
}
const $badge = this.#renderBadge(...(item as [StreamBadge, string, string]));
$container.appendChild($badge);
});
let $badge: HTMLElement;
if (!(item instanceof HTMLElement)) {
$badge = this.renderBadge(...(item as [StreamBadge, string]));
} else {
$badge = item;
}
this.#$container = $container;
await this.#start();
$container.appendChild($badge);
};
this.$container = $container;
await this.start();
return $container;
}
async #getServerStats() {
private async getServerStats() {
const stats = await STATES.currentStream.peerConnection!.getStats();
const allVideoCodecs: {[index: string]: RTCBasicStat} = {};
const allVideoCodecs: Record<string, RTCBasicStat> = {};
let videoCodecId;
let videoWidth = 0;
let videoHeight = 0;
const allAudioCodecs: {[index: string]: RTCBasicStat} = {};
const allAudioCodecs: Record<string, RTCBasicStat> = {};
let audioCodecId;
const allCandidates: {[index: string]: string} = {};
const allCandidates: Record<string, string> = {};
let candidateId;
stats.forEach((stat: RTCBasicStat) => {
@ -284,6 +269,8 @@ export class StreamBadges {
// Get the codecId of the video/audio track currently being used
if (stat.kind === 'video') {
videoCodecId = stat.codecId;
videoWidth = stat.frameWidth;
videoHeight = stat.frameHeight;
} else if (stat.kind === 'audio') {
audioCodecId = stat.codecId;
}
@ -297,71 +284,89 @@ export class StreamBadges {
// Get video codec from codecId
if (videoCodecId) {
const videoStat = allVideoCodecs[videoCodecId];
const video: any = {
const video: StreamServerInfo['video'] = {
width: videoWidth,
height: videoHeight,
codec: videoStat.mimeType.substring(6),
};
if (video.codec === 'H264') {
const match = /profile-level-id=([0-9a-f]{6})/.exec(videoStat.sdpFmtpLine);
video.profile = match ? match[1] : null;
match && (video.profile = match[1]);
}
this.#video = video;
let text = videoHeight + 'p';
text && (text += '/');
text += video.codec;
if (video.profile) {
const profile = video.profile;
let quality = profile;
if (profile.startsWith('4d')) {
quality = t('visual-quality-high');
} else if (profile.startsWith('42e')) {
quality = t('visual-quality-normal');
} else if (profile.startsWith('420')) {
quality = t('visual-quality-low');
}
text += ` (${quality})`;
}
// Render badge
this.badges.video.$element = this.renderBadge(StreamBadge.VIDEO, text);
this.serverInfo.video = video;
}
// Get audio codec from codecId
if (audioCodecId) {
const audioStat = allAudioCodecs[audioCodecId];
this.#audio = {
const audio: StreamServerInfo['audio'] = {
codec: audioStat.mimeType.substring(6),
bitrate: audioStat.clockRate,
}
};
const bitrate = audio.bitrate / 1000;
const text = `${audio.codec} (${bitrate} kHz)`;
this.badges.audio.$element = this.renderBadge(StreamBadge.AUDIO, text);
this.serverInfo.audio = audio;
}
// Get server type
if (candidateId) {
BxLogger.info('candidate', candidateId, allCandidates);
this.#ipv6 = allCandidates[candidateId].includes(':');
// Server + Region
let text = '';
const isIpv6 = allCandidates[candidateId].includes(':');
const server = this.serverInfo.server;
if (server && server.region) {
text += server.region;
}
text += '@' + (isIpv6 ? 'IPv6' : 'IPv4');
this.badges.server.$element = this.renderBadge(StreamBadge.SERVER, text);
}
}
static setupEvents() {
window.addEventListener(BxEvent.STREAM_PLAYING, e => {
const $video = (e as any).$video;
const streamBadges = StreamBadges.getInstance();
// Since the Lite version doesn't have the "..." button on System menu
// we need to display Stream badges in the Guide menu instead
isLiteVersion() && window.addEventListener(BxEvent.XCLOUD_GUIDE_MENU_SHOWN, async e => {
const where = (e as any).where as GuideMenuTab;
streamBadges.#resolution = {
width: $video.videoWidth,
height: $video.videoHeight,
};
streamBadges.startTimestamp = +new Date;
// Get battery level
try {
STATES.browser.capabilities.batteryApi && (navigator as NavigatorBattery).getBattery().then(bm => {
streamBadges.startBatteryLevel = Math.round(bm.level * 100);
});
} catch(e) {}
});
/*
Don't do this until xCloud remove the Stream Menu page
window.addEventListener(BxEvent.XCLOUD_GUIDE_SHOWN, async e => {
const where = (e as any).where as XcloudGuideWhere;
if (where !== XcloudGuideWhere.HOME || !STATES.isPlaying) {
if (where !== GuideMenuTab.HOME || !STATES.isPlaying) {
return;
}
const $btnQuit = document.querySelector('#gamepass-dialog-root a[class*=QuitGameButton]');
if (!$btnQuit) {
return;
if ($btnQuit) {
// Add badges
$btnQuit.insertAdjacentElement('beforebegin', await StreamBadges.getInstance().render());
}
// Add badges
$btnQuit.insertAdjacentElement('beforebegin', await StreamBadges.getInstance().render());
});
*/
}
}

View File

@ -7,9 +7,10 @@ import { getPref, setPref } from "@/utils/settings-storages/global-settings-stor
export function onChangeVideoPlayerType() {
const playerType = getPref(PrefKey.VIDEO_PLAYER_TYPE);
const $videoProcessing = document.getElementById('bx_setting_video_processing') as HTMLSelectElement;
const $videoSharpness = document.getElementById('bx_setting_video_sharpness') as HTMLElement;
const $videoPowerPreference = document.getElementById('bx_setting_video_power_preference') as HTMLElement;
const $videoProcessing = document.getElementById(`bx_setting_${PrefKey.VIDEO_PROCESSING}`) as HTMLSelectElement;
const $videoSharpness = document.getElementById(`bx_setting_${PrefKey.VIDEO_SHARPNESS}`) as HTMLElement;
const $videoPowerPreference = document.getElementById(`bx_setting_${PrefKey.VIDEO_POWER_PREFERENCE}`) as HTMLElement;
const $videoMaxFps = document.getElementById(`bx_setting_${PrefKey.VIDEO_MAX_FPS}`) as HTMLElement;
if (!$videoProcessing) {
return;
@ -17,7 +18,7 @@ export function onChangeVideoPlayerType() {
let isDisabled = false;
const $optCas = $videoProcessing.querySelector(`option[value=${StreamVideoProcessing.CAS}]`) as HTMLOptionElement;
const $optCas = $videoProcessing.querySelector<HTMLOptionElement>(`option[value=${StreamVideoProcessing.CAS}]`);
if (playerType === StreamPlayerType.WEBGL2) {
$optCas && ($optCas.disabled = false);
@ -38,17 +39,26 @@ 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();
}
export function limitVideoPlayerFps(targetFps: number) {
const streamPlayer = STATES.currentStream.streamPlayer;
streamPlayer?.getWebGL2Player()?.setTargetFps(targetFps);
}
export function updateVideoPlayer() {
const streamPlayer = STATES.currentStream.streamPlayer;
if (!streamPlayer) {
return;
}
limitVideoPlayerFps(getPref(PrefKey.VIDEO_MAX_FPS));
const options = {
processing: getPref(PrefKey.VIDEO_PROCESSING),
sharpness: getPref(PrefKey.VIDEO_SHARPNESS),
@ -60,6 +70,7 @@ export function updateVideoPlayer() {
streamPlayer.setPlayerType(getPref(PrefKey.VIDEO_PLAYER_TYPE));
streamPlayer.updateOptions(options);
streamPlayer.refreshPlayer();
}
window.addEventListener('resize', updateVideoPlayer);

View File

@ -4,92 +4,123 @@ 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 { StreamStat, StreamStatsCollector, type StreamStatGrade } from "@/utils/stream-stats-collector"
import { BxLogger } from "@/utils/bx-logger"
export enum StreamStat {
PING = 'ping',
FPS = 'fps',
BITRATE = 'btr',
DECODE_TIME = 'dt',
PACKETS_LOST = 'pl',
FRAMES_LOST = 'fl',
};
export class StreamStats {
private static instance: StreamStats;
public static getInstance(): StreamStats {
if (!StreamStats.instance) {
StreamStats.instance = new StreamStats();
}
public static getInstance = () => StreamStats.instance ?? (StreamStats.instance = new StreamStats());
private readonly LOG_TAG = 'StreamStats';
return StreamStats.instance;
private intervalId?: number | null;
private readonly REFRESH_INTERVAL = 1 * 1000;
private stats = {
[StreamStat.CLOCK]: {
name: t('clock'),
$element: CE('span'),
},
[StreamStat.PLAYTIME]: {
name: t('playtime'),
$element: CE('span'),
},
[StreamStat.BATTERY]: {
name: t('battery'),
$element: CE('span'),
},
[StreamStat.PING]: {
name: t('stat-ping'),
$element: CE('span'),
},
[StreamStat.JITTER]: {
name: t('jitter'),
$element: CE('span'),
},
[StreamStat.FPS]: {
name: t('stat-fps'),
$element: CE('span'),
},
[StreamStat.BITRATE]: {
name: t('stat-bitrate'),
$element: CE('span'),
},
[StreamStat.DECODE_TIME]: {
name: t('stat-decode-time'),
$element: CE('span'),
},
[StreamStat.PACKETS_LOST]: {
name: t('stat-packets-lost'),
$element: CE('span'),
},
[StreamStat.FRAMES_LOST]: {
name: t('stat-frames-lost'),
$element: CE('span'),
},
[StreamStat.DOWNLOAD]: {
name: t('downloaded'),
$element: CE('span'),
},
[StreamStat.UPLOAD]: {
name: t('uploaded'),
$element: CE('span'),
},
};
private $container!: HTMLElement;
quickGlanceObserver?: MutationObserver | null;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.render();
}
#timeoutId?: number | null;
readonly #updateInterval = 1000;
#$container: HTMLElement | undefined;
#$fps: HTMLElement | undefined;
#$ping: HTMLElement | undefined;
#$dt: HTMLElement | undefined;
#$pl: HTMLElement | undefined;
#$fl: HTMLElement | undefined;
#$br: HTMLElement | undefined;
#lastVideoStat?: RTCBasicStat | null;
#quickGlanceObserver?: MutationObserver | null;
constructor() {
this.#render();
}
start(glancing=false) {
async start(glancing=false) {
if (!this.isHidden() || (glancing && this.isGlancing())) {
return;
}
if (this.#$container) {
this.#$container.classList.remove('bx-gone');
this.#$container.dataset.display = glancing ? 'glancing' : 'fixed';
}
this.intervalId && clearInterval(this.intervalId);
await this.update(true);
this.#timeoutId = window.setTimeout(this.#update.bind(this), this.#updateInterval);
this.$container.classList.remove('bx-gone');
this.$container.dataset.display = glancing ? 'glancing' : 'fixed';
this.intervalId = window.setInterval(this.update.bind(this), this.REFRESH_INTERVAL);
}
stop(glancing=false) {
async stop(glancing=false) {
if (glancing && !this.isGlancing()) {
return;
}
this.#timeoutId && clearTimeout(this.#timeoutId);
this.#timeoutId = null;
this.#lastVideoStat = null;
this.intervalId && clearInterval(this.intervalId);
this.intervalId = null;
if (this.#$container) {
this.#$container.removeAttribute('data-display');
this.#$container.classList.add('bx-gone');
}
this.$container.removeAttribute('data-display');
this.$container.classList.add('bx-gone');
}
toggle() {
async toggle() {
if (this.isGlancing()) {
this.#$container && (this.#$container.dataset.display = 'fixed');
this.$container && (this.$container.dataset.display = 'fixed');
} else {
this.isHidden() ? this.start() : this.stop();
this.isHidden() ? await this.start() : await this.stop();
}
}
onStoppedPlaying() {
destroy() {
this.stop();
this.quickGlanceStop();
this.hideSettingsUi();
}
isHidden = () => this.#$container && this.#$container.classList.contains('bx-gone');
isGlancing = () => this.#$container && this.#$container.dataset.display === 'glancing';
isHidden = () => this.$container.classList.contains('bx-gone');
isGlancing = () => this.$container.dataset.display === 'glancing';
quickGlanceSetup() {
if (!STATES.isPlaying || this.#quickGlanceObserver) {
if (!STATES.isPlaying || this.quickGlanceObserver) {
return;
}
@ -98,20 +129,23 @@ export class StreamStats {
return;
}
this.#quickGlanceObserver = new MutationObserver((mutationList, observer) => {
for (let record of mutationList) {
if (record.attributeName && record.attributeName === 'aria-expanded') {
const expanded = (record.target as HTMLElement).ariaExpanded;
if (expanded === 'true') {
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, {
this.quickGlanceObserver.observe($uiContainer, {
attributes: true,
attributeFilter: ['aria-expanded'],
subtree: true,
@ -119,98 +153,52 @@ export class StreamStats {
}
quickGlanceStop() {
this.#quickGlanceObserver && this.#quickGlanceObserver.disconnect();
this.#quickGlanceObserver = null;
this.quickGlanceObserver && this.quickGlanceObserver.disconnect();
this.quickGlanceObserver = null;
}
async #update() {
if (this.isHidden() || !STATES.currentStream.peerConnection) {
this.onStoppedPlaying();
private async update(forceUpdate=false) {
if ((!forceUpdate && this.isHidden()) || !STATES.currentStream.peerConnection) {
this.destroy();
return;
}
this.#timeoutId = null;
const startTime = performance.now();
const PREF_STATS_CONDITIONAL_FORMATTING = getPref(PrefKey.STATS_CONDITIONAL_FORMATTING);
let grade: StreamStatGrade = '';
const stats = await STATES.currentStream.peerConnection.getStats();
let grade = '';
// Collect stats
const statsCollector = StreamStatsCollector.getInstance();
await statsCollector.collect();
stats.forEach(stat => {
if (stat.type === 'inbound-rtp' && stat.kind === 'video') {
// FPS
this.#$fps!.textContent = stat.framesPerSecond || 0;
let statKey: keyof typeof this.stats;
for (statKey in this.stats) {
grade = '';
// Packets Lost
const packetsLost = Math.max(0, stat.packetsLost); // packetsLost can be negative, but we don't care about that
const packetsReceived = stat.packetsReceived;
const packetsLostPercentage = (packetsLost * 100 / ((packetsLost + packetsReceived) || 1)).toFixed(2);
this.#$pl!.textContent = packetsLostPercentage === '0.00' ? packetsLost.toString() : `${packetsLost} (${packetsLostPercentage}%)`;
const stat = this.stats[statKey];
const value = statsCollector.getStat(statKey);
const $element = stat.$element;
$element.textContent = value.toString();
// Frames dropped
const framesDropped = stat.framesDropped;
const framesReceived = stat.framesReceived;
const framesDroppedPercentage = (framesDropped * 100 / ((framesDropped + framesReceived) || 1)).toFixed(2);
this.#$fl!.textContent = framesDroppedPercentage === '0.00' ? framesDropped : `${framesDropped} (${framesDroppedPercentage}%)`;
if (!this.#lastVideoStat) {
this.#lastVideoStat = stat;
return;
}
const lastStat = this.#lastVideoStat;
// Bitrate
const timeDiff = stat.timestamp - lastStat.timestamp;
const bitrate = 8 * (stat.bytesReceived - lastStat.bytesReceived) / timeDiff / 1000;
this.#$br!.textContent = `${bitrate.toFixed(2)} Mbps`;
// Decode time
const totalDecodeTimeDiff = stat.totalDecodeTime - lastStat.totalDecodeTime;
const framesDecodedDiff = stat.framesDecoded - lastStat.framesDecoded;
const currentDecodeTime = totalDecodeTimeDiff / framesDecodedDiff * 1000;
if (isNaN(currentDecodeTime)) {
this.#$dt!.textContent = '??ms';
} else {
this.#$dt!.textContent = `${currentDecodeTime.toFixed(2)}ms`;
}
if (PREF_STATS_CONDITIONAL_FORMATTING) {
grade = (currentDecodeTime > 12) ? 'bad' : (currentDecodeTime > 9) ? 'ok' : (currentDecodeTime > 6) ? 'good' : '';
this.#$dt!.dataset.grade = grade;
}
this.#lastVideoStat = stat;
} else if (stat.type === 'candidate-pair' && stat.packetsReceived > 0 && stat.state === 'succeeded') {
// Round Trip Time
const roundTripTime = !!stat.currentRoundTripTime ? stat.currentRoundTripTime * 1000 : -1;
this.#$ping!.textContent = roundTripTime === -1 ? '???' : roundTripTime.toString();
if (PREF_STATS_CONDITIONAL_FORMATTING) {
grade = (roundTripTime > 100) ? 'bad' : (roundTripTime > 75) ? 'ok' : (roundTripTime > 40) ? 'good' : '';
this.#$ping!.dataset.grade = grade;
}
// Get stat's grade
if (PREF_STATS_CONDITIONAL_FORMATTING && 'grades' in value) {
grade = statsCollector.calculateGrade(value.current, value.grades);
}
});
const lapsedTime = performance.now() - startTime;
this.#timeoutId = window.setTimeout(this.#update.bind(this), this.#updateInterval - lapsedTime);
if ($element.dataset.grade !== grade) {
$element.dataset.grade = grade;
}
}
}
refreshStyles() {
const PREF_ITEMS = getPref(PrefKey.STATS_ITEMS);
const PREF_POSITION = getPref(PrefKey.STATS_POSITION);
const PREF_TRANSPARENT = getPref(PrefKey.STATS_TRANSPARENT);
const PREF_OPACITY = getPref(PrefKey.STATS_OPACITY);
const PREF_TEXT_SIZE = getPref(PrefKey.STATS_TEXT_SIZE);
const $container = this.#$container!;
const $container = this.$container;
$container.dataset.stats = '[' + PREF_ITEMS.join('][') + ']';
$container.dataset.position = PREF_POSITION;
$container.dataset.transparent = PREF_TRANSPARENT;
$container.style.opacity = PREF_OPACITY + '%';
$container.style.fontSize = PREF_TEXT_SIZE;
$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);
}
hideSettingsUi() {
@ -219,34 +207,25 @@ export class StreamStats {
}
}
#render() {
const stats = {
[StreamStat.PING]: [t('stat-ping'), this.#$ping = CE('span', {}, '0')],
[StreamStat.FPS]: [t('stat-fps'), this.#$fps = CE('span', {}, '0')],
[StreamStat.BITRATE]: [t('stat-bitrate'), this.#$br = CE('span', {}, '0 Mbps')],
[StreamStat.DECODE_TIME]: [t('stat-decode-time'), this.#$dt = CE('span', {}, '0ms')],
[StreamStat.PACKETS_LOST]: [t('stat-packets-lost'), this.#$pl = CE('span', {}, '0')],
[StreamStat.FRAMES_LOST]: [t('stat-frames-lost'), this.#$fl = CE('span', {}, '0')],
};
private async render() {
this.$container = CE('div', {class: 'bx-stats-bar bx-gone'});
const $barFragment = document.createDocumentFragment();
let statKey: keyof typeof stats;
for (statKey in stats) {
let statKey: keyof typeof this.stats;
for (statKey in this.stats) {
const stat = this.stats[statKey];
const $div = CE('div', {
'class': `bx-stat-${statKey}`,
title: stats[statKey][0]
},
class: `bx-stat-${statKey}`,
title: stat.name,
},
CE('label', {}, statKey.toUpperCase()),
stats[statKey][1],
stat.$element,
);
$barFragment.appendChild($div);
this.$container.appendChild($div);
}
this.#$container = CE('div', {'class': 'bx-stats-bar bx-gone'}, $barFragment);
this.refreshStyles();
document.documentElement.appendChild(this.#$container!);
document.documentElement.appendChild(this.$container);
}
static setupEvents() {
@ -255,8 +234,8 @@ export class StreamStats {
const PREF_STATS_SHOW_WHEN_PLAYING = getPref(PrefKey.STATS_SHOW_WHEN_PLAYING);
const streamStats = StreamStats.getInstance();
// Setup Stat's Quick Glance mode
// Setup Stat's Quick Glance mode
if (PREF_STATS_SHOW_WHEN_PLAYING) {
streamStats.start();
} else if (PREF_STATS_QUICK_GLANCE) {

View File

@ -39,7 +39,7 @@ export class StreamUiHandler {
return;
}
const $streamHud = (e.target as HTMLElement).closest('#StreamHud') as HTMLElement;
const $streamHud = (e.target as HTMLElement).closest<HTMLElement>('#StreamHud');
if (!$streamHud) {
return;
}
@ -58,13 +58,13 @@ export class StreamUiHandler {
$container.addEventListener('transitionend', onTransitionEnd);
}
const $button = $container.querySelector('button') as HTMLElement;
const $button = $container.querySelector<HTMLButtonElement>('button');
if (!$button) {
return null;
}
$button.setAttribute('title', label);
const $orgSvg = $button.querySelector('svg') as SVGElement;
const $orgSvg = $button.querySelector<SVGElement>('svg');
if (!$orgSvg) {
return null;
}
@ -102,7 +102,7 @@ export class StreamUiHandler {
}
private static async handleStreamMenu() {
const $btnCloseHud = document.querySelector('button[class*=StreamMenu-module__backButton]') as HTMLElement;
const $btnCloseHud = document.querySelector<HTMLElement>('button[class*=StreamMenu-module__backButton]');
if (!$btnCloseHud) {
return;
}
@ -135,27 +135,21 @@ export class StreamUiHandler {
}
private static handleSystemMenu($streamHud: HTMLElement) {
// Grip handle
const $gripHandle = $streamHud.querySelector('button[class^=GripHandle]') as HTMLElement;
if (!$gripHandle) {
return;
}
// Get the last button
const $orgButton = $streamHud.querySelector('div[class^=HUDButton]') as HTMLElement;
const $orgButton = $streamHud.querySelector<HTMLElement>('div[class^=HUDButton]');
if (!$orgButton) {
return;
}
const hideGripHandle = () => {
if (!$gripHandle) {
return;
// Grip handle
const $gripHandle = document.querySelector<HTMLElement>('#StreamHud button[class^=GripHandle]');
if ($gripHandle && $gripHandle.ariaExpanded === 'true') {
$gripHandle.dispatchEvent(new PointerEvent('pointerdown'));
$gripHandle.click();
$gripHandle.dispatchEvent(new PointerEvent('pointerdown'));
$gripHandle.click();
}
$gripHandle.dispatchEvent(new PointerEvent('pointerdown'));
$gripHandle.click();
$gripHandle.dispatchEvent(new PointerEvent('pointerdown'));
$gripHandle.click();
}
// Create Stream Settings button
@ -178,12 +172,12 @@ export class StreamUiHandler {
let $btnStreamStats = StreamUiHandler.$btnStreamStats;
if (typeof $btnStreamStats === 'undefined') {
$btnStreamStats = StreamUiHandler.cloneStreamHudButton($orgButton, t('stream-stats'), BxIcon.STREAM_STATS);
$btnStreamStats?.addEventListener('click', e => {
$btnStreamStats?.addEventListener('click', async (e) => {
hideGripHandle();
e.preventDefault();
// Toggle Stream Stats
streamStats.toggle();
await streamStats.toggle();
const btnStreamStatsOn = (!streamStats.isHidden() && !streamStats.isGlancing());
$btnStreamStats!.classList.toggle('bx-stream-menu-button-on', btnStreamStatsOn);
@ -227,9 +221,10 @@ export class StreamUiHandler {
}
const observer = new MutationObserver(mutationList => {
mutationList.forEach(item => {
let item: MutationRecord;
for (item of mutationList) {
if (item.type !== 'childList') {
return;
continue;
}
item.addedNodes.forEach(async $node => {
@ -269,7 +264,7 @@ export class StreamUiHandler {
// Handle System Menu bar
StreamUiHandler.handleSystemMenu($elm);
});
});
};
});
observer.observe($screen, {subtree: true, childList: true});

View File

@ -85,16 +85,24 @@ export class TouchController {
document.querySelector('#BabylonCanvasContainer-main')?.parentElement?.classList.remove('bx-offscreen');
}
/*
static #hide() {
document.querySelector('#BabylonCanvasContainer-main')?.parentElement?.classList.add('bx-offscreen');
}
*/
static toggleVisibility(status: boolean) {
static toggleVisibility(): boolean {
if (!TouchController.#dataChannel) {
return;
return false;
}
status ? TouchController.#hide() : TouchController.#show();
const $container = document.querySelector('#BabylonCanvasContainer-main')?.parentElement;
if (!$container) {
return false;
}
$container.classList.toggle('bx-offscreen');
return !$container.classList.contains('bx-offscreen');
}
static reset() {

View File

@ -1,9 +1,12 @@
import { GamepadKey } from "@/enums/mkb";
import { EmulatedMkbHandler } from "@/modules/mkb/mkb-handler";
import { PrefKey } from "@/enums/pref-keys";
import { VIRTUAL_GAMEPAD_ID } from "@/modules/mkb/mkb-handler";
import { BxEvent } from "@/utils/bx-event";
import { BxLogger } from "@/utils/bx-logger";
import { STATES } from "@/utils/global";
import { CE, isElementVisible } from "@/utils/html";
import { setNearby } from "@/utils/navigation-utils";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
export enum NavigationDirection {
UP = 1,
@ -80,18 +83,14 @@ export abstract class NavigationDialog {
}
handleGamepad(button: GamepadKey): boolean {
return true;
return false;
}
}
export class NavigationDialogManager {
private static instance: NavigationDialogManager;
public static getInstance(): NavigationDialogManager {
if (!NavigationDialogManager.instance) {
NavigationDialogManager.instance = new NavigationDialogManager();
}
return NavigationDialogManager.instance;
}
public static getInstance = () => NavigationDialogManager.instance ?? (NavigationDialogManager.instance = new NavigationDialogManager());
private readonly LOG_TAG = 'NavigationDialogManager';
private static readonly GAMEPAD_POLLING_INTERVAL = 50;
private static readonly GAMEPAD_KEYS = [
@ -139,7 +138,9 @@ export class NavigationDialogManager {
private $container: HTMLElement;
private dialog: NavigationDialog | null = null;
constructor() {
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.$overlay = CE('div', {class: 'bx-navigation-dialog-overlay bx-gone'});
this.$overlay.addEventListener('click', e => {
e.preventDefault();
@ -154,6 +155,63 @@ export class NavigationDialogManager {
// Hide dialog when the Guide menu is shown
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';
return;
}
const rect = $select.getBoundingClientRect();
let $label: HTMLElement;
let width = Math.ceil(rect.width);
if (!width) {
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';
};
}
handleEvent(event: Event) {
@ -181,7 +239,7 @@ export class NavigationDialogManager {
} else if (keyCode === 'Enter' || keyCode === 'NumpadEnter' || keyCode === 'Space') {
if (!($target instanceof HTMLInputElement && $target.type === 'text')) {
handled = true;
$target.dispatchEvent(new MouseEvent('click'));
$target.dispatchEvent(new MouseEvent('click', {bubbles: true}));
}
} else if (keyCode === 'Escape') {
handled = true;
@ -210,7 +268,7 @@ export class NavigationDialogManager {
}
// Ignore virtual controller
if (gamepad.id === EmulatedMkbHandler.VIRTUAL_GAMEPAD_ID) {
if (gamepad.id === VIRTUAL_GAMEPAD_ID) {
continue;
}
@ -308,7 +366,7 @@ export class NavigationDialogManager {
}
if (releasedButton === GamepadKey.A) {
document.activeElement && document.activeElement.dispatchEvent(new MouseEvent('click'));
document.activeElement && document.activeElement.dispatchEvent(new MouseEvent('click', {bubbles: true}));
return;
} else if (releasedButton === GamepadKey.B) {
this.hide();
@ -544,7 +602,7 @@ export class NavigationDialogManager {
const children = Array.from($elm.children);
// Search from right to left if the orientation is horizontal
const orientation = ($elm as NavigationElement).nearby?.orientation;
const orientation = ($elm as NavigationElement).nearby?.orientation || 'vertical';
if (orientation === 'horizontal' || (orientation === 'vertical' && direction === NavigationDirection.UP)) {
children.reverse();
}

View File

@ -0,0 +1,133 @@
import { ButtonStyle, CE, createButton } from "@/utils/html";
import { NavigationDialog, type NavigationElement } from "./navigation-dialog";
import { PrefKey } from "@/enums/pref-keys";
import { BxIcon } from "@/utils/bx-icon";
import { getPref, setPref } from "@/utils/settings-storages/global-settings-storage";
import { t } from "@/utils/translation";
import { RemotePlayConsoleState, RemotePlayManager } from "@/modules/remote-play-manager";
import { BxSelectElement } from "@/web-components/bx-select";
import { BxEvent } from "@/utils/bx-event";
import { BxLogger } from "@/utils/bx-logger";
export class RemotePlayNavigationDialog extends NavigationDialog {
private static instance: RemotePlayNavigationDialog;
public static getInstance = () => RemotePlayNavigationDialog.instance ?? (RemotePlayNavigationDialog.instance = new RemotePlayNavigationDialog());
private readonly LOG_TAG = 'RemotePlayNavigationDialog';
private readonly STATE_LABELS: Record<RemotePlayConsoleState, string> = {
[RemotePlayConsoleState.ON]: t('powered-on'),
[RemotePlayConsoleState.OFF]: t('powered-off'),
[RemotePlayConsoleState.STANDBY]: t('standby'),
[RemotePlayConsoleState.UNKNOWN]: t('unknown'),
};
$container!: HTMLElement;
private constructor() {
super();
BxLogger.info(this.LOG_TAG, 'constructor()');
this.setupDialog();
}
private setupDialog() {
const $fragment = CE('div', {'class': 'bx-remote-play-container'});
const $settingNote = CE('p', {});
const currentResolution = getPref(PrefKey.REMOTE_PLAY_RESOLUTION);
let $resolutions : HTMLSelectElement | NavigationElement = CE<HTMLSelectElement>('select', {},
CE('option', {value: '1080p'}, '1080p'),
CE('option', {value: '720p'}, '720p'),
);
if (getPref(PrefKey.UI_CONTROLLER_FRIENDLY)) {
$resolutions = BxSelectElement.wrap($resolutions as HTMLSelectElement);
}
$resolutions.addEventListener('input', (e: Event) => {
const value = (e.target as HTMLSelectElement).value;
$settingNote.textContent = value === '1080p' ? '✅ ' + t('can-stream-xbox-360-games') : '❌ ' + t('cant-stream-xbox-360-games');
setPref(PrefKey.REMOTE_PLAY_RESOLUTION, value);
});
($resolutions as any).value = currentResolution;
BxEvent.dispatch($resolutions, 'input', {
manualTrigger: true,
});
const $qualitySettings = CE('div', {
class: 'bx-remote-play-settings',
}, CE('div', {},
CE('label', {}, t('target-resolution'), $settingNote),
$resolutions,
));
$fragment.appendChild($qualitySettings);
// Render consoles list
const manager = RemotePlayManager.getInstance();
const consoles = manager.getConsoles();
for (let con of consoles) {
const $child = CE('div', {class: 'bx-remote-play-device-wrapper'},
CE('div', {class: 'bx-remote-play-device-info'},
CE('div', {},
CE('span', {class: 'bx-remote-play-device-name'}, con.deviceName),
CE('span', {class: 'bx-remote-play-console-type'}, con.consoleType.replace('Xbox', ''))
),
CE('div', {class: 'bx-remote-play-power-state'}, this.STATE_LABELS[con.powerState]),
),
// Connect button
createButton({
classes: ['bx-remote-play-connect-button'],
label: t('console-connect'),
style: ButtonStyle.PRIMARY | ButtonStyle.FOCUSABLE,
onClick: e => manager.play(con.serverId),
}),
);
$fragment.appendChild($child);
}
// Add buttons
$fragment.appendChild(
CE('div', {
class: 'bx-remote-play-buttons',
_nearby: {
orientation: 'horizontal',
},
},
createButton({
icon: BxIcon.QUESTION,
style: ButtonStyle.GHOST | ButtonStyle.FOCUSABLE,
url: 'https://better-xcloud.github.io/remote-play',
label: t('help'),
}),
createButton({
style: ButtonStyle.GHOST | ButtonStyle.FOCUSABLE,
label: t('close'),
onClick: e => this.hide(),
}),
),
);
this.$container = $fragment;
}
getDialog(): NavigationDialog {
return this;
}
getContent(): HTMLElement {
return this.$container;
}
focusIfNeeded(): void {
const $btnConnect = this.$container.querySelector<HTMLElement>('.bx-remote-play-device-wrapper button');
$btnConnect && $btnConnect.focus();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,15 @@
import { BxLogger } from "@/utils/bx-logger";
import { CE } from "@/utils/html";
export class FullscreenText {
private static instance: FullscreenText;
public static getInstance(): FullscreenText {
if (!FullscreenText.instance) {
FullscreenText.instance = new FullscreenText();
}
return FullscreenText.instance;
}
public static getInstance = () => FullscreenText.instance ?? (FullscreenText.instance = new FullscreenText());
private readonly LOG_TAG = 'FullscreenText';
$text: HTMLElement;
constructor() {
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.$text = CE('div', {
class: 'bx-fullscreen-text bx-gone',
});

View File

@ -1,28 +1,17 @@
import { BxEvent } from "@/utils/bx-event";
import { BxIcon } from "@/utils/bx-icon";
import { CE, createSvgIcon, getReactProps } from "@/utils/html";
import { CE, createSvgIcon, getReactProps, isElementVisible, secondsToHms } from "@/utils/html";
import { XcloudApi } from "@/utils/xcloud-api";
export class GameTile {
static #timeout: number | null;
static #secondsToHms(seconds: number) {
let h = Math.floor(seconds / 3600);
seconds %= 3600;
let m = Math.floor(seconds / 60);
let s = seconds % 60;
const output = [];
h > 0 && output.push(`${h}h`);
m > 0 && output.push(`${m}m`);
if (s > 0 || output.length === 0) {
output.push(`${s}s`);
}
return output.join(' ');
}
static async #showWaitTime($elm: HTMLElement, productId: string) {
if (($elm as any).hasWaitTime) {
return;
}
($elm as any).hasWaitTime = true;
let totalWaitTime;
const api = XcloudApi.getInstance();
@ -34,54 +23,70 @@ export class GameTile {
}
}
if (typeof totalWaitTime === 'number' && $elm.isConnected) {
if (typeof totalWaitTime === 'number' && isElementVisible($elm)) {
const $div = CE('div', {'class': 'bx-game-tile-wait-time'},
createSvgIcon(BxIcon.PLAYTIME),
CE('span', {}, GameTile.#secondsToHms(totalWaitTime)),
CE('span', {}, secondsToHms(totalWaitTime)),
);
$elm.insertAdjacentElement('afterbegin', $div);
}
}
static requestWaitTime($elm: HTMLElement, productId: string) {
static #requestWaitTime($elm: HTMLElement, productId: string) {
GameTile.#timeout && clearTimeout(GameTile.#timeout);
GameTile.#timeout = window.setTimeout(async () => {
if (!($elm as any).hasWaitTime) {
($elm as any).hasWaitTime = true;
GameTile.#showWaitTime($elm, productId);
GameTile.#showWaitTime($elm, productId);
}, 500);
}
static #findProductId($elm: HTMLElement): string | null {
let productId = null;
try {
if (($elm.tagName === 'BUTTON' && $elm.className.includes('MruGameCard')) || (($elm.tagName === 'A' && $elm.className.includes('GameCard')))) {
let props = getReactProps($elm.parentElement!);
// When context menu is enabled
if (Array.isArray(props.children)) {
productId = props.children[0].props.productId;
} else {
productId = props.children.props.productId;
}
} else if ($elm.tagName === 'A' && $elm.className.includes('GameItem')) {
let props = getReactProps($elm.parentElement!);
props = props.children.props;
if (props.location !== 'NonStreamableGameItem') {
if ('productId' in props) {
productId = props.productId;
} else {
// Search page
productId = props.children.props.productId;
}
}
}
}, 1000);
} catch (e) {}
return productId;
}
static setup() {
window.addEventListener(BxEvent.NAVIGATION_FOCUS_CHANGED, e => {
let productId;
const $elm = (e as any).element;
try {
if (($elm.tagName === 'BUTTON' && $elm.className.includes('MruGameCard')) || (($elm.tagName === 'A' && $elm.className.includes('GameCard')))) {
let props = getReactProps($elm.parentElement);
// When context menu is enabled
if (Array.isArray(props.children)) {
productId = props.children[0].props.productId;
} else {
productId = props.children.props.productId;
}
} else if ($elm.tagName === 'A' && $elm.className.includes('GameItem')) {
let props = getReactProps($elm.parentElement);
props = props.children.props;
if (props.location !== 'NonStreamableGameItem') {
if ('productId' in props) {
productId = props.productId;
} else {
// Search page
productId = props.children.props.productId;
}
}
const className = $elm.className || '';
if (className.includes('MruGameCard')) {
// Show the wait time of every games in the "Jump back in" section all at once
const $ol = $elm.closest('ol');
if ($ol && !($ol as any).hasWaitTime) {
($ol as any).hasWaitTime = true;
$ol.querySelectorAll('button[class*=MruGameCard]').forEach(($elm: HTMLElement) => {
const productId = GameTile.#findProductId($elm);
productId && GameTile.#showWaitTime($elm, productId);
});
}
} catch (e) {}
productId && GameTile.requestWaitTime($elm, productId);
} else {
const productId = GameTile.#findProductId($elm);
productId && GameTile.#requestWaitTime($elm, productId);
}
});
}
}

View File

@ -1,150 +1,225 @@
import { isFullVersion } from "@macros/build" with {type: "macro"};
import { BxEvent } from "@/utils/bx-event";
import { AppInterface, STATES } from "@/utils/global";
import { createButton, ButtonStyle, CE } from "@/utils/html";
import { t } from "@/utils/translation";
import { SettingsNavigationDialog } from "./dialog/settings-dialog";
import { TrueAchievements } from "@/utils/true-achievements";
import { BxIcon } from "@/utils/bx-icon";
export enum GuideMenuTab {
HOME = 'home',
}
export class GuideMenu {
static #BUTTONS = {
scriptSettings: createButton({
label: t('better-xcloud'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE | ButtonStyle.PRIMARY,
onClick: e => {
// Wait until the Guide dialog is closed
window.addEventListener(BxEvent.XCLOUD_DIALOG_DISMISSED, e => {
setTimeout(() => SettingsNavigationDialog.getInstance().show(), 50);
}, {once: true});
private static instance: GuideMenu;
public static getInstance = () => GuideMenu.instance ?? (GuideMenu.instance = new GuideMenu());
// Close all xCloud's dialogs
window.BX_EXPOSED.dialogRoutes.closeAll();
},
}),
private $renderedButtons?: HTMLElement;
appSettings: createButton({
label: t('app-settings'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE,
onClick: e => {
// Close all xCloud's dialogs
window.BX_EXPOSED.dialogRoutes.closeAll();
AppInterface.openAppSettings && AppInterface.openAppSettings();
},
}),
closeApp: createButton({
label: t('close-app'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE | ButtonStyle.DANGER,
onClick: e => {
AppInterface.closeApp();
},
}),
reloadPage: createButton({
label: t('reload-page'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE,
onClick: e => {
if (STATES.isPlaying) {
confirm(t('confirm-reload-stream')) && window.location.reload();
} else {
window.location.reload();
}
// Close all xCloud's dialogs
window.BX_EXPOSED.dialogRoutes.closeAll();
},
}),
backToHome: createButton({
label: t('back-to-home'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE,
onClick: e => {
confirm(t('back-to-home-confirm')) && (window.location.href = window.location.href.substring(0, 31));
},
}),
}
static #renderButtons(buttons: HTMLElement[]) {
const $div = CE('div', {});
for (const $button of buttons) {
$div.appendChild($button);
closeGuideMenu() {
if (window.BX_EXPOSED.dialogRoutes) {
window.BX_EXPOSED.dialogRoutes.closeAll();
return;
}
// Use alternative method for Lite version
const $btnClose = document.querySelector<HTMLElement>('#gamepass-dialog-root button[class^=Header-module__closeButton]');
$btnClose && $btnClose.click();
}
private renderButtons() {
if (this.$renderedButtons) {
return this.$renderedButtons;
}
const buttons = {
scriptSettings: createButton({
label: t('better-xcloud'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE | ButtonStyle.PRIMARY,
onClick: (() => {
// Wait until the Guide dialog is closed
window.addEventListener(BxEvent.XCLOUD_DIALOG_DISMISSED, e => {
setTimeout(() => SettingsNavigationDialog.getInstance().show(), 50);
}, {once: true});
// Close all xCloud's dialogs
this.closeGuideMenu();
}).bind(this),
}),
closeApp: AppInterface && createButton({
icon: BxIcon.POWER,
label: t('close-app'),
title: t('close-app'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE | ButtonStyle.DANGER,
onClick: e => {
AppInterface.closeApp();
},
attributes: {
'data-state': 'normal',
},
}),
reloadPage: createButton({
icon: BxIcon.REFRESH,
label: t('reload-page'),
title: t('reload-page'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE,
onClick: (() => {
// Close all xCloud's dialogs
this.closeGuideMenu();
if (STATES.isPlaying) {
confirm(t('confirm-reload-stream')) && window.location.reload();
} else {
window.location.reload();
}
}).bind(this),
}),
backToHome: createButton({
icon: BxIcon.HOME,
label: t('back-to-home'),
title: t('back-to-home'),
style: ButtonStyle.FULL_WIDTH | ButtonStyle.FOCUSABLE,
onClick: (() => {
// Close all xCloud's dialogs
this.closeGuideMenu();
confirm(t('back-to-home-confirm')) && (window.location.href = window.location.href.substring(0, 31));
}).bind(this),
attributes: {
'data-state': 'playing',
},
}),
};
const buttonsLayout = [
buttons.scriptSettings,
[
buttons.backToHome,
buttons.reloadPage,
buttons.closeApp,
],
];
const $div = CE('div', {
class: 'bx-guide-home-buttons',
});
for (const $button of buttonsLayout) {
if (!$button) {
continue;
}
if ($button instanceof HTMLElement) {
$div.appendChild($button);
} else if (Array.isArray($button)) {
const $wrapper = CE('div', {});
for (const $child of $button) {
$child && $wrapper.appendChild($child);
}
$div.appendChild($wrapper);
}
}
this.$renderedButtons = $div;
return $div;
}
static #injectHome($root: HTMLElement) {
// Find the last divider
const $dividers = $root.querySelectorAll('div[class*=Divider-module__divider]');
if (!$dividers) {
return;
injectHome($root: HTMLElement, isPlaying = false) {
if (isFullVersion()) {
const $achievementsProgress = $root.querySelector('button[class*=AchievementsButton-module__progressBarContainer]');
if ($achievementsProgress) {
TrueAchievements.getInstance().injectAchievementsProgress($achievementsProgress as HTMLElement);
}
}
const buttons: HTMLElement[] = [];
// Find the element to add buttons to
let $target: HTMLElement | null = null;
if (isPlaying) {
// Quit button
$target = $root.querySelector('a[class*=QuitGameButton]');
// "Better xCloud" button
buttons.push(GuideMenu.#BUTTONS.scriptSettings);
// "App settings" button
AppInterface && buttons.push(GuideMenu.#BUTTONS.appSettings);
// "Reload page" button
buttons.push(GuideMenu.#BUTTONS.reloadPage);
// "Close app" buttons
AppInterface && buttons.push(GuideMenu.#BUTTONS.closeApp);
const $buttons = GuideMenu.#renderButtons(buttons);
const $lastDivider = $dividers[$dividers.length - 1];
$lastDivider.insertAdjacentElement('afterend', $buttons);
}
static #injectHomePlaying($root: HTMLElement) {
const $btnQuit = $root.querySelector('a[class*=QuitGameButton]');
if (!$btnQuit) {
return;
// Hide xCloud's Home button
const $btnXcloudHome = $root.querySelector<HTMLElement>('div[class^=HomeButtonWithDivider]');
$btnXcloudHome && ($btnXcloudHome.style.display = 'none');
} else {
// Last divider
const $dividers = $root.querySelectorAll('div[class*=Divider-module__divider]');
if ($dividers) {
$target = $dividers[$dividers.length - 1] as HTMLElement;
}
}
const buttons: HTMLElement[] = [];
if (!$target) {
return false;
}
buttons.push(GuideMenu.#BUTTONS.scriptSettings);
AppInterface && buttons.push(GuideMenu.#BUTTONS.appSettings);
// Reload page
buttons.push(GuideMenu.#BUTTONS.reloadPage);
// Back to home
buttons.push(GuideMenu.#BUTTONS.backToHome);
const $buttons = GuideMenu.#renderButtons(buttons);
$btnQuit.insertAdjacentElement('afterend', $buttons);
// Hide xCloud's Home button
const $btnXcloudHome = $root.querySelector('div[class^=HomeButtonWithDivider]') as HTMLElement;
$btnXcloudHome && ($btnXcloudHome.style.display = 'none');
const $buttons = this.renderButtons();
$buttons.dataset.isPlaying = isPlaying.toString();
$target.insertAdjacentElement('afterend', $buttons);
}
static async #onShown(e: Event) {
async onShown(e: Event) {
const where = (e as any).where as GuideMenuTab;
if (where === GuideMenuTab.HOME) {
const $root = document.querySelector('#gamepass-dialog-root div[role=dialog] div[role=tabpanel] div[class*=HomeLandingPage]') as HTMLElement;
if ($root) {
if (STATES.isPlaying) {
GuideMenu.#injectHomePlaying($root);
} else {
GuideMenu.#injectHome($root);
}
}
const $root = document.querySelector<HTMLElement>('#gamepass-dialog-root div[role=dialog] div[role=tabpanel] div[class*=HomeLandingPage]');
$root && this.injectHome($root, STATES.isPlaying);
}
}
static observe() {
window.addEventListener(BxEvent.XCLOUD_GUIDE_MENU_SHOWN, GuideMenu.#onShown);
addEventListeners() {
window.addEventListener(BxEvent.XCLOUD_GUIDE_MENU_SHOWN, this.onShown.bind(this));
}
observe($addedElm: HTMLElement) {
let className = $addedElm.className;
// Fix custom buttons disappearing in Guide Menu (#551)
if (!className) {
className = $addedElm.firstElementChild?.className ?? '';
}
if (!className || className.startsWith('bx-')) {
return;
}
// TrueAchievements
if (isFullVersion() && className.includes('AchievementsButton-module__progressBarContainer')) {
TrueAchievements.getInstance().injectAchievementsProgress($addedElm);
return;
}
if (!className.startsWith('NavigationAnimation') &&
!className.startsWith('DialogRoutes') &&
!className.startsWith('Dialog-module__container')) {
return;
}
// Achievement Details page
if (isFullVersion()) {
const $achievDetailPage = $addedElm.querySelector('div[class*=AchievementDetailPage]');
if ($achievDetailPage) {
TrueAchievements.getInstance().injectAchievementDetailPage($achievDetailPage as HTMLElement);
return;
}
}
// Find navigation bar
const $selectedTab = $addedElm.querySelector('div[class^=NavigationMenu] button[aria-selected=true');
if ($selectedTab) {
let $elm: Element | null = $selectedTab;
let index;
for (index = 0; ($elm = $elm?.previousElementSibling); index++);
if (index === 0) {
BxEvent.dispatch(window, BxEvent.XCLOUD_GUIDE_MENU_SHOWN, {where: GuideMenuTab.HOME});
}
}
}
}

View File

@ -2,41 +2,50 @@ import { SCRIPT_VERSION } from "@utils/global";
import { createButton, ButtonStyle, CE, isElementVisible } from "@utils/html";
import { BxIcon } from "@utils/bx-icon";
import { getPreferredServerRegion } from "@utils/region";
import { RemotePlay } from "@modules/remote-play";
import { RemotePlayManager } from "@/modules/remote-play-manager";
import { t } from "@utils/translation";
import { SettingsNavigationDialog } from "./dialog/settings-dialog";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { BxLogger } from "@/utils/bx-logger";
export class HeaderSection {
static #$remotePlayBtn = createButton({
classes: ['bx-header-remote-play-button', 'bx-gone'],
icon: BxIcon.REMOTE_PLAY,
title: t('remote-play'),
style: ButtonStyle.GHOST | ButtonStyle.FOCUSABLE | ButtonStyle.CIRCULAR,
onClick: e => {
RemotePlay.togglePopup();
},
});
private static instance: HeaderSection;
public static getInstance = () => HeaderSection.instance ?? (HeaderSection.instance = new HeaderSection());
private readonly LOG_TAG = 'HeaderSection';
static #$settingsBtn = createButton({
classes: ['bx-header-settings-button'],
label: '???',
style: ButtonStyle.FROSTED | ButtonStyle.DROP_SHADOW | ButtonStyle.FOCUSABLE | ButtonStyle.FULL_HEIGHT,
onClick: e => {
SettingsNavigationDialog.getInstance().show();
},
});
private $btnRemotePlay: HTMLElement;
private $btnSettings: HTMLElement;
private $buttonsWrapper: HTMLElement;
static #$buttonsWrapper = CE('div', {},
getPref(PrefKey.REMOTE_PLAY_ENABLED) ? HeaderSection.#$remotePlayBtn : null,
HeaderSection.#$settingsBtn,
);
private observer?: MutationObserver;
private timeoutId?: number | null;
static #observer: MutationObserver;
static #timeout: number | null;
constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
static #injectSettingsButton($parent?: HTMLElement) {
this.$btnRemotePlay = createButton({
classes: ['bx-header-remote-play-button', 'bx-gone'],
icon: BxIcon.REMOTE_PLAY,
title: t('remote-play'),
style: ButtonStyle.GHOST | ButtonStyle.FOCUSABLE | ButtonStyle.CIRCULAR,
onClick: e => RemotePlayManager.getInstance().togglePopup(),
});
this.$btnSettings = createButton({
classes: ['bx-header-settings-button'],
label: '???',
style: ButtonStyle.FROSTED | ButtonStyle.DROP_SHADOW | ButtonStyle.FOCUSABLE | ButtonStyle.FULL_HEIGHT,
onClick: e => SettingsNavigationDialog.getInstance().show(),
});
this.$buttonsWrapper = CE('div', {},
getPref(PrefKey.REMOTE_PLAY_ENABLED) ? this.$btnRemotePlay : null,
this.$btnSettings,
);
}
private injectSettingsButton($parent?: HTMLElement) {
if (!$parent) {
return;
}
@ -44,8 +53,8 @@ export class HeaderSection {
const PREF_LATEST_VERSION = getPref(PrefKey.LATEST_VERSION);
// Setup Settings button
const $btnSettings = HeaderSection.#$settingsBtn;
if (isElementVisible(HeaderSection.#$buttonsWrapper)) {
const $btnSettings = this.$btnSettings;
if (isElementVisible(this.$buttonsWrapper)) {
return;
}
@ -57,38 +66,42 @@ export class HeaderSection {
}
// Add the Settings button to the web page
$parent.appendChild(HeaderSection.#$buttonsWrapper);
$parent.appendChild(this.$buttonsWrapper);
}
static checkHeader() {
private checkHeader() {
let $target = document.querySelector('#PageContent div[class*=EdgewaterHeader-module__rightSectionSpacing]');
if (!$target) {
$target = document.querySelector("div[class^=UnsupportedMarketPage-module__buttons]");
$target = document.querySelector('div[class^=UnsupportedMarketPage-module__buttons]');
}
$target && HeaderSection.#injectSettingsButton($target as HTMLElement);
$target && this.injectSettingsButton($target as HTMLElement);
}
static showRemotePlayButton() {
HeaderSection.#$remotePlayBtn.classList.remove('bx-gone');
}
static watchHeader() {
private watchHeader() {
const $root = document.querySelector('#PageContent header') || document.querySelector('#root');
if (!$root) {
return;
}
HeaderSection.#timeout && clearTimeout(HeaderSection.#timeout);
HeaderSection.#timeout = null;
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = null;
HeaderSection.#observer && HeaderSection.#observer.disconnect();
HeaderSection.#observer = new MutationObserver(mutationList => {
HeaderSection.#timeout && clearTimeout(HeaderSection.#timeout);
HeaderSection.#timeout = window.setTimeout(HeaderSection.checkHeader, 2000);
this.observer && this.observer.disconnect();
this.observer = new MutationObserver(mutationList => {
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(this.checkHeader.bind(this), 2000);
});
HeaderSection.#observer.observe($root, {subtree: true, childList: true});
this.observer.observe($root, {subtree: true, childList: true});
HeaderSection.checkHeader();
this.checkHeader();
}
showRemotePlayButton() {
this.$btnRemotePlay.classList.remove('bx-gone');
}
static watchHeader() {
HeaderSection.getInstance().watchHeader();
}
}

View File

@ -1,34 +1,50 @@
import { BX_FLAGS } from "@/utils/bx-flags";
import { BxIcon } from "@/utils/bx-icon";
import { AppInterface } from "@/utils/global";
import { ButtonStyle, createButton } from "@/utils/html";
import { ButtonStyle, CE, createButton } from "@/utils/html";
import { t } from "@/utils/translation";
import { parseDetailsPath } from "@/utils/utils";
export class ProductDetailsPage {
private static $btnShortcut = createButton({
classes: ['bx-button-shortcut'],
private static $btnShortcut = AppInterface && createButton({
icon: BxIcon.CREATE_SHORTCUT,
label: t('create-shortcut'),
style: ButtonStyle.FOCUSABLE,
tabIndex: 0,
onClick: e => {
AppInterface && AppInterface.createShortcut(window.location.pathname.substring(6));
AppInterface.createShortcut(window.location.pathname.substring(6));
},
});
private static shortcutTimeoutId: number | null = null;
private static $btnWallpaper = AppInterface && createButton({
icon: BxIcon.DOWNLOAD,
label: t('wallpaper'),
style: ButtonStyle.FOCUSABLE,
tabIndex: 0,
onClick: e => {
const details = parseDetailsPath(window.location.pathname);
details && AppInterface.downloadWallpapers(details.titleSlug, details.productId);
},
});
static injectShortcutButton() {
if (!AppInterface || BX_FLAGS.DeviceInfo.deviceType !== 'android') {
private static injectTimeoutId: number | null = null;
static injectButtons() {
if (!AppInterface) {
return;
}
ProductDetailsPage.shortcutTimeoutId && clearTimeout(ProductDetailsPage.shortcutTimeoutId);
ProductDetailsPage.shortcutTimeoutId = window.setTimeout(() => {
ProductDetailsPage.injectTimeoutId && clearTimeout(ProductDetailsPage.injectTimeoutId);
ProductDetailsPage.injectTimeoutId = window.setTimeout(() => {
// Find action buttons container
const $container = document.querySelector('div[class*=ActionButtons-module__container]');
if ($container) {
$container.parentElement?.appendChild(ProductDetailsPage.$btnShortcut);
if ($container && $container.parentElement) {
$container.parentElement.appendChild(CE('div', {
class: 'bx-product-details-buttons',
},
BX_FLAGS.DeviceInfo.deviceType === 'android' && ProductDetailsPage.$btnShortcut,
ProductDetailsPage.$btnWallpaper,
));
}
}, 500);
}

View File

@ -11,7 +11,7 @@ export function localRedirect(path: string) {
const $anchor = CE<HTMLAnchorElement>('a', {
href: url,
class: 'bx-hidden bx-offscreen'
class: 'bx-hidden bx-offscreen',
}, '');
$anchor.addEventListener('click', e => {
// Remove element after clicking on it

View File

@ -1,7 +1,7 @@
import { AppInterface } from "@utils/global";
import { BxEvent } from "@utils/bx-event";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "@/utils/settings-storages/global-settings-storage";
import { ControllerDeviceVibration, getPref } from "@/utils/settings-storages/global-settings-storage";
const VIBRATION_DATA_MAP = {
'gamepadIndex': 8,
@ -69,9 +69,9 @@ export class VibrationManager {
const value = getPref(PrefKey.CONTROLLER_DEVICE_VIBRATION);
let enabled;
if (value === 'on') {
if (value === ControllerDeviceVibration.ON) {
enabled = true;
} else if (value === 'auto') {
} else if (value === ControllerDeviceVibration.AUTO) {
enabled = true;
const gamepads = window.navigator.getGamepads();
for (const gamepad of gamepads) {

71
src/types/index.d.ts vendored
View File

@ -1,7 +1,9 @@
type BuildVariant = 'full' | 'lite';
// Get type of an array's element
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
type PartialRecord<K extends keyof any, T> = Partial<Record<K, T>>
type PartialRecord<K extends keyof any, T> = Partial<Record<K, T>>;
interface Window {
AppInterface: any;
@ -10,6 +12,7 @@ interface Window {
BX_EXPOSED: any;
BX_VIBRATION_INTENSITY: number;
BX_CONTROLLER_POLLING_RATE: number;
BX_ENABLE_CONTROLLER_VIBRATION: boolean;
BX_ENABLE_DEVICE_VIBRATION: boolean;
@ -18,20 +21,29 @@ interface Window {
interface NavigatorBattery extends Navigator {
getBattery: () => Promise<{
charging: boolean,
level: float,
charging: boolean;
level: float;
}>,
}
type ServerContinent = 'america-north' | 'america-south' | 'asia' | 'australia' | 'europe' | 'other';
type ServerRegion = {
baseUri: string;
isDefault: boolean;
name: string;
shortName: string;
contintent: ServerContinent;
};
type BxStates = {
supportedRegion: boolean;
serverRegions: any;
serverRegions: Record<string, ServerRegion>;
selectedRegion: any;
gsToken: string;
isSignedIn: boolean;
isPlaying: boolean;
appContext: any | null;
browser: {
capabilities: {
@ -44,13 +56,14 @@ type BxStates = {
isTv: boolean;
capabilities: {
touch: boolean;
mkb: boolean;
};
};
currentStream: Partial<{
titleId: string;
productId: string;
titleSlug: string;
titleInfo: XcloudTitleInfo;
xboxTitleId: number;
streamPlayer: StreamPlayer | null;
@ -65,18 +78,18 @@ type BxStates = {
config: {
serverId: string;
};
titleId?: string;
}>;
pointerServerPort: number;
}
type DualEnum = {[index: string]: number} & {[index: number]: string};
type XcloudTitleInfo = {
titleId: string,
details: {
productId: string;
xboxTitleId: number;
supportedInputTypes: InputType[];
supportedTabs: any[];
hasNativeTouchSupport: boolean;
@ -86,6 +99,7 @@ type XcloudTitleInfo = {
};
product: {
title: string;
heroImageUrl: string;
titledHeroImageUrl: string;
tileImageUrl: string;
@ -120,3 +134,42 @@ type MkbMouseWheel = {
vertical: number;
horizontal: number;
}
type XboxAchievement = {
version: number;
id: string;
name: string;
gamerscore: number;
isSecret: boolean;
isUnlocked: boolean;
description: {
locked: string;
unlocked: string;
};
imageUrl: string,
requirements: Array<{
current: number;
target: number;
percentComplete: number;
}>;
percentComplete: 0,
rarity: {
currentCategory: string;
currentPercentage: number;
};
rewards: Array<{
value: number;
valueType: string;
type: string;
}>;
title: {
id: string;
scid: string;
productId: string;
name: string;
}
};

View File

@ -3,8 +3,9 @@ export type PreferenceSetting = {
optionsGroup?: string;
options?: {[index: string]: string};
multipleOptions?: {[index: string]: string};
unsupported?: string | boolean;
note?: string | HTMLElement;
unsupported?: boolean;
unsupportedNote?: string | (() => HTMLElement);
note?: string | (() => HTMLElement);
type?: SettingElementType;
ready?: (setting: PreferenceSetting) => void;
migrate?: (this: Preferences, savedPrefs: any, value: any) => void;

View File

@ -1,11 +1,31 @@
import type { PrefKey } from "@/enums/pref-keys";
import type { SettingElementType } from "@/utils/setting-element";
export type SuggestedSettingCategory = 'recommended' | 'lowest' | 'highest' | 'default';
export type RecommendedSettings = {
schema_version: 1,
device_name: string,
device_type: 'android' | 'android-tv' | 'android-handheld' | 'webos',
settings: {
app: any,
script: {
_base?: 'lowest' | 'highest',
} & PartialRecord<PrefKey, any>,
},
};
export type SettingDefinition = {
default: any;
} & Partial<{
label: string;
note: string | HTMLElement;
note: string | (() => HTMLElement);
experimental: boolean;
unsupported: string | boolean;
unsupported: boolean;
unsupportedNote: string | (() => HTMLElement);
suggest: PartialRecord<SuggestedSettingCategory, any>,
ready: (setting: SettingDefinition) => void;
type: SettingElementType,
requiredVariants: BuildVariant | Array<BuildVariant>;
// migrate?: (this: Preferences, savedPrefs: any, value: any) => void;
}> & (
{} | {
@ -39,4 +59,5 @@ export type NumberStepperParams = Partial<{
exactTicks: number;
customTextValue: (value: any) => string | null;
reverse: boolean;
}>

View File

@ -3,6 +3,8 @@ type RTCBasicStat = {
bytesReceived: number,
clockRate: number,
codecId: string,
frameWidth: number,
frameHeight: number,
framesDecoded: number,
id: string,
kind: string,

View File

@ -1,4 +1,6 @@
import { AppInterface } from "@utils/global";
import { BxLogger } from "./bx-logger";
import { BX_FLAGS } from "./bx-flags";
export namespace BxEvent {
@ -35,6 +37,7 @@ export namespace BxEvent {
export const GAME_BAR_ACTION_ACTIVATED = 'bx-game-bar-action-activated';
export const MICROPHONE_STATE_CHANGED = 'bx-microphone-state-changed';
export const SPEAKER_STATE_CHANGED = 'bx-speaker-state-changed';
export const CAPTURE_SCREENSHOT = 'bx-capture-screenshot';
@ -51,7 +54,7 @@ export namespace BxEvent {
export const XCLOUD_POLLING_MODE_CHANGED = 'bx-xcloud-polling-mode-changed';
export const XCLOUD_RENDERING_COMPONENT = 'bx-xcloud-rendering-page';
export const XCLOUD_RENDERING_COMPONENT = 'bx-xcloud-rendering-component';
export const XCLOUD_ROUTER_HISTORY_READY = 'bx-xcloud-router-history-ready';
@ -75,6 +78,8 @@ export namespace BxEvent {
target.dispatchEvent(event);
AppInterface && AppInterface.onEvent(eventName);
BX_FLAGS.Debug && BxLogger.warning('BxEvent', 'dispatch', eventName, data)
}
}

View File

@ -1,3 +1,5 @@
import { isFullVersion } from "@macros/build" with {type: "macro"};
import { ControllerShortcut } from "@/modules/controller-shortcut";
import { BxEvent } from "@utils/bx-event";
import { deepClone, STATES } from "@utils/global";
@ -5,7 +7,9 @@ import { BxLogger } from "./bx-logger";
import { BX_FLAGS } from "./bx-flags";
import { NavigationDialogManager } from "@/modules/ui/dialog/navigation-dialog";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "./settings-storages/global-settings-storage";
import { getPref, StreamTouchController } from "./settings-storages/global-settings-storage";
import { GamePassCloudGallery } from "@/enums/game-pass-gallery";
import { TouchController } from "@/modules/touch-controller";
export enum SupportedInputType {
CONTROLLER = 'Controller',
@ -20,7 +24,61 @@ export type SupportedInputTypeValue = (typeof SupportedInputType)[keyof typeof S
export const BxExposed = {
getTitleInfo: () => STATES.currentStream.titleInfo,
modifyTitleInfo: (titleInfo: XcloudTitleInfo): XcloudTitleInfo => {
modifyPreloadedState: isFullVersion() && ((state: any) => {
let LOG_TAG = 'PreloadState';
// Override User-Agent
try {
state.appContext.requestInfo.userAgent = window.navigator.userAgent;
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
// Add list of games with custom layouts to the official list
try {
const sigls = state.xcloud.sigls;
if (STATES.userAgent.capabilities.touch) {
// The list of custom touch controls
let customList = TouchController.getCustomList();
// Remove non-cloud games from the official list
const allGames = sigls[GamePassCloudGallery.ALL].data.products;
customList = customList.filter(id => allGames.includes(id));
// Add to the official touchlist
sigls[GamePassCloudGallery.TOUCH]?.data.products.push(...customList);
}
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
// Add forced Native MKB titles to the official list
try {
const sigls = state.xcloud.sigls;
if (BX_FLAGS.ForceNativeMkbTitles) {
// Add to the official list
sigls[GamePassCloudGallery.NATIVE_MKB]?.data.products.push(...BX_FLAGS.ForceNativeMkbTitles);
}
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
// Redirect to /en-US/play if visiting from an unsupported region
try {
const xCloud = state.xcloud.authentication.authStatusByStrategy.XCloud;
if (xCloud.type === 3 && xCloud.error.type === 'UnsupportedMarketError') {
// Redirect to /en-US/play
window.stop();
window.location.href = 'https://www.xbox.com/en-US/play';
}
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
return state;
}),
modifyTitleInfo: isFullVersion() && function(titleInfo: XcloudTitleInfo): XcloudTitleInfo {
// Clone the object since the original is read-only
titleInfo = deepClone(titleInfo);
@ -41,7 +99,7 @@ export const BxExposed = {
let touchControllerAvailability = getPref(PrefKey.STREAM_TOUCH_CONTROLLER);
// Disable touch control when gamepad found
if (touchControllerAvailability !== 'off' && getPref(PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF)) {
if (touchControllerAvailability !== StreamTouchController.OFF && getPref(PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF)) {
const gamepads = window.navigator.getGamepads();
let gamepadFound = false;
@ -52,10 +110,10 @@ export const BxExposed = {
}
}
gamepadFound && (touchControllerAvailability = 'off');
gamepadFound && (touchControllerAvailability = StreamTouchController.OFF);
}
if (touchControllerAvailability === 'off') {
if (touchControllerAvailability === StreamTouchController.OFF) {
// Disable touch on all games (not native touch)
supportedInputTypes = supportedInputTypes.filter(i => i !== SupportedInputType.CUSTOM_TOUCH_OVERLAY && i !== SupportedInputType.GENERIC_TOUCH);
// Empty TABs
@ -68,7 +126,7 @@ export const BxExposed = {
supportedInputTypes.includes(SupportedInputType.CUSTOM_TOUCH_OVERLAY) ||
supportedInputTypes.includes(SupportedInputType.GENERIC_TOUCH);
if (!titleInfo.details.hasTouchSupport && touchControllerAvailability === 'all') {
if (!titleInfo.details.hasTouchSupport && touchControllerAvailability === StreamTouchController.ALL) {
// Add generic touch support for non touch-supported games
titleInfo.details.hasFakeTouchSupport = true;
supportedInputTypes.push(SupportedInputType.GENERIC_TOUCH);
@ -110,8 +168,8 @@ export const BxExposed = {
}
},
handleControllerShortcut: ControllerShortcut.handle,
resetControllerShortcut: ControllerShortcut.reset,
handleControllerShortcut: isFullVersion() && ControllerShortcut.handle,
resetControllerShortcut: isFullVersion() && ControllerShortcut.reset,
overrideSettings: {
'Tv_settings': {
@ -142,4 +200,10 @@ export const BxExposed = {
return false;
},
GameSlugRegexes: [
/[;,/?:@&=+_`~$%#^*()!^\u2122\xae\xa9]/g,
/ {2,}/g,
/ /g,
],
};

View File

@ -1,4 +1,8 @@
type BxFlags = {
import { BxLogger } from "./bx-logger";
export type BxFlags = {
Debug: boolean;
CheckForUpdate: boolean;
EnableXcloudLogging: boolean;
SafariWorkaround: boolean;
@ -7,13 +11,22 @@ type BxFlags = {
FeatureGates: {[key: string]: boolean} | null,
DeviceInfo: {
deviceType: 'android' | 'android-tv' | 'webos' | 'unknown',
deviceType: 'android' | 'android-tv' | 'android-handheld' | 'webos' | 'unknown',
userAgent?: string,
androidInfo?: {
manufacturer: string,
brand: string,
board: string,
model: string,
},
}
}
// Setup flags
const DEFAULT_FLAGS: BxFlags = {
Debug: false,
CheckForUpdate: true,
EnableXcloudLogging: false,
SafariWorkaround: true,
@ -35,4 +48,6 @@ if (!BX_FLAGS.DeviceInfo.userAgent) {
BX_FLAGS.DeviceInfo.userAgent = window.navigator.userAgent;
}
BxLogger.info('BxFlags', BX_FLAGS);
export const NATIVE_FETCH = window.fetch;

View File

@ -1,4 +1,6 @@
// Credit: https://phosphoricons.com
import iconBetterXcloud from "@assets/svg/better-xcloud.svg" with { type: "text" };
import iconTrueAchievements from "@assets/svg/true-achievements.svg" with { type: "text" };
import iconClose from "@assets/svg/close.svg" with { type: "text" };
import iconCommand from "@assets/svg/command.svg" with { type: "text" };
import iconController from "@assets/svg/controller.svg" with { type: "text" };
@ -6,12 +8,16 @@ import iconCopy from "@assets/svg/copy.svg" with { type: "text" };
import iconCreateShortcut from "@assets/svg/create-shortcut.svg" with { type: "text" };
import iconCursorText from "@assets/svg/cursor-text.svg" with { type: "text" };
import iconDisplay from "@assets/svg/display.svg" with { type: "text" };
import iconEye from "@assets/svg/eye.svg" with { type: "text" };
import iconEyeSlash from "@assets/svg/eye-slash.svg" with { type: "text" };
import iconHome from "@assets/svg/home.svg" with { type: "text" };
import iconNativeMkb from "@assets/svg/native-mkb.svg" with { type: "text" };
import iconNew from "@assets/svg/new.svg" with { type: "text" };
import iconPower from "@assets/svg/power.svg" with { type: "text" };
import iconQuestion from "@assets/svg/question.svg" with { type: "text" };
import iconRefresh from "@assets/svg/refresh.svg" with { type: "text" };
import iconRemotePlay from "@assets/svg/remote-play.svg" with { type: "text" };
import iconSpeakerSlash from "@assets/svg/speaker-slash.svg" with { type: "text" };
import iconStreamSettings from "@assets/svg/stream-settings.svg" with { type: "text" };
import iconStreamStats from "@assets/svg/stream-stats.svg" with { type: "text" };
import iconTouchControlDisable from "@assets/svg/touch-control-disable.svg" with { type: "text" };
@ -37,6 +43,7 @@ import iconUpload from "@assets/svg/upload.svg" with { type: "text" };
export const BxIcon = {
BETTER_XCLOUD: iconBetterXcloud,
TRUE_ACHIEVEMENTS: iconTrueAchievements,
STREAM_SETTINGS: iconStreamSettings,
STREAM_STATS: iconStreamStats,
CLOSE: iconClose,
@ -44,12 +51,15 @@ export const BxIcon = {
CONTROLLER: iconController,
CREATE_SHORTCUT: iconCreateShortcut,
DISPLAY: iconDisplay,
EYE: iconEye,
EYE_SLASH: iconEyeSlash,
HOME: iconHome,
NATIVE_MKB: iconNativeMkb,
NEW: iconNew,
COPY: iconCopy,
TRASH: iconTrash,
CURSOR_TEXT: iconCursorText,
POWER: iconPower,
QUESTION: iconQuestion,
REFRESH: iconRefresh,
VIRTUAL_CONTROLLER: iconVirtualController,
@ -60,6 +70,7 @@ export const BxIcon = {
CARET_LEFT: iconCaretLeft,
CARET_RIGHT: iconCaretRight,
SCREENSHOT: iconCamera,
SPEAKER_MUTED: iconSpeakerSlash,
TOUCH_CONTROL_ENABLE: iconTouchControlEnable,
TOUCH_CONTROL_DISABLE: iconTouchControlDisable,

View File

@ -1,3 +1,5 @@
import { BX_FLAGS } from "./bx-flags";
const enum TextColor {
INFO = '#008746',
WARNING = '#c1a404',
@ -5,22 +7,12 @@ const enum TextColor {
}
export class BxLogger {
static #PREFIX = '[BxC]';
static info = (tag: string, ...args: any[]) => BxLogger.log(TextColor.INFO, tag, ...args);
static warning = (tag: string, ...args: any[]) => BxLogger.log(TextColor.WARNING, tag, ...args);
static error = (tag: string, ...args: any[]) => BxLogger.log(TextColor.ERROR, tag, ...args);
static info(tag: string, ...args: any[]) {
BxLogger.#log(TextColor.INFO, tag, ...args);
}
static warning(tag: string, ...args: any[]) {
BxLogger.#log(TextColor.WARNING, tag, ...args);
}
static error(tag: string, ...args: any[]) {
BxLogger.#log(TextColor.ERROR, tag, ...args);
}
static #log(color: string, tag: string, ...args: any) {
console.log(`%c${BxLogger.#PREFIX}`, `color:${color};font-weight:bold;`, tag, '//', ...args);
private static log(color: string, tag: string, ...args: any) {
BX_FLAGS.Debug && console.log(`%c[BxC]`, `color:${color};font-weight:bold;`, tag, '//', ...args);
}
}

View File

@ -9,11 +9,6 @@ export let FeatureGates: {[key: string]: boolean} = {
'ShowForcedUpdateScreen': false,
};
// Disable context menu in Home page
if (getPref(PrefKey.UI_HOME_CONTEXT_MENU_DISABLED)) {
FeatureGates['EnableHomeContextMenu'] = false;
}
// Disable chat feature
if (getPref(PrefKey.BLOCK_SOCIAL_FEATURES)) {
FeatureGates['EnableGuideChatTab'] = false;

View File

@ -1,4 +1,4 @@
import { EmulatedMkbHandler } from "@modules/mkb/mkb-handler";
import { VIRTUAL_GAMEPAD_ID } from "@modules/mkb/mkb-handler";
import { t } from "@utils/translation";
import { Toast } from "@utils/toast";
import { BxLogger } from "@utils/bx-logger";
@ -8,7 +8,7 @@ import { getPref } from "./settings-storages/global-settings-storage";
// Show a toast when connecting/disconecting controller
export function showGamepadToast(gamepad: Gamepad) {
// Don't show Toast for virtual controller
if (gamepad.id === EmulatedMkbHandler.VIRTUAL_GAMEPAD_ID) {
if (gamepad.id === VIRTUAL_GAMEPAD_ID) {
return;
}
@ -33,3 +33,7 @@ export function showGamepadToast(gamepad: Gamepad) {
Toast.show(text, status, {instant: false});
}
export function updatePollingRate() {
window.BX_CONTROLLER_POLLING_RATE = getPref(PrefKey.CONTROLLER_POLLING_RATE);
}

View File

@ -2,6 +2,7 @@ import type { BaseSettingsStore } from "./settings-storages/base-settings-storag
import { UserAgent } from "./user-agent";
export const SCRIPT_VERSION = Bun.env.SCRIPT_VERSION!;
export const SCRIPT_VARIANT = Bun.env.BUILD_VARIANT! as BuildVariant;
export const AppInterface = window.AppInterface;
@ -12,6 +13,7 @@ const isTv = userAgent.includes('smart-tv') || userAgent.includes('smarttv') ||
const isVr = window.navigator.userAgent.includes('VR') && window.navigator.userAgent.includes('OculusBrowser');
const browserHasTouchSupport = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
const userAgentHasTouchSupport = !isTv && !isVr && browserHasTouchSupport;
const supportMkb = AppInterface || !userAgent.match(/(android|iphone|ipad)/);
export const STATES: BxStates = {
supportedRegion: true,
@ -21,7 +23,6 @@ export const STATES: BxStates = {
isSignedIn: false,
isPlaying: false,
appContext: {},
browser: {
capabilities: {
@ -34,6 +35,7 @@ export const STATES: BxStates = {
isTv: isTv,
capabilities: {
touch: userAgentHasTouchSupport,
mkb: supportMkb,
}
},

View File

@ -1,6 +1,6 @@
import { BxEvent } from "@utils/bx-event";
import { LoadingScreen } from "@modules/loading-screen";
import { RemotePlay } from "@modules/remote-play";
import { RemotePlayManager } from "@/modules/remote-play-manager";
import { HeaderSection } from "@/modules/ui/header";
import { NavigationDialogManager } from "@/modules/ui/dialog/navigation-dialog";
@ -24,7 +24,7 @@ export function onHistoryChanged(e: PopStateEvent) {
return;
}
window.setTimeout(RemotePlay.detect, 10);
window.setTimeout(RemotePlayManager.detect, 10);
// Hide Global settings
const $settings = document.querySelector('.bx-settings-container');
@ -35,9 +35,6 @@ export function onHistoryChanged(e: PopStateEvent) {
// Hide Navigation dialog
NavigationDialogManager.getInstance().hide();
// Hide Remote Play popup
RemotePlay.detachPopup();
LoadingScreen.reset();
window.setTimeout(HeaderSection.watchHeader, 2000);

View File

@ -2,8 +2,38 @@ import type { BxIcon } from "@utils/bx-icon";
import { setNearby } from "./navigation-utils";
import type { NavigationNearbyElements } from "@/modules/ui/dialog/navigation-dialog";
type BxButton = {
style?: number | string | ButtonStyle;
export enum ButtonStyle {
PRIMARY = 1,
DANGER = 2,
GHOST = 4,
FROSTED = 8,
DROP_SHADOW = 16,
FOCUSABLE = 32,
FULL_WIDTH = 64,
FULL_HEIGHT = 128,
TALL = 256,
CIRCULAR = 512,
NORMAL_CASE = 1024,
NORMAL_LINK = 2048,
}
const ButtonStyleClass = {
[ButtonStyle.PRIMARY]: 'bx-primary',
[ButtonStyle.DANGER]: 'bx-danger',
[ButtonStyle.GHOST]: 'bx-ghost',
[ButtonStyle.FROSTED]: 'bx-frosted',
[ButtonStyle.DROP_SHADOW]: 'bx-drop-shadow',
[ButtonStyle.FOCUSABLE]: 'bx-focusable',
[ButtonStyle.FULL_WIDTH]: 'bx-full-width',
[ButtonStyle.FULL_HEIGHT]: 'bx-full-height',
[ButtonStyle.TALL]: 'bx-tall',
[ButtonStyle.CIRCULAR]: 'bx-circular',
[ButtonStyle.NORMAL_CASE]: 'bx-normal-case',
[ButtonStyle.NORMAL_LINK]: 'bx-normal-link',
}
export type BxButton = {
style?: ButtonStyle;
url?: string;
classes?: string[];
icon?: typeof BxIcon;
@ -15,8 +45,6 @@ type BxButton = {
attributes?: {[key: string]: any},
}
type ButtonStyle = {[index: string]: number} & {[index: number]: string};
// Quickly create a tree of elements without having to use innerHTML
type CreateElementOptions = {
[index: string]: any;
@ -28,6 +56,8 @@ function createElement<T=HTMLElement>(elmName: string, props: CreateElementOptio
let $elm;
const hasNs = 'xmlns' in props;
// console.trace('createElement', elmName, props);
if (hasNs) {
$elm = document.createElementNS(props.xmlns, elmName);
delete props.xmlns;
@ -73,42 +103,30 @@ function createElement<T=HTMLElement>(elmName: string, props: CreateElementOptio
export const CE = createElement;
// Credit: https://phosphoricons.com
const svgParser = (svg: string) => new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement;
export const createSvgIcon = (icon: typeof BxIcon) => {
return svgParser(icon.toString());
const domParser = new DOMParser();
export function createSvgIcon(icon: typeof BxIcon) {
return domParser.parseFromString(icon.toString(), 'image/svg+xml').documentElement;
}
export const ButtonStyle: DualEnum = {};
ButtonStyle[ButtonStyle.PRIMARY = 1] = 'bx-primary';
ButtonStyle[ButtonStyle.DANGER = 2] = 'bx-danger';
ButtonStyle[ButtonStyle.GHOST = 4] = 'bx-ghost';
ButtonStyle[ButtonStyle.FROSTED = 8] = 'bx-frosted';
ButtonStyle[ButtonStyle.DROP_SHADOW = 16] = 'bx-drop-shadow';
ButtonStyle[ButtonStyle.FOCUSABLE = 32] = 'bx-focusable';
ButtonStyle[ButtonStyle.FULL_WIDTH = 64] = 'bx-full-width';
ButtonStyle[ButtonStyle.FULL_HEIGHT = 128] = 'bx-full-height';
ButtonStyle[ButtonStyle.TALL = 256] = 'bx-tall';
ButtonStyle[ButtonStyle.CIRCULAR = 512] = 'bx-circular';
ButtonStyle[ButtonStyle.NORMAL_CASE = 1024] = 'bx-normal-case';
const ButtonStyleIndices = Object.keys(ButtonStyleClass).map(i => parseInt(i));
const ButtonStyleIndices = Object.keys(ButtonStyle).splice(0, Object.keys(ButtonStyle).length / 2).map(i => parseInt(i));
export const createButton = <T=HTMLButtonElement>(options: BxButton): T => {
export function createButton<T=HTMLButtonElement>(options: BxButton): T {
let $btn;
if (options.url) {
$btn = CE('a', {'class': 'bx-button'}) as HTMLAnchorElement;
$btn = CE<HTMLAnchorElement>('a', {'class': 'bx-button'});
$btn.href = options.url;
$btn.target = '_blank';
} else {
$btn = CE('button', {'class': 'bx-button', type: 'button'}) as HTMLButtonElement;
$btn = CE<HTMLButtonElement>('button', {'class': 'bx-button', type: 'button'});
}
const style = (options.style || 0) as number;
style && ButtonStyleIndices.forEach(index => {
(style & index) && $btn.classList.add(ButtonStyle[index] as string);
});
if (style) {
let index: keyof typeof ButtonStyleClass;
for (index of ButtonStyleIndices) {
(style & index) && $btn.classList.add(ButtonStyleClass[index] as string);
}
}
options.classes && $btn.classList.add(...options.classes);
@ -148,8 +166,65 @@ export function escapeHtml(html: string): string {
export function isElementVisible($elm: HTMLElement): boolean {
const rect = $elm.getBoundingClientRect();
return !!rect.width && !!rect.height;
return (rect.x >= 0 || rect.y >= 0) && !!rect.width && !!rect.height;
}
export const CTN = document.createTextNode.bind(document);
window.BX_CE = createElement;
export function removeChildElements($parent: HTMLElement) {
while ($parent.firstElementChild) {
$parent.firstElementChild.remove();
}
}
export function clearFocus() {
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
}
export function clearDataSet($elm: HTMLElement) {
Object.keys($elm.dataset).forEach(key => {
delete $elm.dataset[key];
});
}
// https://stackoverflow.com/a/20732091
const FILE_SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
export function humanFileSize(size: number) {
const i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024));
return (size / Math.pow(1024, i)).toFixed(2) + ' ' + FILE_SIZE_UNITS[i];
}
export function secondsToHm(seconds: number) {
let h = Math.floor(seconds / 3600);
let m = Math.floor(seconds % 3600 / 60) + 1;
if (m === 60) {
h += 1;
m = 0;
}
const output = [];
h > 0 && output.push(`${h}h`);
m > 0 && output.push(`${m}m`);
return output.join(' ');
}
export function secondsToHms(seconds: number) {
let h = Math.floor(seconds / 3600);
seconds %= 3600;
let m = Math.floor(seconds / 60);
let s = seconds % 60;
const output = [];
h > 0 && output.push(`${h}h`);
m > 0 && output.push(`${m}m`);
if (s > 0 || output.length === 0) {
output.push(`${s}s`);
}
return output.join(' ');
}

View File

@ -1,165 +0,0 @@
import { MkbPreset } from "@modules/mkb/mkb-preset";
import { t } from "@utils/translation";
import type { MkbStoredPreset, MkbStoredPresets } from "@/types/mkb";
import { PrefKey } from "@/enums/pref-keys";
import { setPref } from "./settings-storages/global-settings-storage";
export class LocalDb {
static #instance: LocalDb;
static get INSTANCE() {
if (!LocalDb.#instance) {
LocalDb.#instance = new LocalDb();
}
return LocalDb.#instance;
}
static readonly DB_NAME = 'BetterXcloud';
static readonly DB_VERSION = 1;
static readonly TABLE_PRESETS = 'mkb_presets';
#DB: any;
#open() {
return new Promise<void>((resolve, reject) => {
if (this.#DB) {
resolve();
return;
}
const request = window.indexedDB.open(LocalDb.DB_NAME, LocalDb.DB_VERSION);
request.onupgradeneeded = (e: IDBVersionChangeEvent) => {
const db = (e.target! as any).result;
switch (e.oldVersion) {
case 0: {
const presets = db.createObjectStore(LocalDb.TABLE_PRESETS, {keyPath: 'id', autoIncrement: true});
presets.createIndex('name_idx', 'name');
break;
}
}
};
request.onerror = e => {
console.log(e);
alert((e.target as any).error.message);
reject && reject();
};
request.onsuccess = e => {
this.#DB = (e.target as any).result;
resolve();
};
});
}
#table(name: string, type: string): Promise<IDBObjectStore> {
const transaction = this.#DB.transaction(name, type || 'readonly');
const table = transaction.objectStore(name);
return new Promise(resolve => resolve(table));
}
// Convert IndexDB method to Promise
#call(method: any) {
const table = arguments[1];
return new Promise(resolve => {
const request = method.call(table, ...Array.from(arguments).slice(2));
request.onsuccess = (e: Event) => {
resolve([table, (e.target as any).result]);
};
});
}
#count(table: IDBObjectStore): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.#call(table.count, ...arguments);
}
#add(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.#call(table.add, ...arguments);
}
#put(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.#call(table.put, ...arguments);
}
#delete(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.#call(table.delete, ...arguments);
}
#get(table: IDBObjectStore, id: number): Promise<any> {
// @ts-ignore
return this.#call(table.get, ...arguments);
}
#getAll(table: IDBObjectStore): Promise<[IDBObjectStore, any]> {
// @ts-ignore
return this.#call(table.getAll, ...arguments);
}
newPreset(name: string, data: any) {
return this.#open()
.then(() => this.#table(LocalDb.TABLE_PRESETS, 'readwrite'))
.then(table => this.#add(table, {name, data}))
.then(([table, id]) => new Promise<number>(resolve => resolve(id)));
}
updatePreset(preset: MkbStoredPreset) {
return this.#open()
.then(() => this.#table(LocalDb.TABLE_PRESETS, 'readwrite'))
.then(table => this.#put(table, preset))
.then(([table, id]) => new Promise(resolve => resolve(id)));
}
deletePreset(id: number) {
return this.#open()
.then(() => this.#table(LocalDb.TABLE_PRESETS, 'readwrite'))
.then(table => this.#delete(table, id))
.then(([table, id]) => new Promise(resolve => resolve(id)));
}
getPreset(id: number): Promise<MkbStoredPreset> {
return this.#open()
.then(() => this.#table(LocalDb.TABLE_PRESETS, 'readwrite'))
.then(table => this.#get(table, id))
.then(([table, preset]) => new Promise(resolve => resolve(preset)));
}
getPresets(): Promise<MkbStoredPresets> {
return this.#open()
.then(() => this.#table(LocalDb.TABLE_PRESETS, 'readwrite'))
.then(table => this.#count(table))
.then(([table, count]) => {
if (count > 0) {
return new Promise(resolve => {
this.#getAll(table)
.then(([table, items]) => {
const presets: MkbStoredPresets = {};
items.forEach((item: MkbStoredPreset) => (presets[item.id!] = item));
resolve(presets);
});
});
}
// Create "Default" preset when the table is empty
const preset: MkbStoredPreset = {
name: t('default'),
data: MkbPreset.DEFAULT_PRESET,
}
return new Promise<MkbStoredPresets>(resolve => {
this.#add(table, preset)
.then(([table, id]) => {
preset.id = id;
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, id);
resolve({[id]: preset});
});
});
});
}
}

View File

@ -0,0 +1,79 @@
export abstract class LocalDb {
static readonly DB_NAME = 'BetterXcloud';
static readonly DB_VERSION = 2;
protected db!: IDBDatabase;
protected open() {
return new Promise<void>((resolve, reject) => {
if (this.db) {
resolve();
return;
}
const request = window.indexedDB.open(LocalDb.DB_NAME, LocalDb.DB_VERSION);
request.onupgradeneeded = this.onUpgradeNeeded.bind(this);
request.onerror = e => {
console.log(e);
alert((e.target as any).error.message);
reject && reject();
};
request.onsuccess = e => {
this.db = (e.target as any).result;
resolve();
};
});
}
protected abstract onUpgradeNeeded(e: IDBVersionChangeEvent): void;
protected table(name: string, type: IDBTransactionMode): Promise<IDBObjectStore> {
const transaction = this.db.transaction(name, type || 'readonly');
const table = transaction.objectStore(name);
return new Promise(resolve => resolve(table));
}
// Convert IndexDB method to Promise
protected call(method: any) {
const table = arguments[1];
return new Promise(resolve => {
const request = method.call(table, ...Array.from(arguments).slice(2));
request.onsuccess = (e: Event) => {
resolve([table, (e.target as any).result]);
};
});
}
protected count(table: IDBObjectStore): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.call(table.count, ...arguments);
}
protected add(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.call(table.add, ...arguments);
}
protected put(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.call(table.put, ...arguments);
}
protected delete(table: IDBObjectStore, data: any): Promise<[IDBObjectStore, number]> {
// @ts-ignore
return this.call(table.delete, ...arguments);
}
protected get(table: IDBObjectStore, id: number): Promise<any> {
// @ts-ignore
return this.call(table.get, ...arguments);
}
protected getAll(table: IDBObjectStore): Promise<[IDBObjectStore, any]> {
// @ts-ignore
return this.call(table.getAll, ...arguments);
}
}

View File

@ -0,0 +1,102 @@
import { PrefKey } from "@/enums/pref-keys";
import { MkbPreset } from "@/modules/mkb/mkb-preset";
import type { MkbStoredPreset, MkbStoredPresets } from "@/types/mkb";
import { setPref } from "../settings-storages/global-settings-storage";
import { t } from "../translation";
import { LocalDb } from "./local-db";
import { BxLogger } from "../bx-logger";
export class MkbPresetsDb extends LocalDb {
private static instance: MkbPresetsDb;
public static getInstance = () => MkbPresetsDb.instance ?? (MkbPresetsDb.instance = new MkbPresetsDb());
private readonly LOG_TAG = 'MkbPresetsDb';
private readonly TABLE_PRESETS = 'mkb_presets';
private constructor() {
super();
BxLogger.info(this.LOG_TAG, 'constructor()');
}
private createTable(db: IDBDatabase) {
const presets = db.createObjectStore(this.TABLE_PRESETS, {
keyPath: 'id',
autoIncrement: true,
});
presets.createIndex('name_idx', 'name');
}
protected onUpgradeNeeded(e: IDBVersionChangeEvent): void {
const db = (e.target! as any).result as IDBDatabase;
if (db.objectStoreNames.contains('undefined')) {
db.deleteObjectStore('undefined');
}
if (!db.objectStoreNames.contains(this.TABLE_PRESETS)) {
this.createTable(db);
}
}
private async presetsTable() {
await this.open();
return await this.table(this.TABLE_PRESETS, 'readwrite');
}
async newPreset(name: string, data: any) {
const table = await this.presetsTable();
const [, id] = await this.add(table, { name, data });
return id;
}
async updatePreset(preset: MkbStoredPreset) {
const table = await this.presetsTable();
const [, id] = await this.put(table, preset);
return id;
}
async deletePreset(id: number) {
const table = await this.presetsTable();
await this.delete(table, id);
return id;
}
async getPreset(id: number): Promise<MkbStoredPreset> {
const table = await this.presetsTable();
const [, preset] = await this.get(table, id);
return preset;
}
async getPresets(): Promise<MkbStoredPresets> {
const table = await this.presetsTable();
const [, count] = await this.count(table);
// Return stored presets
if (count > 0) {
const [, items] = await this.getAll(table);
const presets: MkbStoredPresets = {};
items.forEach((item: MkbStoredPreset) => (presets[item.id!] = item));
return presets;
}
// Create "Default" preset when the table is empty
const preset: MkbStoredPreset = {
name: t('default'),
data: MkbPreset.DEFAULT_PRESET,
};
const [, id] = await this.add(table, preset);
preset.id = id;
setPref(PrefKey.MKB_DEFAULT_PRESET_ID, id);
return {
[id]: preset,
};
}
}

View File

@ -254,6 +254,7 @@ export function patchPointerLockApi() {
});
// const nativeRequestPointerLock = HTMLElement.prototype.requestPointerLock;
// @ts-ignore
HTMLElement.prototype.requestPointerLock = function() {
pointerLockElement = document.documentElement;
window.dispatchEvent(new Event(BxEvent.POINTER_LOCK_REQUESTED));

View File

@ -1,4 +1,5 @@
import { BxEvent } from "@utils/bx-event";
import { isFullVersion } from "@macros/build" with {type: "macro"};
import { BX_FLAGS, NATIVE_FETCH } from "@utils/bx-flags";
import { TouchController } from "@modules/touch-controller";
import { STATES } from "@utils/global";
@ -27,9 +28,7 @@ function clearDbLogs(dbName: string, table: string) {
const objectStore = db.transaction(table, 'readwrite').objectStore(table);
const objectStoreRequest = objectStore.clear();
objectStoreRequest.onsuccess = function() {
console.log(`[Better xCloud] Cleared ${dbName}.${table}`);
};
objectStoreRequest.onsuccess = () => BxLogger.info('clearDbLogs', `Cleared ${dbName}.${table}`);
} catch (ex) {}
}
}
@ -132,6 +131,7 @@ export function interceptHttpRequests() {
'https://browser.events.data.microsoft.com',
'https://dc.services.visualstudio.com',
'https://2c06dea3f26c40c69b8456d319791fd0@o427368.ingest.sentry.io',
'https://mscom.demdex.net',
]);
}
@ -170,29 +170,42 @@ export function interceptHttpRequests() {
};
let gamepassAllGames: string[] = [];
const IGNORED_DOMAINS = [
'accounts.xboxlive.com',
'chat.xboxlive.com',
'notificationinbox.xboxlive.com',
'peoplehub.xboxlive.com',
'rta.xboxlive.com',
'userpresence.xboxlive.com',
'xblmessaging.xboxlive.com',
'consent.config.office.com',
'arc.msn.com',
'browser.events.data.microsoft.com',
'dc.services.visualstudio.com',
'2c06dea3f26c40c69b8456d319791fd0@o427368.ingest.sentry.io',
];
(window as any).BX_FETCH = window.fetch = async (request: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
let url = (typeof request === 'string') ? request : (request as Request).url;
// Check blocked URLs
for (let blocked of BLOCKED_URLS) {
if (!url.startsWith(blocked)) {
continue;
if (url.startsWith(blocked)) {
return new Response('{"acc":1,"webResult":{}}', {
status: 200,
statusText: '200 OK',
});
}
return new Response('{"acc":1,"webResult":{}}', {
status: 200,
statusText: '200 OK',
});
}
if (url.endsWith('/play')) {
BxEvent.dispatch(window, BxEvent.STREAM_LOADING);
// Ignore URLs
const domain = (new URL(url)).hostname;
if (IGNORED_DOMAINS.includes(domain)) {
return NATIVE_FETCH(request, init);
}
if (url.endsWith('/configuration')) {
BxEvent.dispatch(window, BxEvent.STREAM_STARTING);
}
// BxLogger.info('fetch', url);
// Override experimentals
if (url.startsWith('https://emerald.xboxservices.com/xboxcomfd/experimentation')) {
@ -210,6 +223,7 @@ export function interceptHttpRequests() {
return response;
} catch (e) {
console.log(e);
return NATIVE_FETCH(request, init);
}
}
@ -222,7 +236,7 @@ export function interceptHttpRequests() {
for (let i = 1; i < obj.length; i++) {
gamepassAllGames.push(obj[i].id);
}
} else if (url.includes(GamePassCloudGallery.TOUCH)) {
} else if (isFullVersion() && url.includes(GamePassCloudGallery.TOUCH)) {
try {
let customList = TouchController.getCustomList();
@ -262,7 +276,7 @@ export function interceptHttpRequests() {
requestType = 'xcloud';
}
if (requestType === 'xhome') {
if (isFullVersion() && requestType === 'xhome') {
return XhomeInterceptor.handle(request as Request);
}

View File

@ -1,66 +0,0 @@
import { deepClone, STATES } from "@utils/global";
import { BxLogger } from "./bx-logger";
import { TouchController } from "@modules/touch-controller";
import { GamePassCloudGallery } from "../enums/game-pass-gallery";
import { BX_FLAGS } from "./bx-flags";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "./settings-storages/global-settings-storage";
const LOG_TAG = 'PreloadState';
export function overridePreloadState() {
let _state: any;
Object.defineProperty(window, '__PRELOADED_STATE__', {
configurable: true,
get: () => {
return _state;
},
set: state => {
// Override User-Agent
try {
state.appContext.requestInfo.userAgent = window.navigator.userAgent;
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
// Add list of games with custom layouts to the official list
if (STATES.userAgent.capabilities.touch) {
try {
const sigls = state.xcloud.sigls;
if (GamePassCloudGallery.TOUCH in sigls) {
let customList = TouchController.getCustomList();
const allGames = sigls[GamePassCloudGallery.ALL].data.products;
// Remove non-cloud games from the list
customList = customList.filter(id => allGames.includes(id));
// Add to the official list
sigls[GamePassCloudGallery.TOUCH]?.data.products.push(...customList);
}
if (BX_FLAGS.ForceNativeMkbTitles && GamePassCloudGallery.NATIVE_MKB in sigls) {
// Add to the official list
sigls[GamePassCloudGallery.NATIVE_MKB]?.data.products.push(...BX_FLAGS.ForceNativeMkbTitles);
}
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
}
if (getPref(PrefKey.UI_HOME_CONTEXT_MENU_DISABLED)) {
try {
state.experiments.experimentationInfo.data.treatments.EnableHomeContextMenu = false;
} catch (e) {
BxLogger.error(LOG_TAG, e);
}
}
// @ts-ignore
_state = state;
STATES.appContext = deepClone(state.appContext);
}
});
}

View File

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

View File

@ -0,0 +1,105 @@
import { StreamPlayerType } from "@enums/stream-player";
import { AppInterface, STATES } from "./global";
import { CE } from "./html";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "./settings-storages/global-settings-storage";
import { BxLogger } from "./bx-logger";
export class ScreenshotManager {
private static instance: ScreenshotManager;
public static getInstance = () => ScreenshotManager.instance ?? (ScreenshotManager.instance = new ScreenshotManager());
private readonly LOG_TAG = 'ScreenshotManager';
private $download: HTMLAnchorElement;
private $canvas: HTMLCanvasElement;
private canvasContext: CanvasRenderingContext2D;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.$download = CE<HTMLAnchorElement>('a');
this.$canvas = CE<HTMLCanvasElement>('canvas', {'class': 'bx-gone'});
this.canvasContext = this.$canvas.getContext('2d', {
alpha: false,
willReadFrequently: false,
})!;
}
updateCanvasSize(width: number, height: number) {
this.$canvas.width = width;
this.$canvas.height = height;
}
updateCanvasFilters(filters: string) {
this.canvasContext.filter = filters;
}
private onAnimationEnd(e: Event) {
(e.target as HTMLElement).classList.remove('bx-taking-screenshot');
}
takeScreenshot(callback?: any) {
const currentStream = STATES.currentStream;
const streamPlayer = currentStream.streamPlayer;
const $canvas = this.$canvas;
if (!streamPlayer || !$canvas) {
return;
}
let $player;
if (getPref(PrefKey.SCREENSHOT_APPLY_FILTERS)) {
$player = streamPlayer.getPlayerElement();
} else {
$player = streamPlayer.getPlayerElement(StreamPlayerType.VIDEO);
}
if (!$player || !$player.isConnected) {
return;
}
$player.parentElement!.addEventListener('animationend', this.onAnimationEnd, { once: true });
$player.parentElement!.classList.add('bx-taking-screenshot');
const canvasContext = this.canvasContext;
if ($player instanceof HTMLCanvasElement) {
streamPlayer.getWebGL2Player().forceDrawFrame();
}
canvasContext.drawImage($player, 0, 0, $canvas.width, $canvas.height);
// Get data URL and pass to parent app
if (AppInterface) {
const data = $canvas.toDataURL('image/png').split(';base64,')[1];
AppInterface.saveScreenshot(currentStream.titleSlug, data);
// Free screenshot from memory
canvasContext.clearRect(0, 0, $canvas.width, $canvas.height);
callback && callback();
return;
}
$canvas.toBlob(blob => {
if (!blob) {
return;
}
// Download screenshot
const now = +new Date;
const $download = this.$download;
$download.download = `${currentStream.titleSlug}-${now}.png`;
$download.href = URL.createObjectURL(blob);
$download.click();
// Free screenshot from memory
URL.revokeObjectURL($download.href);
$download.href = '';
$download.download = '';
canvasContext.clearRect(0, 0, $canvas.width, $canvas.height);
callback && callback();
}, 'image/png');
}
}

View File

@ -1,99 +0,0 @@
import { StreamPlayerType } from "@enums/stream-player";
import { AppInterface, STATES } from "./global";
import { CE } from "./html";
import { PrefKey } from "@/enums/pref-keys";
import { getPref } from "./settings-storages/global-settings-storage";
export class Screenshot {
static #$canvas: HTMLCanvasElement;
static #canvasContext: CanvasRenderingContext2D;
static setup() {
if (Screenshot.#$canvas) {
return;
}
Screenshot.#$canvas = CE<HTMLCanvasElement>('canvas', {'class': 'bx-gone'});
Screenshot.#canvasContext = Screenshot.#$canvas.getContext('2d', {
alpha: false,
willReadFrequently: false,
})!;
}
static updateCanvasSize(width: number, height: number) {
const $canvas = Screenshot.#$canvas;
if ($canvas) {
$canvas.width = width;
$canvas.height = height;
}
}
static updateCanvasFilters(filters: string) {
Screenshot.#canvasContext.filter = filters;
}
static #onAnimationEnd(e: Event) {
const $target = e.target as HTMLElement;
$target.classList.remove('bx-taking-screenshot');
}
static takeScreenshot(callback?: any) {
const currentStream = STATES.currentStream;
const streamPlayer = currentStream.streamPlayer;
const $canvas = Screenshot.#$canvas;
if (!streamPlayer || !$canvas) {
return;
}
let $player;
if (getPref(PrefKey.SCREENSHOT_APPLY_FILTERS)) {
$player = streamPlayer.getPlayerElement();
} else {
$player = streamPlayer.getPlayerElement(StreamPlayerType.VIDEO);
}
if (!$player || !$player.isConnected) {
return;
}
$player.parentElement!.addEventListener('animationend', this.#onAnimationEnd, { once: true });
$player.parentElement!.classList.add('bx-taking-screenshot');
const canvasContext = Screenshot.#canvasContext;
if ($player instanceof HTMLCanvasElement) {
streamPlayer.getWebGL2Player().drawFrame();
}
canvasContext.drawImage($player, 0, 0, $canvas.width, $canvas.height);
// Get data URL and pass to parent app
if (AppInterface) {
const data = $canvas.toDataURL('image/png').split(';base64,')[1];
AppInterface.saveScreenshot(currentStream.titleId, data);
// Free screenshot from memory
canvasContext.clearRect(0, 0, $canvas.width, $canvas.height);
callback && callback();
return;
}
$canvas && $canvas.toBlob(blob => {
// Download screenshot
const now = +new Date;
const $anchor = CE<HTMLAnchorElement>('a', {
'download': `${currentStream.titleId}-${now}.png`,
'href': URL.createObjectURL(blob!),
});
$anchor.click();
// Free screenshot from memory
URL.revokeObjectURL($anchor.href);
canvasContext.clearRect(0, 0, $canvas.width, $canvas.height);
callback && callback();
}, 'image/png');
}
}

View File

@ -4,6 +4,7 @@ import { setNearby } from "./navigation-utils";
import type { PrefKey } from "@/enums/pref-keys";
import type { BaseSettingsStore } from "./settings-storages/base-settings-storage";
import { type MultipleOptionsParams, type NumberStepperParams } from "@/types/setting-definition";
import { BxEvent } from "./bx-event";
export enum SettingElementType {
OPTIONS = 'options',
@ -13,16 +14,26 @@ export enum SettingElementType {
CHECKBOX = 'checkbox',
}
interface BxBaseSettingElement {
setValue: (value: any) => void,
}
export interface BxHtmlSettingElement extends HTMLElement, BxBaseSettingElement {};
export interface BxSelectSettingElement extends HTMLSelectElement, BxBaseSettingElement {}
export class SettingElement {
static #renderOptions(key: string, setting: PreferenceSetting, currentValue: any, onChange: any) {
const $control = CE<HTMLSelectElement>('select', {
// title: setting.label,
tabindex: 0,
}) as HTMLSelectElement;
static #renderOptions(key: string, setting: PreferenceSetting, currentValue: any, onChange: any): BxSelectSettingElement {
const $control = CE<BxSelectSettingElement>('select', {
// title: setting.label,
tabindex: 0,
});
let $parent: HTMLElement;
if (setting.optionsGroup) {
$parent = CE('optgroup', {'label': setting.optionsGroup});
$parent = CE('optgroup', {
label: setting.optionsGroup,
});
$control.appendChild($parent);
} else {
$parent = $control;
@ -44,19 +55,20 @@ export class SettingElement {
});
// Custom method
($control as any).setValue = (value: any) => {
$control.setValue = (value: any) => {
$control.value = value;
};
return $control;
}
static #renderMultipleOptions(key: string, setting: PreferenceSetting, currentValue: any, onChange: any, params: MultipleOptionsParams={}) {
const $control = CE<HTMLSelectElement>('select', {
// title: setting.label,
multiple: true,
tabindex: 0,
});
static #renderMultipleOptions(key: string, setting: PreferenceSetting, currentValue: any, onChange: any, params: MultipleOptionsParams={}): BxSelectSettingElement {
const $control = CE<BxSelectSettingElement>('select', {
// title: setting.label,
multiple: true,
tabindex: 0,
});
if (params && params.size) {
$control.setAttribute('size', params.size.toString());
}
@ -75,7 +87,7 @@ export class SettingElement {
const $parent = target.parentElement!;
$parent.focus();
$parent.dispatchEvent(new Event('input'));
BxEvent.dispatch($parent, 'input');
});
$control.appendChild($option);
@ -100,9 +112,15 @@ export class SettingElement {
}
static #renderNumber(key: string, setting: PreferenceSetting, currentValue: any, onChange: any) {
const $control = CE('input', {'tabindex': 0, 'type': 'number', 'min': setting.min, 'max': setting.max}) as HTMLInputElement;
const $control = CE<HTMLInputElement>('input', {
tabindex: 0,
type: 'number',
min: setting.min,
max: setting.max,
});
$control.value = currentValue;
onChange && $control.addEventListener('change', (e: Event) => {
onChange && $control.addEventListener('input', (e: Event) => {
const target = e.target as HTMLInputElement;
const value = Math.max(setting.min!, Math.min(setting.max!, parseInt(target.value)));
@ -118,10 +136,14 @@ export class SettingElement {
const $control = CE('input', {'type': 'checkbox', 'tabindex': 0}) as HTMLInputElement;
$control.checked = currentValue;
onChange && $control.addEventListener('change', e => {
onChange && $control.addEventListener('input', e => {
!(e as any).ignoreOnChange && onChange(e, (e.target as HTMLInputElement).checked);
});
($control as any).setValue = (value: boolean) => {
$control.checked = !!value;
};
return $control;
}
@ -138,10 +160,18 @@ export class SettingElement {
let controlValue = value;
const MIN = setting.min!;
const MAX = setting.max!;
const MIN = options.reverse ? -setting.max! : setting.min!;
const MAX = options.reverse ? -setting.min! : setting.max!;
const STEPS = Math.max(setting.steps || 1, 1);
let intervalId: number | null;
let isHolding = false;
const clearIntervalId = () => {
intervalId && clearInterval(intervalId);
intervalId = null;
}
const renderTextValue = (value: any) => {
value = parseInt(value as string);
@ -160,103 +190,102 @@ export class SettingElement {
const updateButtonsVisibility = () => {
$btnDec.classList.toggle('bx-inactive', controlValue === MIN);
$btnInc.classList.toggle('bx-inactive', controlValue === MAX);
}
const $wrapper = CE('div', {'class': 'bx-number-stepper', id: `bx_setting_${key}`},
$btnDec = CE('button', {
'data-type': 'dec',
type: 'button',
class: options.hideSlider ? 'bx-focusable' : '',
tabindex: options.hideSlider ? 0 : -1,
}, '-') as HTMLButtonElement,
$text = CE('span', {}, renderTextValue(value)) as HTMLSpanElement,
$btnInc = CE('button', {
'data-type': 'inc',
type: 'button',
class: options.hideSlider ? 'bx-focusable' : '',
tabindex: options.hideSlider ? 0 : -1,
}, '+') as HTMLButtonElement,
);
if (options.disabled) {
($wrapper as any).disabled = true;
}
if (!options.disabled && !options.hideSlider) {
$range = CE('input', {
id: `bx_setting_${key}`,
type: 'range',
min: MIN,
max: MAX,
value: value,
step: STEPS,
tabindex: 0,
}) as HTMLInputElement;
$range.addEventListener('input', e => {
value = parseInt((e.target as HTMLInputElement).value);
const valueChanged = controlValue !== value;
if (!valueChanged) {
return;
}
controlValue = value;
updateButtonsVisibility();
$text.textContent = renderTextValue(value);
!(e as any).ignoreOnChange && onChange && onChange(e, value);
});
$wrapper.appendChild($range);
if (options.ticks || options.exactTicks) {
const markersId = `markers-${key}`;
const $markers = CE('datalist', {'id': markersId});
$range.setAttribute('list', markersId);
if (options.exactTicks) {
let start = Math.max(Math.floor(MIN / options.exactTicks), 1) * options.exactTicks;
if (start === MIN) {
start += options.exactTicks;
}
for (let i = start; i < MAX; i += options.exactTicks) {
$markers.appendChild(CE<HTMLOptionElement>('option', {'value': i}));
}
} else {
for (let i = MIN + options.ticks!; i < MAX; i += options.ticks!) {
$markers.appendChild(CE<HTMLOptionElement>('option', {'value': i}));
}
}
$wrapper.appendChild($markers);
if (controlValue === MIN || controlValue === MAX) {
clearIntervalId();
}
}
const $wrapper = CE<BxHtmlSettingElement>('div', {'class': 'bx-number-stepper', id: `bx_setting_${key}`},
$btnDec = CE('button', {
'data-type': 'dec',
type: 'button',
class: options.hideSlider ? 'bx-focusable' : '',
tabindex: options.hideSlider ? 0 : -1,
}, '-') as HTMLButtonElement,
$text = CE('span', {}, renderTextValue(value)) as HTMLSpanElement,
$btnInc = CE('button', {
'data-type': 'inc',
type: 'button',
class: options.hideSlider ? 'bx-focusable' : '',
tabindex: options.hideSlider ? 0 : -1,
}, '+') as HTMLButtonElement,
);
if (options.disabled) {
$btnInc.disabled = true;
$btnInc.classList.add('bx-inactive');
$btnDec.disabled = true;
$btnDec.classList.add('bx-inactive');
($wrapper as any).disabled = true;
return $wrapper;
}
$range = CE<HTMLInputElement>('input', {
id: `bx_inp_setting_${key}`,
type: 'range',
min: MIN,
max: MAX,
value: options.reverse ? -value : value,
step: STEPS,
tabindex: 0,
});
options.hideSlider && $range.classList.add('bx-gone');
$range.addEventListener('input', e => {
value = parseInt((e.target as HTMLInputElement).value);
if (options.reverse) {
value *= -1;
}
const valueChanged = controlValue !== value;
if (!valueChanged) {
return;
}
controlValue = options.reverse ? -value : value;
updateButtonsVisibility();
$text.textContent = renderTextValue(value);
!(e as any).ignoreOnChange && onChange && onChange(e, value);
});
$wrapper.addEventListener('input', e => {
BxEvent.dispatch($range, 'input');
});
$wrapper.appendChild($range);
if (options.ticks || options.exactTicks) {
const markersId = `markers-${key}`;
const $markers = CE('datalist', {id: markersId});
$range.setAttribute('list', markersId);
if (options.exactTicks) {
let start = Math.max(Math.floor(setting.min! / options.exactTicks), 1) * options.exactTicks;
if (start === setting.min!) {
start += options.exactTicks;
}
for (let i = start; i < setting.max!; i += options.exactTicks) {
$markers.appendChild(CE<HTMLOptionElement>('option', {
value: options.reverse ? -i : i,
}));
}
} else {
for (let i = MIN + options.ticks!; i < MAX; i += options.ticks!) {
$markers.appendChild(CE<HTMLOptionElement>('option', {value: i}));
}
}
$wrapper.appendChild($markers);
}
updateButtonsVisibility();
let interval: number;
let isHolding = false;
const onClick = (e: Event) => {
if (isHolding) {
e.preventDefault();
isHolding = false;
return;
}
const $btn = e.target as HTMLElement;
const buttonPressed = (e: Event, $btn: HTMLElement) => {
let value = parseInt(controlValue);
const btnType = $btn.dataset.type;
@ -272,54 +301,59 @@ export class SettingElement {
$text.textContent = renderTextValue(value);
$range && ($range.value = value.toString());
isHolding = false;
!(e as any).ignoreOnChange && onChange && onChange(e, value);
}
const onMouseDown = (e: PointerEvent) => {
e.preventDefault();
isHolding = true;
const args = arguments;
interval && clearInterval(interval);
interval = window.setInterval(() => {
const event = new Event('click');
(event as any).arguments = args;
e.target?.dispatchEvent(event);
}, 200);
onChange && onChange(e, value);
};
const onMouseUp = (e: PointerEvent) => {
const onClick = (e: Event) => {
e.preventDefault();
if (isHolding) {
return;
}
const $btn = (e.target as HTMLElement).closest('button') as HTMLElement;
$btn && buttonPressed(e, $btn);
clearIntervalId();
isHolding = false;
};
const onPointerDown = (e: PointerEvent) => {
clearIntervalId();
const $btn = (e.target as HTMLElement).closest('button') as HTMLElement;
if (!$btn) {
return;
}
isHolding = true;
e.preventDefault();
interval && clearInterval(interval);
intervalId = window.setInterval((e: Event) => {
buttonPressed(e, $btn);
}, 200);
window.addEventListener('pointerup', onPointerUp, {once: true});
window.addEventListener('pointercancel', onPointerUp, {once: true});
};
const onPointerUp = (e: PointerEvent) => {
clearIntervalId();
isHolding = false;
};
const onContextMenu = (e: Event) => e.preventDefault();
// Custom method
($wrapper as any).setValue = (value: any) => {
controlValue = parseInt(value);
$wrapper.setValue = (value: any) => {
$text.textContent = renderTextValue(value);
$range && ($range.value = value);
$range.value = options.reverse ? -value : value;
};
$btnDec.addEventListener('click', onClick);
$btnDec.addEventListener('pointerdown', onMouseDown);
$btnDec.addEventListener('pointerup', onMouseUp);
$btnDec.addEventListener('contextmenu', onContextMenu);
$btnInc.addEventListener('click', onClick);
$btnInc.addEventListener('pointerdown', onMouseDown);
$btnInc.addEventListener('pointerup', onMouseUp);
$btnInc.addEventListener('contextmenu', onContextMenu);
$wrapper.addEventListener('click', onClick);
$wrapper.addEventListener('pointerdown', onPointerDown);
$wrapper.addEventListener('contextmenu', onContextMenu);
setNearby($wrapper, {
focus: $range || $btnInc,
focus: options.hideSlider ? $btnInc : $range,
})
return $wrapper;

View File

@ -1,6 +1,9 @@
import type { PrefKey } from "@/enums/pref-keys";
import type { SettingDefinitions } from "@/types/setting-definition";
import type { NumberStepperParams, SettingDefinitions } from "@/types/setting-definition";
import { BxEvent } from "../bx-event";
import { SettingElementType } from "../setting-element";
import { t } from "../translation";
import { SCRIPT_VARIANT } from "../global";
export class BaseSettingsStore {
private storage: Storage;
@ -12,9 +15,15 @@ export class BaseSettingsStore {
this.storage = window.localStorage;
this.storageKey = storageKey;
for (const settingId in definitions) {
let settingId: keyof typeof definitions
for (settingId in definitions) {
const setting = definitions[settingId];
// Convert requiredVariants to array
if (typeof setting.requiredVariants === 'string') {
setting.requiredVariants = [setting.requiredVariants];
}
/*
if (setting.migrate && settingId in savedPrefs) {
setting.migrate.call(this, savedPrefs, savedPrefs[settingId]);
@ -49,15 +58,22 @@ export class BaseSettingsStore {
return this.definitions[key];
}
getSetting(key: PrefKey) {
getSetting(key: PrefKey, checkUnsupported = true) {
if (typeof key === 'undefined') {
debugger;
return;
}
const definition = this.definitions[key];
// Return default value if build variant is different
if (definition.requiredVariants && !definition.requiredVariants.includes(SCRIPT_VARIANT)) {
return definition.default;
}
// Return default value if the feature is not supported
if (this.definitions[key].unsupported) {
return this.definitions[key].default;
if (checkUnsupported && definition.unsupported) {
return definition.default;
}
if (!(key in this.settings)) {
@ -121,4 +137,32 @@ export class BaseSettingsStore {
return value;
}
getLabel(key: PrefKey): string {
return this.definitions[key].label || key;
}
getValueText(key: PrefKey, value: any): string {
const definition = this.definitions[key];
if (definition.type === SettingElementType.NUMBER_STEPPER) {
const params = (definition as any).params as NumberStepperParams;
if (params.customTextValue) {
const text = params.customTextValue(value);
if (text) {
return text;
}
}
return value.toString();
} else if ('options' in definition) {
const options = (definition as any).options;
if (value in options) {
return options[value];
}
} else if (typeof value === 'boolean') {
return value ? t('on') : t('off')
}
return value.toString();
}
}

View File

@ -3,9 +3,7 @@ import { PrefKey, StorageKey } from "@/enums/pref-keys";
import { StreamPlayerType, StreamVideoProcessing } from "@/enums/stream-player";
import { UiSection } from "@/enums/ui-sections";
import { UserAgentProfile } from "@/enums/user-agent";
import { StreamStat } from "@/modules/stream/stream-stats";
import type { PreferenceSetting } from "@/types/preferences";
import { type SettingDefinitions } from "@/types/setting-definition";
import { type SettingDefinition, type SettingDefinitions } from "@/types/setting-definition";
import { BX_FLAGS } from "../bx-flags";
import { STATES, AppInterface, STORAGE } from "../global";
import { CE } from "../html";
@ -13,10 +11,40 @@ import { t, SUPPORTED_LANGUAGES } from "../translation";
import { UserAgent } from "../user-agent";
import { BaseSettingsStore as BaseSettingsStorage } from "./base-settings-storage";
import { SettingElementType } from "../setting-element";
import { StreamStat } from "../stream-stats-collector";
export const enum StreamResolution {
DIM_720P = '720p',
DIM_1080P = '1080p',
}
export const enum CodecProfile {
DEFAULT = 'default',
LOW = 'low',
NORMAL = 'normal',
HIGH = 'high',
};
export const enum StreamTouchController {
DEFAULT = 'default',
ALL = 'all',
OFF = 'off',
}
export const enum ControllerDeviceVibration {
ON = 'on',
AUTO = 'auto',
OFF = 'off',
}
export type GameBarPosition = 'bottom-left' | 'bottom-right' | 'off';
export type GameBarPositionOptions = Record<GameBarPosition, string>;
function getSupportedCodecProfiles() {
const options: {[index: string]: string} = {
const options: PartialRecord<CodecProfile, string> = {
default: t('default'),
};
@ -46,25 +74,25 @@ function getSupportedCodecProfiles() {
if (hasLowCodec) {
if (!hasNormalCodec && !hasHighCodec) {
options.default = `${t('visual-quality-low')} (${t('default')})`;
options[CodecProfile.DEFAULT] = `${t('visual-quality-low')} (${t('default')})`;
} else {
options.low = t('visual-quality-low');
options[CodecProfile.LOW] = t('visual-quality-low');
}
}
if (hasNormalCodec) {
if (!hasLowCodec && !hasHighCodec) {
options.default = `${t('visual-quality-normal')} (${t('default')})`;
options[CodecProfile.DEFAULT] = `${t('visual-quality-normal')} (${t('default')})`;
} else {
options.normal = t('visual-quality-normal');
options[CodecProfile.NORMAL] = t('visual-quality-normal');
}
}
if (hasHighCodec) {
if (!hasLowCodec && !hasNormalCodec) {
options.default = `${t('visual-quality-high')} (${t('default')})`;
options[CodecProfile.DEFAULT] = `${t('visual-quality-high')} (${t('default')})`;
} else {
options.high = t('visual-quality-high');
options[CodecProfile.HIGH] = t('visual-quality-high');
}
}
@ -72,7 +100,7 @@ function getSupportedCodecProfiles() {
}
export class GlobalSettingsStorage extends BaseSettingsStorage {
private static readonly DEFINITIONS: SettingDefinitions = {
private static readonly DEFINITIONS = {
[PrefKey.LAST_UPDATE_CHECK]: {
default: 0,
},
@ -89,6 +117,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.SERVER_REGION]: {
label: t('region'),
note: CE('a', {target: '_blank', href: 'https://umap.openstreetmap.fr/en/map/xbox-cloud-gaming-servers_1135022'}, t('server-locations')),
default: 'default',
},
[PrefKey.SERVER_BYPASS_RESTRICTION]: {
@ -107,12 +136,13 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
options: {
default: t('default'),
'ar-SA': 'العربية',
'bg-BG': 'Български',
'cs-CZ': 'čeština',
'da-DK': 'dansk',
'de-DE': 'Deutsch',
'el-GR': 'Ελληνικά',
'en-GB': 'English (United Kingdom)',
'en-US': 'English (United States)',
'en-GB': 'English (UK)',
'en-US': 'English (US)',
'es-ES': 'español (España)',
'es-MX': 'español (Latinoamérica)',
'fi-FI': 'suomi',
@ -127,9 +157,11 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
'pl-PL': 'polski',
'pt-BR': 'português (Brasil)',
'pt-PT': 'português (Portugal)',
'ro-RO': 'Română',
'ru-RU': 'русский',
'sk-SK': 'slovenčina',
'sv-SE': 'svenska',
'th-TH': 'ไทย',
'tr-TR': 'Türkçe',
'zh-CN': '中文(简体)',
'zh-TW': '中文 (繁體)',
@ -140,25 +172,31 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
default: 'auto',
options: {
auto: t('default'),
'720p': '720p',
'1080p': '1080p',
[StreamResolution.DIM_720P]: '720p',
[StreamResolution.DIM_1080P]: '1080p',
},
suggest: {
lowest: StreamResolution.DIM_720P,
highest: StreamResolution.DIM_1080P,
},
},
[PrefKey.STREAM_CODEC_PROFILE]: {
label: t('visual-quality'),
default: 'default',
options: getSupportedCodecProfiles(),
ready: (setting: PreferenceSetting) => {
const options: any = setting.options;
ready: (setting: SettingDefinition) => {
const options = (setting as any).options;
const keys = Object.keys(options);
if (keys.length <= 1) { // Unsupported
setting.unsupported = true;
setting.note = '⚠️ ' + t('browser-unsupported-feature');
} else {
// Set default value to the best codec profile
// setting.default = keys[keys.length - 1];
setting.unsupportedNote = '⚠️ ' + t('browser-unsupported-feature');
}
setting.suggest = {
lowest: keys.length === 1 ? keys[0] : keys[1],
highest: keys[keys.length - 1],
};
},
},
[PrefKey.PREFER_IPV6_SERVER]: {
@ -167,6 +205,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.SCREENSHOT_APPLY_FILTERS]: {
requiredVariants: 'full',
label: t('screenshot-apply-filters'),
default: false,
},
@ -181,6 +220,8 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.STREAM_COMBINE_SOURCES]: {
requiredVariants: 'full',
label: t('combine-audio-video-streams'),
default: false,
experimental: true,
@ -188,26 +229,29 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.STREAM_TOUCH_CONTROLLER]: {
requiredVariants: 'full',
label: t('tc-availability'),
default: 'all',
default: StreamTouchController.ALL,
options: {
default: t('default'),
all: t('tc-all-games'),
off: t('off'),
[StreamTouchController.DEFAULT]: t('default'),
[StreamTouchController.ALL]: t('tc-all-games'),
[StreamTouchController.OFF]: t('off'),
},
unsupported: !STATES.userAgent.capabilities.touch,
ready: (setting: PreferenceSetting) => {
ready: (setting: SettingDefinition) => {
if (setting.unsupported) {
setting.default = 'default';
setting.default = StreamTouchController.DEFAULT;
}
},
},
[PrefKey.STREAM_TOUCH_CONTROLLER_AUTO_OFF]: {
requiredVariants: 'full',
label: t('tc-auto-off'),
default: false,
unsupported: !STATES.userAgent.capabilities.touch,
},
[PrefKey.STREAM_TOUCH_CONTROLLER_DEFAULT_OPACITY]: {
requiredVariants: 'full',
type: SettingElementType.NUMBER_STEPPER,
label: t('tc-default-opacity'),
default: 100,
@ -222,6 +266,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
unsupported: !STATES.userAgent.capabilities.touch,
},
[PrefKey.STREAM_TOUCH_CONTROLLER_STYLE_STANDARD]: {
requiredVariants: 'full',
label: t('tc-standard-layout-style'),
default: 'default',
options: {
@ -232,6 +277,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
unsupported: !STATES.userAgent.capabilities.touch,
},
[PrefKey.STREAM_TOUCH_CONTROLLER_STYLE_CUSTOM]: {
requiredVariants: 'full',
label: t('tc-custom-layout-style'),
default: 'default',
options: {
@ -246,15 +292,18 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
default: false,
},
[PrefKey.MKB_HIDE_IDLE_CURSOR]: {
requiredVariants: 'full',
label: t('hide-idle-cursor'),
default: false,
},
[PrefKey.STREAM_DISABLE_FEEDBACK_DIALOG]: {
requiredVariants: 'full',
label: t('disable-post-stream-feedback-dialog'),
default: false,
},
[PrefKey.BITRATE_VIDEO_MAX]: {
requiredVariants: 'full',
type: SettingElementType.NUMBER_STEPPER,
label: t('bitrate-video-maximum'),
note: '⚠️ ' + t('unexpected-behavior'),
@ -274,25 +323,30 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
}
},
},
suggest: {
highest: 0,
},
},
[PrefKey.GAME_BAR_POSITION]: {
requiredVariants: 'full',
label: t('position'),
default: 'bottom-left',
default: 'bottom-left' satisfies GameBarPosition,
options: {
'bottom-left': t('bottom-left'),
'bottom-right': t('bottom-right'),
'off': t('off'),
},
} satisfies GameBarPositionOptions,
},
[PrefKey.LOCAL_CO_OP_ENABLED]: {
requiredVariants: 'full',
label: t('enable-local-co-op-support'),
default: false,
note: CE<HTMLAnchorElement>('a', {
href: 'https://github.com/redphx/better-xcloud/discussions/275',
target: '_blank',
}, t('enable-local-co-op-support-note')),
note: () => CE<HTMLAnchorElement>('a', {
href: 'https://github.com/redphx/better-xcloud/discussions/275',
target: '_blank',
}, t('enable-local-co-op-support-note')),
},
/*
@ -307,26 +361,25 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
default: true,
},
[PrefKey.CONTROLLER_ENABLE_SHORTCUTS]: {
default: false,
},
[PrefKey.CONTROLLER_ENABLE_VIBRATION]: {
requiredVariants: 'full',
label: t('controller-vibration'),
default: true,
},
[PrefKey.CONTROLLER_DEVICE_VIBRATION]: {
requiredVariants: 'full',
label: t('device-vibration'),
default: 'off',
default: ControllerDeviceVibration.OFF,
options: {
on: t('on'),
auto: t('device-vibration-not-using-gamepad'),
off: t('off'),
[ControllerDeviceVibration.ON]: t('on'),
[ControllerDeviceVibration.AUTO]: t('device-vibration-not-using-gamepad'),
[ControllerDeviceVibration.OFF]: t('off'),
},
},
[PrefKey.CONTROLLER_VIBRATION_INTENSITY]: {
requiredVariants: 'full',
label: t('vibration-intensity'),
type: SettingElementType.NUMBER_STEPPER,
default: 100,
@ -339,14 +392,36 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
},
[PrefKey.CONTROLLER_POLLING_RATE]: {
requiredVariants: 'full',
label: t('polling-rate'),
type: SettingElementType.NUMBER_STEPPER,
default: 4,
min: 4,
max: 60,
steps: 4,
params: {
exactTicks: 20,
reverse: true,
customTextValue(value: any) {
value = parseInt(value);
let text = +(1000 / value).toFixed(2) + ' Hz';
if (value === 4) {
text = `${text} (${t('default')})`;
}
return text;
},
},
},
[PrefKey.MKB_ENABLED]: {
requiredVariants: 'full',
label: t('enable-mkb'),
default: false,
unsupported: ((): string | boolean => {
const userAgent = ((window.navigator as any).orgUserAgent || window.navigator.userAgent || '').toLowerCase();
return !AppInterface && userAgent.match(/(android|iphone|ipad)/) ? t('browser-unsupported-feature') : false;
})(),
ready: (setting: PreferenceSetting) => {
unsupported: !STATES.userAgent.capabilities.mkb,
ready: (setting: SettingDefinition) => {
let note;
let url;
if (setting.unsupported) {
@ -357,14 +432,15 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
url = 'https://better-xcloud.github.io/mouse-and-keyboard/#disclaimer';
}
setting.note = CE('a', {
href: url,
target: '_blank',
}, '⚠️ ' + note);
setting.unsupportedNote = () => CE<HTMLAnchorElement>('a', {
href: url,
target: '_blank',
}, '⚠️ ' + note);
},
},
[PrefKey.NATIVE_MKB_ENABLED]: {
requiredVariants: 'full',
label: t('native-mkb'),
default: 'default',
options: {
@ -372,21 +448,21 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
on: t('on'),
off: t('off'),
},
ready: (setting: PreferenceSetting) => {
ready: (setting: SettingDefinition) => {
if (AppInterface) {
} else if (UserAgent.isMobile()) {
setting.unsupported = true;
setting.default = 'off';
delete setting.options!['default'];
delete setting.options!['on'];
delete (setting as any).options['default'];
delete (setting as any).options['on'];
} else {
delete setting.options!['on'];
delete (setting as any).options['on'];
}
},
},
[PrefKey.NATIVE_MKB_SCROLL_HORIZONTAL_SENSITIVITY]: {
requiredVariants: 'full',
label: t('horizontal-scroll-sensitivity'),
type: SettingElementType.NUMBER_STEPPER,
default: 0,
@ -406,6 +482,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.NATIVE_MKB_SCROLL_VERTICAL_SENSITIVITY]: {
requiredVariants: 'full',
label: t('vertical-scroll-sensitivity'),
type: SettingElementType.NUMBER_STEPPER,
default: 0,
@ -425,10 +502,12 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.MKB_DEFAULT_PRESET_ID]: {
requiredVariants: 'full',
default: 0,
},
[PrefKey.MKB_ABSOLUTE_MOUSE]: {
requiredVariants: 'full',
default: false,
},
@ -438,6 +517,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.UI_LOADING_SCREEN_GAME_ART]: {
requiredVariants: 'full',
label: t('show-game-art'),
default: true,
},
@ -461,6 +541,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.UI_LAYOUT]: {
requiredVariants: 'full',
label: t('layout'),
default: 'default',
options: {
@ -475,12 +556,8 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
default: false,
},
[PrefKey.UI_HOME_CONTEXT_MENU_DISABLED]: {
label: t('disable-home-context-menu'),
default: STATES.browser.capabilities.touch,
},
[PrefKey.UI_HIDE_SECTIONS]: {
requiredVariants: 'full',
label: t('hide-sections'),
default: [],
multipleOptions: {
@ -497,6 +574,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.UI_GAME_CARD_SHOW_WAIT_TIME]: {
requiredVariants: 'full',
label: t('show-wait-time-in-game-card'),
default: false,
},
@ -530,6 +608,10 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
[StreamPlayerType.VIDEO]: t('default'),
[StreamPlayerType.WEBGL2]: t('webgl2'),
},
suggest: {
lowest: StreamPlayerType.VIDEO,
highest: StreamPlayerType.WEBGL2,
},
},
[PrefKey.VIDEO_PROCESSING]: {
label: t('clarity-boost'),
@ -538,15 +620,37 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
[StreamVideoProcessing.USM]: t('unsharp-masking'),
[StreamVideoProcessing.CAS]: t('amd-fidelity-cas'),
},
suggest: {
lowest: StreamVideoProcessing.USM,
highest: StreamVideoProcessing.CAS,
},
},
[PrefKey.VIDEO_POWER_PREFERENCE]: {
label: t('renderer-configuration'),
default: 'default',
options: {
'default': t('default'),
'low-power': t('low-power'),
'low-power': t('battery-saving'),
'high-performance': t('high-performance'),
},
suggest: {
highest: 'low-power',
},
},
[PrefKey.VIDEO_MAX_FPS]: {
label: t('max-fps'),
type: SettingElementType.NUMBER_STEPPER,
default: 60,
min: 10,
max: 60,
steps: 10,
params: {
exactTicks: 10,
customTextValue: (value: any) => {
value = parseInt(value);
return value === 60 ? t('unlimited') : value + 'fps';
},
},
},
[PrefKey.VIDEO_SHARPNESS]: {
label: t('sharpness'),
@ -561,6 +665,10 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
return value === 0 ? t('off') : value.toString();
},
},
suggest: {
lowest: 0,
highest: 2,
},
},
[PrefKey.VIDEO_RATIO]: {
label: t('aspect-ratio'),
@ -616,6 +724,7 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
default: false,
},
[PrefKey.AUDIO_ENABLE_VOLUME_CONTROL]: {
requiredVariants: 'full',
label: t('enable-volume-control'),
default: false,
},
@ -637,16 +746,29 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
label: t('stats'),
default: [StreamStat.PING, StreamStat.FPS, StreamStat.BITRATE, StreamStat.DECODE_TIME, StreamStat.PACKETS_LOST, StreamStat.FRAMES_LOST],
multipleOptions: {
[StreamStat.CLOCK]: `${StreamStat.CLOCK.toUpperCase()}: ${t('clock')}`,
[StreamStat.PLAYTIME]: `${StreamStat.PLAYTIME.toUpperCase()}: ${t('playtime')}`,
[StreamStat.BATTERY]: `${StreamStat.BATTERY.toUpperCase()}: ${t('battery')}`,
[StreamStat.PING]: `${StreamStat.PING.toUpperCase()}: ${t('stat-ping')}`,
[StreamStat.JITTER]: `${StreamStat.JITTER.toUpperCase()}: ${t('jitter')}`,
[StreamStat.FPS]: `${StreamStat.FPS.toUpperCase()}: ${t('stat-fps')}`,
[StreamStat.BITRATE]: `${StreamStat.BITRATE.toUpperCase()}: ${t('stat-bitrate')}`,
[StreamStat.DECODE_TIME]: `${StreamStat.DECODE_TIME.toUpperCase()}: ${t('stat-decode-time')}`,
[StreamStat.PACKETS_LOST]: `${StreamStat.PACKETS_LOST.toUpperCase()}: ${t('stat-packets-lost')}`,
[StreamStat.FRAMES_LOST]: `${StreamStat.FRAMES_LOST.toUpperCase()}: ${t('stat-frames-lost')}`,
[StreamStat.DOWNLOAD]: `${StreamStat.DOWNLOAD.toUpperCase()}: ${t('downloaded')}`,
[StreamStat.UPLOAD]: `${StreamStat.UPLOAD.toUpperCase()}: ${t('uploaded')}`,
},
params: {
size: 6,
},
ready: setting => {
// Remove Battery option in unsupported browser
const multipleOptions = (setting as any).multipleOptions;
if (!STATES.browser.capabilities.batteryApi) {
delete multipleOptions[StreamStat.BATTERY];
}
},
},
[PrefKey.STATS_SHOW_WHEN_PLAYING]: {
label: t('show-stats-on-startup'),
@ -696,24 +818,34 @@ export class GlobalSettingsStorage extends BaseSettingsStorage {
},
[PrefKey.REMOTE_PLAY_ENABLED]: {
requiredVariants: 'full',
label: t('enable-remote-play-feature'),
default: false,
},
[PrefKey.REMOTE_PLAY_RESOLUTION]: {
default: '1080p',
requiredVariants: 'full',
default: StreamResolution.DIM_1080P,
options: {
'1080p': '1080p',
'720p': '720p',
[StreamResolution.DIM_1080P]: '1080p',
[StreamResolution.DIM_720P]: '720p',
},
},
[PrefKey.GAME_FORTNITE_FORCE_CONSOLE]: {
requiredVariants: 'full',
label: '🎮 ' + t('fortnite-force-console-version'),
default: false,
note: t('fortnite-allow-stw-mode'),
},
};
[PrefKey.GAME_MSFS2020_FORCE_NATIVE_MKB]: {
requiredVariants: 'full',
label: '✈️ ' + t('msfs2020-force-native-mkb'),
default: false,
note: t('may-not-work-properly'),
},
} satisfies SettingDefinitions;
constructor() {
super(StorageKey.GLOBAL, GlobalSettingsStorage.DEFINITIONS);

View File

@ -0,0 +1,332 @@
import { PrefKey } from "@/enums/pref-keys";
import { BxEvent } from "./bx-event";
import { STATES } from "./global";
import { humanFileSize, secondsToHm } from "./html";
import { getPref } from "./settings-storages/global-settings-storage";
import { BxLogger } from "./bx-logger";
export enum StreamStat {
PING = 'ping',
JITTER = 'jit',
FPS = 'fps',
BITRATE = 'btr',
DECODE_TIME = 'dt',
PACKETS_LOST = 'pl',
FRAMES_LOST = 'fl',
DOWNLOAD = 'dl',
UPLOAD = 'ul',
PLAYTIME = 'play',
BATTERY = 'batt',
CLOCK = 'time',
};
export type StreamStatGrade = '' | 'bad' | 'ok' | 'good';
type CurrentStats = {
[StreamStat.PING]: {
current: number;
grades: [number, number, number];
toString: () => string;
};
[StreamStat.JITTER]: {
current: number;
grades: [number, number, number];
toString: () => string;
};
[StreamStat.FPS]: {
current: number;
toString: () => string;
};
[StreamStat.BITRATE]: {
current: number;
toString: () => string;
};
[StreamStat.FRAMES_LOST]: {
received: number;
dropped: number;
toString: () => string;
};
[StreamStat.PACKETS_LOST]: {
received: number;
dropped: number;
toString: () => string;
};
[StreamStat.DECODE_TIME]: {
current: number;
total: number;
grades: [number, number, number];
toString: () => string;
};
[StreamStat.DOWNLOAD]: {
total: number;
toString: () => string;
};
[StreamStat.UPLOAD]: {
total: number;
toString: () => string;
};
[StreamStat.PLAYTIME]: {
seconds: number;
startTime: number;
toString: () => string;
};
[StreamStat.BATTERY]: {
current: number;
start: number;
isCharging: boolean;
toString: () => string;
},
[StreamStat.CLOCK]: {
toString: () => string;
},
};
export class StreamStatsCollector {
private static instance: StreamStatsCollector;
public static getInstance = () => StreamStatsCollector.instance ?? (StreamStatsCollector.instance = new StreamStatsCollector());
private readonly LOG_TAG = 'StreamStatsCollector';
// Collect in background - 60 seconds
static readonly INTERVAL_BACKGROUND = 60 * 1000;
public calculateGrade(value: number, grades: [number, number, number]): StreamStatGrade {
return (value > grades[2]) ? 'bad' : (value > grades[1]) ? 'ok' : (value > grades[0]) ? 'good' : '';
}
private currentStats: CurrentStats = {
[StreamStat.PING]: {
current: -1,
grades: [40, 75, 100],
toString() {
return this.current === -1 ? '???' : this.current.toString();
},
},
[StreamStat.JITTER]: {
current: 0,
grades: [30, 40, 60],
toString() {
return `${this.current.toFixed(2)}ms`;
},
},
[StreamStat.FPS]: {
current: 0,
toString() {
const maxFps = getPref(PrefKey.VIDEO_MAX_FPS);
return maxFps < 60 ? `${maxFps}/${this.current}` : this.current.toString();
},
},
[StreamStat.BITRATE]: {
current: 0,
toString() {
return `${this.current.toFixed(2)} Mbps`;
},
},
[StreamStat.FRAMES_LOST]: {
received: 0,
dropped: 0,
toString() {
const framesDroppedPercentage = (this.dropped * 100 / ((this.dropped + this.received) || 1)).toFixed(2);
return framesDroppedPercentage === '0.00' ? this.dropped.toString() : `${this.dropped} (${framesDroppedPercentage}%)`;
},
},
[StreamStat.PACKETS_LOST]: {
received: 0,
dropped: 0,
toString() {
const packetsLostPercentage = (this.dropped * 100 / ((this.dropped + this.received) || 1)).toFixed(2);
return packetsLostPercentage === '0.00' ? this.dropped.toString() : `${this.dropped} (${packetsLostPercentage}%)`;
},
},
[StreamStat.DECODE_TIME]: {
current: 0,
total: 0,
grades: [6, 9, 12],
toString() {
return isNaN(this.current) ? '??ms' : `${this.current.toFixed(2)}ms`;
},
},
[StreamStat.DOWNLOAD]: {
total: 0,
toString() {
return humanFileSize(this.total);
},
},
[StreamStat.UPLOAD]: {
total: 0,
toString() {
return humanFileSize(this.total);
},
},
[StreamStat.PLAYTIME]: {
seconds: 0,
startTime: 0,
toString() {
return secondsToHm(this.seconds);
},
},
[StreamStat.BATTERY]: {
current: 100,
start: 100,
isCharging: false,
toString() {
let text = `${this.current}%`;
if (this.current !== this.start) {
const diffLevel = Math.round(this.current - this.start);
const sign = diffLevel > 0 ? '+' : '';
text += ` (${sign}${diffLevel}%)`;
}
return text;
},
},
[StreamStat.CLOCK]: {
toString() {
return new Date().toLocaleTimeString([], {
hour: '2-digit',
minute:'2-digit',
hour12: false,
});
}
},
};
private lastVideoStat?: RTCInboundRtpStreamStats | null;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
}
async collect() {
const stats = await STATES.currentStream.peerConnection?.getStats();
if (!stats) {
return;
}
stats.forEach(stat => {
if (stat.type === 'inbound-rtp' && stat.kind === 'video') {
// FPS
const fps = this.currentStats[StreamStat.FPS];
fps.current = stat.framesPerSecond || 0;
// Packets Lost
// packetsLost can be negative, but we don't care about that
const pl = this.currentStats[StreamStat.PACKETS_LOST];
pl.dropped = Math.max(0, stat.packetsLost);
pl.received = stat.packetsReceived;
// Frames lost
const fl = this.currentStats[StreamStat.FRAMES_LOST];
fl.dropped = stat.framesDropped;
fl.received = stat.framesReceived;
if (!this.lastVideoStat) {
this.lastVideoStat = stat;
return;
}
const lastStat = this.lastVideoStat;
// Jitter
const jit = this.currentStats[StreamStat.JITTER];
const bufferDelayDiff = (stat as RTCInboundRtpStreamStats).jitterBufferDelay! - lastStat.jitterBufferDelay!;
const emittedCountDiff = (stat as RTCInboundRtpStreamStats).jitterBufferEmittedCount! - lastStat.jitterBufferEmittedCount!;
if (emittedCountDiff > 0) {
jit.current = bufferDelayDiff / emittedCountDiff * 1000;
}
// Bitrate
const btr = this.currentStats[StreamStat.BITRATE];
const timeDiff = stat.timestamp - lastStat.timestamp;
btr.current = 8 * (stat.bytesReceived - lastStat.bytesReceived!) / timeDiff / 1000;
// Decode time
const dt = this.currentStats[StreamStat.DECODE_TIME];
dt.total = stat.totalDecodeTime - lastStat.totalDecodeTime!;
const framesDecodedDiff = stat.framesDecoded - lastStat.framesDecoded!;
dt.current = dt.total / framesDecodedDiff * 1000;
this.lastVideoStat = stat;
} else if (stat.type === 'candidate-pair' && stat.packetsReceived > 0 && stat.state === 'succeeded') {
// Round Trip Time
const ping = this.currentStats[StreamStat.PING];
ping.current = stat.currentRoundTripTime ? stat.currentRoundTripTime * 1000 : -1;
// Download
const dl = this.currentStats[StreamStat.DOWNLOAD];
dl.total = stat.bytesReceived;
// Upload
const ul = this.currentStats[StreamStat.UPLOAD];
ul.total = stat.bytesSent;
}
});
// Battery
let batteryLevel = 100;
let isCharging = false;
if (STATES.browser.capabilities.batteryApi) {
try {
const bm = await (navigator as NavigatorBattery).getBattery();
isCharging = bm.charging;
batteryLevel = Math.round(bm.level * 100);
} catch(e) {}
}
const battery = this.currentStats[StreamStat.BATTERY];
battery.current = batteryLevel;
battery.isCharging = isCharging;
// Playtime
const playTime = this.currentStats[StreamStat.PLAYTIME];
const now = +new Date;
playTime.seconds = Math.ceil((now - playTime.startTime) / 1000);
}
getStat<T extends StreamStat>(kind: T): CurrentStats[T] {
return this.currentStats[kind];
}
reset() {
const playTime = this.currentStats[StreamStat.PLAYTIME];
playTime.seconds = 0;
playTime.startTime = +new Date;
// Get battery level
try {
STATES.browser.capabilities.batteryApi && (navigator as NavigatorBattery).getBattery().then(bm => {
this.currentStats[StreamStat.BATTERY].start = Math.round(bm.level * 100);
});
} catch(e) {}
}
static setupEvents() {
window.addEventListener(BxEvent.STREAM_PLAYING, e => {
const statsCollector = StreamStatsCollector.getInstance();
statsCollector.reset();
});
}
}

View File

@ -1,4 +1,5 @@
import { CE } from "@utils/html";
import { BxLogger } from "./bx-logger";
type ToastOptions = {
instant?: boolean;
@ -6,84 +7,100 @@ type ToastOptions = {
}
export class Toast {
static #$wrapper: HTMLElement;
static #$msg: HTMLElement;
static #$status: HTMLElement;
static #stack: Array<[string, string, ToastOptions]> = [];
static #isShowing = false;
private static instance: Toast;
public static getInstance = () => Toast.instance ?? (Toast.instance = new Toast());
private readonly LOG_TAG = 'Toast';
static #timeout?: number | null;
static #DURATION = 3000;
private $wrapper: HTMLElement;
private $msg: HTMLElement;
private $status: HTMLElement;
static show(msg: string, status?: string, options: Partial<ToastOptions> = {}) {
private stack: Array<[string, string, ToastOptions]> = [];
private isShowing = false;
private timeoutId?: number | null;
private DURATION = 3000;
private constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.$wrapper = CE('div', {class: 'bx-toast bx-offscreen'},
this.$msg = CE('span', {class: 'bx-toast-msg'}),
this.$status = CE('span', {class: 'bx-toast-status'}),
);
this.$wrapper.addEventListener('transitionend', e => {
const classList = this.$wrapper.classList;
if (classList.contains('bx-hide')) {
classList.remove('bx-offscreen', 'bx-hide');
classList.add('bx-offscreen');
this.showNext();
}
});
document.documentElement.appendChild(this.$wrapper);
}
private show(msg: string, status?: string, options: Partial<ToastOptions> = {}) {
options = options || {};
const args = Array.from(arguments) as [string, string, ToastOptions];
if (options.instant) {
// Clear stack
Toast.#stack = [args];
Toast.#showNext();
this.stack = [args];
this.showNext();
} else {
Toast.#stack.push(args);
!Toast.#isShowing && Toast.#showNext();
this.stack.push(args);
!this.isShowing && this.showNext();
}
}
static #showNext() {
if (!Toast.#stack.length) {
Toast.#isShowing = false;
private showNext() {
if (!this.stack.length) {
this.isShowing = false;
return;
}
Toast.#isShowing = true;
this.isShowing = true;
Toast.#timeout && clearTimeout(Toast.#timeout);
Toast.#timeout = window.setTimeout(Toast.#hide, Toast.#DURATION);
this.timeoutId && clearTimeout(this.timeoutId);
this.timeoutId = window.setTimeout(this.hide.bind(this), this.DURATION);
// Get values from item
const [msg, status, options] = Toast.#stack.shift()!;
const [msg, status, options] = this.stack.shift()!;
if (options && options.html) {
Toast.#$msg.innerHTML = msg;
this.$msg.innerHTML = msg;
} else {
Toast.#$msg.textContent = msg;
this.$msg.textContent = msg;
}
if (status) {
Toast.#$status.classList.remove('bx-gone');
Toast.#$status.textContent = status;
this.$status.classList.remove('bx-gone');
this.$status.textContent = status;
} else {
Toast.#$status.classList.add('bx-gone');
this.$status.classList.add('bx-gone');
}
const classList = Toast.#$wrapper.classList;
const classList = this.$wrapper.classList;
classList.remove('bx-offscreen', 'bx-hide');
classList.add('bx-show');
}
static #hide() {
Toast.#timeout = null;
private hide() {
this.timeoutId = null;
const classList = Toast.#$wrapper.classList;
const classList = this.$wrapper.classList;
classList.remove('bx-show');
classList.add('bx-hide');
}
static setup() {
Toast.#$wrapper = CE('div', {'class': 'bx-toast bx-offscreen'},
Toast.#$msg = CE('span', {'class': 'bx-toast-msg'}),
Toast.#$status = CE('span', {'class': 'bx-toast-status'}));
static show(msg: string, status?: string, options: Partial<ToastOptions> = {}) {
Toast.getInstance().show(msg, status, options);
}
Toast.#$wrapper.addEventListener('transitionend', e => {
const classList = Toast.#$wrapper.classList;
if (classList.contains('bx-hide')) {
classList.remove('bx-offscreen', 'bx-hide');
classList.add('bx-offscreen');
Toast.#showNext();
}
});
document.documentElement.appendChild(Toast.#$wrapper);
static showNext() {
Toast.getInstance().showNext();
}
}

View File

@ -2,7 +2,7 @@ import { NATIVE_FETCH } from "./bx-flags";
import { BxLogger } from "./bx-logger";
export const SUPPORTED_LANGUAGES = {
'en-US': 'English (United States)',
'en-US': 'English (US)',
'ca-CA': 'Català',
'da-DK': 'dansk',
@ -40,13 +40,8 @@ const Texts = {
"auto": "Auto",
"back-to-home": "Back to home",
"back-to-home-confirm": "Do you want to go back to the home page (without disconnecting)?",
"badge-audio": "Audio",
"badge-battery": "Battery",
"badge-in": "In",
"badge-out": "Out",
"badge-playtime": "Playtime",
"badge-server": "Server",
"badge-video": "Video",
"battery": "Battery",
"battery-saving": "Battery saving",
"better-xcloud": "Better xCloud",
"bitrate-audio-maximum": "Maximum audio bitrate",
"bitrate-video-maximum": "Maximum video bitrate",
@ -62,6 +57,7 @@ const Texts = {
"clarity-boost": "Clarity boost",
"clarity-boost-warning": "These settings don't work when the Clarity Boost mode is ON",
"clear": "Clear",
"clock": "Clock",
"close": "Close",
"close-app": "Close app",
"combine-audio-video-streams": "Combine audio & video streams",
@ -71,6 +67,11 @@ const Texts = {
"confirm-reload-stream": "Do you want to refresh the stream?",
"connected": "Connected",
"console-connect": "Connect",
"continent-asia": "Asia",
"continent-australia": "Australia",
"continent-europe": "Europe",
"continent-north-america": "North America",
"continent-south-america": "South America",
"contrast": "Contrast",
"controller": "Controller",
"controller-friendly-ui": "Controller-friendly UI",
@ -96,10 +97,12 @@ const Texts = {
"disable-xcloud-analytics": "Disable xCloud analytics",
"disabled": "Disabled",
"disconnected": "Disconnected",
"download": "Download",
"downloaded": "Downloaded",
"edit": "Edit",
"enable-controller-shortcuts": "Enable controller shortcuts",
"enable-local-co-op-support": "Enable local co-op support",
"enable-local-co-op-support-note": "Only works if the game doesn't require a different profile",
"enable-local-co-op-support-note": "Only works with some games",
"enable-mic-on-startup": "Enable microphone on game launch",
"enable-mkb": "Emulate controller with Mouse & Keyboard",
"enable-quick-glance-mode": "Enable \"Quick Glance\" mode",
@ -109,10 +112,11 @@ const Texts = {
"experimental": "Experimental",
"export": "Export",
"fast": "Fast",
"fortnite-allow-stw-mode": "Allows playing STW mode on mobile",
"fortnite-allow-stw-mode": "Allows playing \"Save the World\" mode on mobile",
"fortnite-force-console-version": "Fortnite: force console version",
"game-bar": "Game Bar",
"getting-consoles-list": "Getting the list of consoles...",
"guide": "Guide",
"help": "Help",
"hide": "Hide",
"hide-idle-cursor": "Hide mouse cursor on idle",
@ -121,23 +125,30 @@ const Texts = {
"hide-system-menu-icon": "Hide System menu's icon",
"hide-touch-controller": "Hide touch controller",
"high-performance": "High performance",
"highest-quality": "Highest quality",
"highest-quality-note": "Your device may not be powerful enough to use these settings",
"horizontal-scroll-sensitivity": "Horizontal scroll sensitivity",
"horizontal-sensitivity": "Horizontal sensitivity",
"how-to-fix": "How to fix",
"how-to-improve-app-performance": "How to improve app's performance",
"ignore": "Ignore",
"import": "Import",
"increase": "Increase",
"install-android": "Better xCloud app for Android",
"japan": "Japan",
"jitter": "Jitter",
"keyboard-shortcuts": "Keyboard shortcuts",
"korea": "Korea",
"language": "Language",
"large": "Large",
"layout": "Layout",
"left-stick": "Left stick",
"load-failed-message": "Failed to run Better xCloud",
"loading-screen": "Loading screen",
"local-co-op": "Local co-op",
"low-power": "Low power",
"lowest-quality": "Lowest quality",
"map-mouse-to": "Map mouse to",
"max-fps": "Max FPS",
"may-not-work-properly": "May not work properly!",
"menu": "Menu",
"microphone": "Microphone",
@ -146,10 +157,32 @@ const Texts = {
"mkb-disclaimer": "Using this feature when playing online could be viewed as cheating",
"mouse-and-keyboard": "Mouse & Keyboard",
"mouse-wheel": "Mouse wheel",
"msfs2020-force-native-mkb": "MSFS2020: force native M&KB support",
"muted": "Muted",
"name": "Name",
"native-mkb": "Native Mouse & Keyboard",
"new": "New",
"new-version-available": [
(e: any) => `Version ${e.version} available`,
,
,
(e: any) => `Version ${e.version} verfügbar`,
(e: any) => `Versi ${e.version} tersedia`,
(e: any) => `Versión ${e.version} disponible`,
(e: any) => `Version ${e.version} disponible`,
(e: any) => `Disponibile la versione ${e.version}`,
(e: any) => `Ver ${e.version} が利用可能です`,
(e: any) => `${e.version} 버전 사용가능`,
(e: any) => `Dostępna jest nowa wersja ${e.version}`,
(e: any) => `Versão ${e.version} disponível`,
(e: any) => `Версия ${e.version} доступна`,
(e: any) => `เวอร์ชัน ${e.version} พร้อมใช้งานแล้ว`,
(e: any) => `${e.version} sayılı yeni sürüm mevcut`,
(e: any) => `Доступна версія ${e.version}`,
(e: any) => `Đã có phiên bản ${e.version}`,
(e: any) => `版本 ${e.version} 可供更新`,
(e: any) => `已可更新為 ${e.version}`,
],
"no-consoles-found": "No consoles found",
"normal": "Normal",
"off": "Off",
@ -158,7 +191,9 @@ const Texts = {
"opacity": "Opacity",
"other": "Other",
"playing": "Playing",
"playtime": "Playtime",
"poland": "Poland",
"polling-rate": "Polling rate",
"position": "Position",
"powered-off": "Powered off",
"powered-on": "Powered on",
@ -189,6 +224,28 @@ const Texts = {
],
"press-to-bind": "Press a key or do a mouse click to bind...",
"prompt-preset-name": "Preset's name:",
"recommended": "Recommended",
"recommended-settings-for-device": [
(e: any) => `Recommended settings for ${e.device}`,
(e: any) => `Configuració recomanada per a ${e.device}`,
,
(e: any) => `Empfohlene Einstellungen für ${e.device}`,
(e: any) => `Rekomendasi pengaturan untuk ${e.device}`,
(e: any) => `Ajustes recomendados para ${e.device}`,
(e: any) => `Paramètres recommandés pour ${e.device}`,
(e: any) => `Configurazioni consigliate per ${e.device}`,
(e: any) => `${e.device} の推奨設定`,
(e: any) => `다음 기기에서 권장되는 설정: ${e.device}`,
(e: any) => `Zalecane ustawienia dla ${e.device}`,
(e: any) => `Configurações recomendadas para ${e.device}`,
(e: any) => `Рекомендуемые настройки для ${e.device}`,
(e: any) => `การตั้งค่าที่แนะนำสำหรับ ${e.device}`,
(e: any) => `${e.device} için önerilen ayarlar`,
(e: any) => `Рекомендовані налаштування для ${e.device}`,
(e: any) => `Cấu hình được đề xuất cho ${e.device}`,
(e: any) => `${e.device} 的推荐设置`,
(e: any) => `${e.device} 推薦的設定`,
],
"reduce-animations": "Reduce UI animations",
"region": "Region",
"reload-page": "Reload page",
@ -202,7 +259,6 @@ const Texts = {
"rocket-always-show": "Always show",
"rocket-animation": "Rocket animation",
"rocket-hide-queue": "Hide when queuing",
"safari-failed-message": "Failed to run Better xCloud. Retrying, please wait...",
"saturation": "Saturation",
"save": "Save",
"screen": "Screen",
@ -216,6 +272,7 @@ const Texts = {
"separate-touch-controller": "Separate Touch controller & Controller #1",
"separate-touch-controller-note": "Touch controller is Player 1, Controller #1 is Player 2",
"server": "Server",
"server-locations": "Server locations",
"settings": "Settings",
"settings-reload": "Reload page to reflect changes",
"settings-reload-note": "Settings in this tab only go into effect on the next page load",
@ -250,6 +307,8 @@ const Texts = {
"stream-settings": "Stream settings",
"stream-stats": "Stream stats",
"stretch": "Stretch",
"suggest-settings": "Suggest settings",
"suggest-settings-link": "Suggest recommended settings for this device",
"support-better-xcloud": "Support Better xCloud",
"swap-buttons": "Swap buttons",
"take-screenshot": "Take screenshot",
@ -291,6 +350,7 @@ const Texts = {
],
"touch-controller": "Touch controller",
"transparent-background": "Transparent background",
"true-achievements": "TrueAchievements",
"ui": "UI",
"unexpected-behavior": "May cause unexpected behavior",
"united-states": "United States",
@ -298,6 +358,8 @@ const Texts = {
"unlimited": "Unlimited",
"unmuted": "Unmuted",
"unsharp-masking": "Unsharp masking",
"upload": "Upload",
"uploaded": "Uploaded",
"use-mouse-absolute-position": "Use mouse's absolute position",
"use-this-at-your-own-risk": "Use this at your own risk",
"user-agent-profile": "User-Agent profile",
@ -314,6 +376,7 @@ const Texts = {
"volume": "Volume",
"wait-time-countdown": "Countdown",
"wait-time-estimated": "Estimated finish time",
"wallpaper": "Wallpaper",
"webgl2": "WebGL2",
};

View File

@ -0,0 +1,173 @@
import { BxIcon } from "./bx-icon";
import { BxLogger } from "./bx-logger";
import { AppInterface, SCRIPT_VARIANT, STATES } from "./global";
import { ButtonStyle, CE, clearDataSet, createButton, getReactProps } from "./html";
import { t } from "./translation";
export class TrueAchievements {
private static instance: TrueAchievements;
public static getInstance = () => TrueAchievements.instance ?? (TrueAchievements.instance = new TrueAchievements());
private readonly LOG_TAG = 'TrueAchievements';
private $link: HTMLElement;
private $button: HTMLElement;
private $hiddenLink: HTMLAnchorElement;
constructor() {
BxLogger.info(this.LOG_TAG, 'constructor()');
this.$link = createButton<HTMLAnchorElement>({
label: t('true-achievements'),
url: '#',
icon: BxIcon.TRUE_ACHIEVEMENTS,
style: ButtonStyle.FOCUSABLE | ButtonStyle.GHOST | ButtonStyle.FULL_WIDTH | ButtonStyle.NORMAL_LINK,
onClick: this.onClick.bind(this),
});
this.$button = createButton<HTMLAnchorElement>({
label: t('true-achievements'),
title: t('true-achievements'),
icon: BxIcon.TRUE_ACHIEVEMENTS,
style: ButtonStyle.FOCUSABLE,
onClick: this.onClick.bind(this),
});
this.$hiddenLink = CE<HTMLAnchorElement>('a', {
target: '_blank',
});
}
private onClick(e: Event) {
e.preventDefault();
// Close all xCloud's dialogs
window.BX_EXPOSED.dialogRoutes?.closeAll();
const dataset = this.$link.dataset;
this.open(true, dataset.xboxTitleId, dataset.id);
}
private updateIds(xboxTitleId?: string, id?: string) {
const $link = this.$link;
const $button = this.$button;
clearDataSet($link);
clearDataSet($button);
if (xboxTitleId) {
$link.dataset.xboxTitleId = xboxTitleId;
$button.dataset.xboxTitleId = xboxTitleId;
}
if (id) {
$link.dataset.id = id;
$button.dataset.id = id;
}
}
injectAchievementsProgress($elm: HTMLElement) {
// Only do this in Full version
if (SCRIPT_VARIANT !== 'full') {
return;
}
const $parent = $elm.parentElement!;
// Wrap xCloud's element with our own
const $div = CE('div', {
class: 'bx-guide-home-achievements-progress',
}, $elm);
// Get xboxTitleId of the game
let xboxTitleId: string | number | undefined;
try {
const $container = $parent.closest<HTMLElement>('div[class*=AchievementsPreview-module__container]');
if ($container) {
const props = getReactProps($container);
xboxTitleId = props.children.props.data.data.xboxTitleId;
}
} catch (e) {}
if (!xboxTitleId) {
xboxTitleId = this.getStreamXboxTitleId();
}
if (typeof xboxTitleId !== 'undefined') {
xboxTitleId = xboxTitleId.toString();
}
this.updateIds(xboxTitleId);
if (document.documentElement.dataset.xdsPlatform === 'tv') {
$div.appendChild(this.$link);
} else {
$div.appendChild(this.$button);
}
$parent.appendChild($div);
}
injectAchievementDetailPage($parent: HTMLElement) {
// Only do this in Full version
if (SCRIPT_VARIANT !== 'full') {
return;
}
const props = getReactProps($parent);
if (!props) {
return;
}
try {
// Achievement list
const achievementList: XboxAchievement[] = props.children.props.data.data;
// Get current achievement name
const $header = $parent.querySelector<HTMLElement>('div[class*=AchievementDetailHeader]')!;
const achievementName = getReactProps($header).children[0].props.achievementName;
// Find achievement based on name
let id: string | undefined;
let xboxTitleId: string | undefined;
for (const achiev of achievementList) {
if (achiev.name === achievementName) {
id = achiev.id;
xboxTitleId = achiev.title.id;
break;
}
}
// Found achievement -> add TrueAchievements button
if (id) {
this.updateIds(xboxTitleId, id);
$parent.appendChild(this.$link);
}
} catch (e) {};
}
private getStreamXboxTitleId() : number | undefined {
return STATES.currentStream.xboxTitleId || STATES.currentStream.titleInfo?.details.xboxTitleId;
}
open(override: boolean, xboxTitleId?: number | string, id?: number | string) {
if (!xboxTitleId || xboxTitleId === 'undefined') {
xboxTitleId = this.getStreamXboxTitleId();
}
if (AppInterface && AppInterface.openTrueAchievementsLink) {
AppInterface.openTrueAchievementsLink(override, xboxTitleId?.toString(), id?.toString());
return;
}
let url = 'https://www.trueachievements.com';
if (xboxTitleId) {
url += `/deeplink/${xboxTitleId}`;
if (id) {
url += `/${id}`;
}
}
this.$hiddenLink.href = url;
this.$hiddenLink.click();
}
}

View File

@ -28,7 +28,7 @@ export class UserAgent {
static #USER_AGENTS: PartialRecord<UserAgentProfile, string> = {
[UserAgentProfile.WINDOWS_EDGE]: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${CHROMIUM_VERSION} Safari/537.36 Edg/${CHROMIUM_VERSION}`,
[UserAgentProfile.MACOS_SAFARI]: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5.2 Safari/605.1.1',
[UserAgentProfile.SMART_TV_GENERIC]: `${window.navigator.userAgent} SmartTV`,
[UserAgentProfile.SMART_TV_GENERIC]: `${window.navigator.userAgent} Smart-TV`,
[UserAgentProfile.SMART_TV_TIZEN]: `Mozilla/5.0 (SMART-TV; LINUX; Tizen 7.0) AppleWebKit/537.36 (KHTML, like Gecko) ${CHROMIUM_VERSION}/7.0 TV Safari/537.36 ${SMART_TV_UNIQUE_ID}`,
[UserAgentProfile.VR_OCULUS]: window.navigator.userAgent + ' OculusBrowser VR',
}

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