c64-ready 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -62
- package/bin/headless.mjs +1 -1
- package/dist/assets/CHANGELOG-0a7A8Ekq.js +391 -0
- package/dist/assets/index-BESofQoh.js +627 -0
- package/dist/games/cartridges/goat-beat.crt +0 -0
- package/dist/index.html +1 -1
- package/dist-ts/emulator/c64-emulator.d.ts +7 -0
- package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
- package/dist-ts/emulator/c64-emulator.js +50 -6
- package/dist-ts/emulator/c64-emulator.js.map +1 -1
- package/dist-ts/emulator/constants.d.ts +3 -1
- package/dist-ts/emulator/constants.d.ts.map +1 -1
- package/dist-ts/emulator/constants.js +2 -0
- package/dist-ts/emulator/constants.js.map +1 -1
- package/dist-ts/emulator/input.d.ts +21 -1
- package/dist-ts/emulator/input.d.ts.map +1 -1
- package/dist-ts/emulator/input.js +295 -10
- package/dist-ts/emulator/input.js.map +1 -1
- package/dist-ts/types/emulator.d.ts +1 -1
- package/dist-ts/types/emulator.d.ts.map +1 -1
- package/package.json +1 -1
- package/public/games/cartridges/goat-beat.crt +0 -0
- package/src/emulator/c64-emulator.ts +6 -5
- package/src/emulator/constants.ts +5 -1
- package/src/emulator/input.ts +331 -19
- package/src/headless/headless-cli.mjs +73 -37
- package/src/headless/input-server.mjs +276 -102
- package/src/headless/webrtc-server.mjs +123 -12
- package/src/main.ts +12 -0
- package/src/player/c64-player.ts +21 -6
- package/src/player/input-handler.ts +8 -0
- package/src/player/styles/ui-controller.css +13 -0
- package/src/player/ui-controller.ts +128 -12
- package/src/types/emulator.ts +1 -1
- package/dist/assets/CHANGELOG-B12WeYEc.js +0 -116
- package/dist/assets/index-fUdEY2R7.js +0 -610
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
22
|
import http from 'http';
|
|
23
|
+
import crypto from 'crypto';
|
|
23
24
|
import { WebSocketServer } from 'ws';
|
|
24
25
|
import wrtc from '@roamhq/wrtc';
|
|
25
26
|
|
|
@@ -32,15 +33,51 @@ function parseCsvList(raw) {
|
|
|
32
33
|
.filter(Boolean);
|
|
33
34
|
}
|
|
34
35
|
|
|
36
|
+
function normalizeTurnTtlSeconds(rawTtl, fallback = 24 * 3600) {
|
|
37
|
+
const parsed = Number.parseInt(String(rawTtl ?? ''), 10);
|
|
38
|
+
if (Number.isFinite(parsed) && parsed > 0) return parsed;
|
|
39
|
+
return fallback;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function buildTimedTurnCredentials({
|
|
43
|
+
secret,
|
|
44
|
+
ttlSeconds = 24 * 3600,
|
|
45
|
+
usernameLabel = 'c64live',
|
|
46
|
+
nowSeconds = Math.floor(Date.now() / 1000),
|
|
47
|
+
} = {}) {
|
|
48
|
+
const safeSecret = String(secret ?? '').trim();
|
|
49
|
+
if (!safeSecret) throw new Error('TURN secret is required');
|
|
50
|
+
|
|
51
|
+
const safeLabel = String(usernameLabel ?? '').trim() || 'c64live';
|
|
52
|
+
const expiresAt = Math.floor(nowSeconds) + normalizeTurnTtlSeconds(ttlSeconds);
|
|
53
|
+
const username = `${expiresAt}:${safeLabel}`;
|
|
54
|
+
const credential = crypto
|
|
55
|
+
.createHmac('sha1', safeSecret)
|
|
56
|
+
.update(username)
|
|
57
|
+
.digest('base64');
|
|
58
|
+
|
|
59
|
+
return { username, credential };
|
|
60
|
+
}
|
|
61
|
+
|
|
35
62
|
function buildIceServers({
|
|
36
63
|
iceStunUrls,
|
|
37
64
|
iceTurnUrls,
|
|
65
|
+
iceTurnSecret,
|
|
66
|
+
iceTurnTtlSeconds,
|
|
67
|
+
iceTurnUsernameLabel,
|
|
38
68
|
iceTurnUsername,
|
|
39
69
|
iceTurnPassword,
|
|
40
70
|
verbose = false,
|
|
41
71
|
} = {}) {
|
|
42
72
|
const stunUrls = parseCsvList(iceStunUrls ?? process.env.ICE_STUN_URLS);
|
|
43
73
|
const turnUrls = parseCsvList(iceTurnUrls ?? process.env.ICE_TURN_URLS);
|
|
74
|
+
const turnSecret = String(iceTurnSecret ?? process.env.ICE_TURN_SECRET ?? '').trim();
|
|
75
|
+
const turnTtlSeconds = normalizeTurnTtlSeconds(
|
|
76
|
+
iceTurnTtlSeconds ?? process.env.ICE_TURN_TTL_SECONDS,
|
|
77
|
+
);
|
|
78
|
+
const turnUsernameLabel = String(
|
|
79
|
+
iceTurnUsernameLabel ?? process.env.ICE_TURN_USERNAME_LABEL ?? 'c64live',
|
|
80
|
+
).trim();
|
|
44
81
|
const turnUsername = String(iceTurnUsername ?? process.env.ICE_TURN_USERNAME ?? '').trim();
|
|
45
82
|
const turnPassword = String(iceTurnPassword ?? process.env.ICE_TURN_PASSWORD ?? '').trim();
|
|
46
83
|
|
|
@@ -49,7 +86,18 @@ function buildIceServers({
|
|
|
49
86
|
iceServers.push({ urls: stunUrls });
|
|
50
87
|
}
|
|
51
88
|
|
|
52
|
-
if (turnUrls.length > 0 &&
|
|
89
|
+
if (turnUrls.length > 0 && turnSecret) {
|
|
90
|
+
const creds = buildTimedTurnCredentials({
|
|
91
|
+
secret: turnSecret,
|
|
92
|
+
ttlSeconds: turnTtlSeconds,
|
|
93
|
+
usernameLabel: turnUsernameLabel,
|
|
94
|
+
});
|
|
95
|
+
iceServers.push({
|
|
96
|
+
urls: turnUrls,
|
|
97
|
+
username: creds.username,
|
|
98
|
+
credential: creds.credential,
|
|
99
|
+
});
|
|
100
|
+
} else if (turnUrls.length > 0 && turnUsername && turnPassword) {
|
|
53
101
|
iceServers.push({
|
|
54
102
|
urls: turnUrls,
|
|
55
103
|
username: turnUsername,
|
|
@@ -57,7 +105,7 @@ function buildIceServers({
|
|
|
57
105
|
});
|
|
58
106
|
} else if (turnUrls.length > 0 && verbose) {
|
|
59
107
|
console.error(
|
|
60
|
-
'[webrtc] ICE_TURN_URLS provided without ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN',
|
|
108
|
+
'[webrtc] ICE_TURN_URLS provided without ICE_TURN_SECRET or ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN',
|
|
61
109
|
);
|
|
62
110
|
}
|
|
63
111
|
|
|
@@ -68,9 +116,13 @@ function buildIceServers({
|
|
|
68
116
|
if (verbose) {
|
|
69
117
|
const stunCount = stunUrls.length;
|
|
70
118
|
const turnCount = turnUrls.length;
|
|
71
|
-
const
|
|
119
|
+
const turnMode = turnUrls.length > 0 && turnSecret
|
|
120
|
+
? 'timed'
|
|
121
|
+
: turnUrls.length > 0 && turnUsername && turnPassword
|
|
122
|
+
? 'static'
|
|
123
|
+
: 'disabled';
|
|
72
124
|
console.error(
|
|
73
|
-
`[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount}
|
|
125
|
+
`[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnMode=${turnMode}`,
|
|
74
126
|
);
|
|
75
127
|
}
|
|
76
128
|
|
|
@@ -83,7 +135,7 @@ function buildIceServers({
|
|
|
83
135
|
* @param {boolean} [opts.verbose=false] Log state changes to stderr
|
|
84
136
|
* @param {number} [opts.inputPort=9001] Port the input WebSocket listens on
|
|
85
137
|
* (embedded in the browser page)
|
|
86
|
-
* @param {number} [opts.maxSpectators=
|
|
138
|
+
* @param {number} [opts.maxSpectators=10] Maximum number of spectator connections
|
|
87
139
|
* (not counting the 2 player slots).
|
|
88
140
|
* When the limit is reached, new WebRTC
|
|
89
141
|
* connections are rejected immediately with
|
|
@@ -92,6 +144,9 @@ function buildIceServers({
|
|
|
92
144
|
* @param {number} [opts.maxBitrateKbps=600] SDP x-google-max-bitrate for VP8 answer
|
|
93
145
|
* @param {string|string[]} [opts.iceStunUrls] Optional STUN URL list
|
|
94
146
|
* @param {string|string[]} [opts.iceTurnUrls] Optional TURN URL list
|
|
147
|
+
* @param {string} [opts.iceTurnSecret] Optional TURN shared secret for timed creds
|
|
148
|
+
* @param {number} [opts.iceTurnTtlSeconds] Optional TURN credential TTL in seconds
|
|
149
|
+
* @param {string} [opts.iceTurnUsernameLabel] Optional TURN username suffix for timed creds
|
|
95
150
|
* @param {string} [opts.iceTurnUsername] Optional TURN username
|
|
96
151
|
* @param {string} [opts.iceTurnPassword] Optional TURN credential/password
|
|
97
152
|
* @param {(pc: RTCPeerConnection) => void} opts.onOffer
|
|
@@ -99,6 +154,8 @@ function buildIceServers({
|
|
|
99
154
|
* Attach tracks here: pc.addTrack(videoTrack, stream)
|
|
100
155
|
* @param {(pc: RTCPeerConnection) => void} [opts.onPeerConnected]
|
|
101
156
|
* Called once ICE reaches 'connected' or 'completed'.
|
|
157
|
+
* @param {(payload: { msg: any, remoteAddr: string, sessionId: string|null, send: (msg: any) => void }) => boolean | void} [opts.onDataChannelInput]
|
|
158
|
+
* Called for JSON messages received on the browser-created `input` data channel.
|
|
102
159
|
* @returns {{ close: () => Promise<void> }}
|
|
103
160
|
*/
|
|
104
161
|
export function createWebRTCServer({
|
|
@@ -106,24 +163,33 @@ export function createWebRTCServer({
|
|
|
106
163
|
verbose = false,
|
|
107
164
|
logEvents = false,
|
|
108
165
|
inputPort = 9001,
|
|
109
|
-
maxSpectators =
|
|
166
|
+
maxSpectators = 10,
|
|
110
167
|
minBitrateKbps = 200,
|
|
111
168
|
maxBitrateKbps = 600,
|
|
112
169
|
iceStunUrls,
|
|
113
170
|
iceTurnUrls,
|
|
171
|
+
iceTurnSecret,
|
|
172
|
+
iceTurnTtlSeconds,
|
|
173
|
+
iceTurnUsernameLabel,
|
|
114
174
|
iceTurnUsername,
|
|
115
175
|
iceTurnPassword,
|
|
116
176
|
onOffer,
|
|
117
177
|
onPeerConnected,
|
|
178
|
+
onDataChannelInput,
|
|
118
179
|
} = {}) {
|
|
119
|
-
const
|
|
180
|
+
const buildRuntimeIceServers = () => buildIceServers({
|
|
120
181
|
iceStunUrls,
|
|
121
182
|
iceTurnUrls,
|
|
183
|
+
iceTurnSecret,
|
|
184
|
+
iceTurnTtlSeconds,
|
|
185
|
+
iceTurnUsernameLabel,
|
|
122
186
|
iceTurnUsername,
|
|
123
187
|
iceTurnPassword,
|
|
124
188
|
verbose,
|
|
125
189
|
});
|
|
126
190
|
|
|
191
|
+
const iceServers = buildRuntimeIceServers();
|
|
192
|
+
|
|
127
193
|
/** Emit a structured [event] line — same format as input-server.mjs. */
|
|
128
194
|
function logEv(tag, fields = {}) {
|
|
129
195
|
if (!logEvents) return;
|
|
@@ -465,8 +531,13 @@ export function createWebRTCServer({
|
|
|
465
531
|
|
|
466
532
|
const httpServer = http.createServer((req, res) => {
|
|
467
533
|
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
|
|
534
|
+
const requestIceServers = buildRuntimeIceServers();
|
|
468
535
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
469
|
-
res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe,
|
|
536
|
+
res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, requestIceServers));
|
|
537
|
+
} else if (req.method === 'GET' && req.url === '/ice-config') {
|
|
538
|
+
const requestIceServers = buildRuntimeIceServers();
|
|
539
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
540
|
+
res.end(JSON.stringify({ iceServers: requestIceServers }));
|
|
470
541
|
} else if (req.url === '/favicon.ico') {
|
|
471
542
|
// Return a minimal 1×1 transparent ICO so browsers don't log a 404
|
|
472
543
|
res.writeHead(204);
|
|
@@ -548,7 +619,7 @@ export function createWebRTCServer({
|
|
|
548
619
|
logEv('webrtc-peer-connected', { addr: remoteAddr });
|
|
549
620
|
logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
|
|
550
621
|
|
|
551
|
-
const pc = new RTCPeerConnection({ iceServers });
|
|
622
|
+
const pc = new RTCPeerConnection({ iceServers: buildRuntimeIceServers() });
|
|
552
623
|
const controller = {
|
|
553
624
|
pc,
|
|
554
625
|
ws,
|
|
@@ -610,6 +681,15 @@ export function createWebRTCServer({
|
|
|
610
681
|
function closePeer(reason) {
|
|
611
682
|
clearDisconnectTimer();
|
|
612
683
|
const wasActive = activePeers.delete(pc);
|
|
684
|
+
const detail = {
|
|
685
|
+
reason,
|
|
686
|
+
iceState: controller.iceState,
|
|
687
|
+
everConnected,
|
|
688
|
+
connected: controller.connected,
|
|
689
|
+
sessionId: controller.sessionKey ?? null,
|
|
690
|
+
signalingState: pc.signalingState,
|
|
691
|
+
connectionState: pc.connectionState,
|
|
692
|
+
};
|
|
613
693
|
peerStatsPrev.delete(pc);
|
|
614
694
|
if (controller.sessionKey) {
|
|
615
695
|
const mapped = peerBySession.get(controller.sessionKey);
|
|
@@ -620,14 +700,16 @@ export function createWebRTCServer({
|
|
|
620
700
|
if (!wasActive && !everConnected) {
|
|
621
701
|
if (pendingPeers > 0) pendingPeers--;
|
|
622
702
|
}
|
|
623
|
-
console.error(
|
|
624
|
-
|
|
703
|
+
console.error(
|
|
704
|
+
`[webrtc] closing peer (${remoteAddr}): ${reason} ice=${detail.iceState} everConnected=${detail.everConnected} signaling=${detail.signalingState} pc=${detail.connectionState}`,
|
|
705
|
+
);
|
|
706
|
+
logEv('webrtc-peer-closed', { addr: remoteAddr, ...detail });
|
|
625
707
|
logLoadSnapshot('webrtc-load-change', { reason: `peer-closed:${reason}` });
|
|
626
708
|
// Tell the browser the stream died so it can reconnect immediately
|
|
627
709
|
// rather than sitting on a frozen frame.
|
|
628
710
|
if (ws.readyState === ws.OPEN) {
|
|
629
711
|
try {
|
|
630
|
-
ws.send(JSON.stringify({ type: 'peer-closed',
|
|
712
|
+
ws.send(JSON.stringify({ type: 'peer-closed', ...detail }));
|
|
631
713
|
} catch (_) {}
|
|
632
714
|
}
|
|
633
715
|
pc.close();
|
|
@@ -642,6 +724,35 @@ export function createWebRTCServer({
|
|
|
642
724
|
}
|
|
643
725
|
};
|
|
644
726
|
|
|
727
|
+
pc.ondatachannel = ({ channel }) => {
|
|
728
|
+
if (!channel || channel.label !== 'input') return;
|
|
729
|
+
|
|
730
|
+
channel.onmessage = ({ data }) => {
|
|
731
|
+
let msg;
|
|
732
|
+
try {
|
|
733
|
+
msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
|
|
734
|
+
} catch {
|
|
735
|
+
if (verbose) console.error(`[webrtc] bad datachannel JSON from ${remoteAddr}`);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
try {
|
|
740
|
+
onDataChannelInput?.({
|
|
741
|
+
msg,
|
|
742
|
+
remoteAddr,
|
|
743
|
+
sessionId: controller.sessionKey ?? null,
|
|
744
|
+
send(reply) {
|
|
745
|
+
if (!reply) return;
|
|
746
|
+
if (channel.readyState !== 'open') return;
|
|
747
|
+
channel.send(JSON.stringify(reply));
|
|
748
|
+
},
|
|
749
|
+
});
|
|
750
|
+
} catch (err) {
|
|
751
|
+
console.error(`[webrtc] datachannel input error (${remoteAddr}): ${err?.message ?? err}`);
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
};
|
|
755
|
+
|
|
645
756
|
pc.oniceconnectionstatechange = () => {
|
|
646
757
|
const s = pc.iceConnectionState;
|
|
647
758
|
controller.iceState = s;
|
package/src/main.ts
CHANGED
|
@@ -89,6 +89,18 @@ window.addEventListener('c64-load-file', async (e: Event) => {
|
|
|
89
89
|
}
|
|
90
90
|
});
|
|
91
91
|
|
|
92
|
+
window.addEventListener('c64-controller-connected', (e: Event) => {
|
|
93
|
+
const detail = (e as CustomEvent).detail;
|
|
94
|
+
status.textContent = `Controller Connected: ${detail.index} - ${detail.name}`;
|
|
95
|
+
status.style.color = '#9ecbff';
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
window.addEventListener('c64-controller-disconnected', (e: Event) => {
|
|
99
|
+
const detail = (e as CustomEvent).detail;
|
|
100
|
+
status.textContent = `Controller Disconnected : ${detail.index} - ${detail.name}`;
|
|
101
|
+
status.style.color = '#9ecbff';
|
|
102
|
+
})
|
|
103
|
+
|
|
92
104
|
window.addEventListener('c64-load-tool', async (e: Event) => {
|
|
93
105
|
const detail = (e as CustomEvent).detail as
|
|
94
106
|
| { name?: string; url?: string; type?: string }
|
package/src/player/c64-player.ts
CHANGED
|
@@ -95,11 +95,11 @@ export class C64Player {
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
const contentLength = Number(response.headers.get('content-length') ?? 0);
|
|
98
|
-
let data: Uint8Array
|
|
98
|
+
let data: Uint8Array<ArrayBufferLike>;
|
|
99
99
|
|
|
100
100
|
if (contentLength > 0 && response.body) {
|
|
101
101
|
const reader = response.body.getReader();
|
|
102
|
-
const chunks: Uint8Array[] = [];
|
|
102
|
+
const chunks: Uint8Array<ArrayBufferLike>[] = [];
|
|
103
103
|
let loaded = 0;
|
|
104
104
|
|
|
105
105
|
let result = await reader.read();
|
|
@@ -271,6 +271,21 @@ export class C64Player {
|
|
|
271
271
|
this.inputHandler?.setInputMode(mode);
|
|
272
272
|
}
|
|
273
273
|
|
|
274
|
+
setActiveGamepadIndex(index: number): void {
|
|
275
|
+
this.inputHandler?.setActiveGamepadIndex(index);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
getActiveGamepadIndex(): number {
|
|
279
|
+
return this.inputHandler?.getActiveGamepadIndex() ?? -1;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
getSnapshot(): Uint8Array {
|
|
283
|
+
if (!this.emulator) {
|
|
284
|
+
throw new Error('Emulator not initialised');
|
|
285
|
+
}
|
|
286
|
+
return this.emulator.getSnapshot();
|
|
287
|
+
}
|
|
288
|
+
|
|
274
289
|
setCrtPreloadChecksDisabled(disabled: boolean): void {
|
|
275
290
|
this.disableCrtPreloadChecks = disabled;
|
|
276
291
|
this.emulator?.setCrtPreloadChecksEnabled(!disabled);
|
|
@@ -317,7 +332,7 @@ export class C64Player {
|
|
|
317
332
|
}
|
|
318
333
|
|
|
319
334
|
private assertSnapshotFormatSupported(
|
|
320
|
-
data: Uint8Array
|
|
335
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
321
336
|
type: GameLoadOptions['type'],
|
|
322
337
|
source: string,
|
|
323
338
|
): void {
|
|
@@ -348,7 +363,7 @@ export class C64Player {
|
|
|
348
363
|
}
|
|
349
364
|
|
|
350
365
|
private handleCrtPreloadChecks(
|
|
351
|
-
data: Uint8Array
|
|
366
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
352
367
|
source: string,
|
|
353
368
|
onProgress?: ProgressCallback,
|
|
354
369
|
): void {
|
|
@@ -381,7 +396,7 @@ export class C64Player {
|
|
|
381
396
|
}
|
|
382
397
|
|
|
383
398
|
function validateCrtSupportOrThrow(
|
|
384
|
-
data: Uint8Array
|
|
399
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
385
400
|
source: string,
|
|
386
401
|
onProgress?: ProgressCallback,
|
|
387
402
|
): void {
|
|
@@ -413,7 +428,7 @@ function waitMs(ms: number): Promise<void> {
|
|
|
413
428
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
414
429
|
}
|
|
415
430
|
|
|
416
|
-
function hasViceSnapshotMagic(data: Uint8Array): boolean {
|
|
431
|
+
function hasViceSnapshotMagic(data: Uint8Array<ArrayBufferLike>): boolean {
|
|
417
432
|
const magic = 'VICE Snapshot File\x1a';
|
|
418
433
|
if (data.length < magic.length) return false;
|
|
419
434
|
for (let i = 0; i < magic.length; i++) {
|
|
@@ -40,6 +40,14 @@ export default class InputHandler {
|
|
|
40
40
|
return this.emulatorInput.getInputMode();
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
setActiveGamepadIndex(index: number): void {
|
|
44
|
+
this.emulatorInput.setActiveGamepadIndex(index);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
getActiveGamepadIndex(): number {
|
|
48
|
+
return this.emulatorInput.getActiveGamepadIndex();
|
|
49
|
+
}
|
|
50
|
+
|
|
43
51
|
private onCaptureKeyDown(e: KeyboardEvent): void {
|
|
44
52
|
// Block joystick-mapped keys (standard + mixed mode) when overlays are
|
|
45
53
|
// visible or the document is unfocused. Use the union of both key sets.
|
|
@@ -358,6 +358,7 @@
|
|
|
358
358
|
}
|
|
359
359
|
.c64-radio-row {
|
|
360
360
|
margin-top: 8px;
|
|
361
|
+
margin-bottom: 16px;
|
|
361
362
|
display: flex;
|
|
362
363
|
gap: 12px;
|
|
363
364
|
align-items: center;
|
|
@@ -371,6 +372,18 @@
|
|
|
371
372
|
color: #888;
|
|
372
373
|
line-height: 1.4;
|
|
373
374
|
}
|
|
375
|
+
.c64-gamepad-list {
|
|
376
|
+
margin-top: 8px;
|
|
377
|
+
margin-bottom: 8px;
|
|
378
|
+
display: flex;
|
|
379
|
+
flex-wrap: wrap;
|
|
380
|
+
gap: 8px;
|
|
381
|
+
}
|
|
382
|
+
.c64-gamepad-btn.active {
|
|
383
|
+
background: #7b71d5;
|
|
384
|
+
border-color: #948bff;
|
|
385
|
+
color: #fff;
|
|
386
|
+
}
|
|
374
387
|
.c64-dragarea {
|
|
375
388
|
border: 2px dashed #2a2a3e;
|
|
376
389
|
border-radius: 6px;
|
|
@@ -39,6 +39,16 @@ import {
|
|
|
39
39
|
|
|
40
40
|
const CRT_PRELOAD_CHECKS_STORAGE_KEY = 'c64-disable-crt-preload-checks';
|
|
41
41
|
|
|
42
|
+
type ConnectedGamepad = {
|
|
43
|
+
index: number;
|
|
44
|
+
name: string;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
function formatSnapshotFilename(now: Date = new Date()): string {
|
|
48
|
+
const pad = (value: number): string => String(value).padStart(2, '0');
|
|
49
|
+
return `snapshot-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.c64`;
|
|
50
|
+
}
|
|
51
|
+
|
|
42
52
|
export default class UIController {
|
|
43
53
|
private helpOverlay: HTMLElement | null = null;
|
|
44
54
|
private settingsOverlay: HTMLElement | null = null;
|
|
@@ -47,15 +57,98 @@ export default class UIController {
|
|
|
47
57
|
// Save previous overflow styles so we can restore them when exiting full/stretch
|
|
48
58
|
private savedHtmlOverflow: string | null = null;
|
|
49
59
|
private savedBodyOverflow: string | null = null;
|
|
60
|
+
private connectedGamepads = new Map<number, ConnectedGamepad>();
|
|
61
|
+
private readonly handleControllerConnected = (event: Event): void => {
|
|
62
|
+
const detail = (event as CustomEvent<{ name?: string; index?: number }>).detail;
|
|
63
|
+
if (typeof detail?.index !== 'number') return;
|
|
64
|
+
this.connectedGamepads.set(detail.index, {
|
|
65
|
+
index: detail.index,
|
|
66
|
+
name: detail.name ?? `Gamepad ${detail.index}`,
|
|
67
|
+
});
|
|
68
|
+
this.renderGamepadButtons();
|
|
69
|
+
};
|
|
70
|
+
private readonly handleControllerDisconnected = (event: Event): void => {
|
|
71
|
+
const detail = (event as CustomEvent<{ index?: number }>).detail;
|
|
72
|
+
if (typeof detail?.index !== 'number') return;
|
|
73
|
+
this.connectedGamepads.delete(detail.index);
|
|
74
|
+
this.renderGamepadButtons();
|
|
75
|
+
};
|
|
50
76
|
|
|
51
77
|
init(player?: C64Player): void {
|
|
52
78
|
this.player = player ?? null;
|
|
79
|
+
this.syncConnectedGamepads();
|
|
53
80
|
this.injectCSS();
|
|
54
81
|
this.createButton();
|
|
55
82
|
this.createDialog();
|
|
56
83
|
this.createHamburger();
|
|
57
84
|
this.createMenu();
|
|
58
85
|
this.createUnmuteButton();
|
|
86
|
+
window.addEventListener('c64-controller-connected', this.handleControllerConnected);
|
|
87
|
+
window.addEventListener('c64-controller-disconnected', this.handleControllerDisconnected);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private syncConnectedGamepads(): void {
|
|
91
|
+
this.connectedGamepads.clear();
|
|
92
|
+
const gamepads = navigator.getGamepads?.() ?? [];
|
|
93
|
+
for (const gamepad of gamepads) {
|
|
94
|
+
if (!gamepad) continue;
|
|
95
|
+
this.connectedGamepads.set(gamepad.index, {
|
|
96
|
+
index: gamepad.index,
|
|
97
|
+
name: gamepad.id,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private getConnectedGamepads(): ConnectedGamepad[] {
|
|
103
|
+
return Array.from(this.connectedGamepads.values()).sort((a, b) => a.index - b.index);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private getGamepadLabel(gamepad: ConnectedGamepad): string {
|
|
107
|
+
const shortenedName = gamepad.name.replace(/\s*\([^)]*\)\s*$/u, '').trim();
|
|
108
|
+
const name = shortenedName || gamepad.name.trim() || `Gamepad ${gamepad.index}`;
|
|
109
|
+
return `${gamepad.index}: ${name}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private renderGamepadButtons(): void {
|
|
113
|
+
const container = document.getElementById('c64-gamepad-list');
|
|
114
|
+
const emptyState = document.getElementById('c64-gamepad-empty');
|
|
115
|
+
if (!container || !emptyState) return;
|
|
116
|
+
|
|
117
|
+
const gamepads = this.getConnectedGamepads();
|
|
118
|
+
const activeIndex = this.player?.getActiveGamepadIndex() ?? -1;
|
|
119
|
+
|
|
120
|
+
container.replaceChildren(
|
|
121
|
+
...gamepads.map((gamepad) => {
|
|
122
|
+
const button = document.createElement('button');
|
|
123
|
+
const active = gamepad.index === activeIndex;
|
|
124
|
+
button.type = 'button';
|
|
125
|
+
button.className = `c64-btn c64-gamepad-btn${active ? ' active' : ''}`;
|
|
126
|
+
button.textContent = this.getGamepadLabel(gamepad);
|
|
127
|
+
button.setAttribute('aria-pressed', active ? 'true' : 'false');
|
|
128
|
+
button.addEventListener('click', () => {
|
|
129
|
+
if (!this.player) return;
|
|
130
|
+
this.player.setActiveGamepadIndex(gamepad.index);
|
|
131
|
+
this.renderGamepadButtons();
|
|
132
|
+
});
|
|
133
|
+
return button;
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
emptyState.hidden = gamepads.length > 0;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
private downloadSnapshot(snapshot: Uint8Array): void {
|
|
141
|
+
const snapshotCopy = new Uint8Array(snapshot.byteLength);
|
|
142
|
+
snapshotCopy.set(snapshot);
|
|
143
|
+
const blob = new Blob([snapshotCopy], { type: 'application/bin' });
|
|
144
|
+
const url = URL.createObjectURL(blob);
|
|
145
|
+
const link = document.createElement('a');
|
|
146
|
+
link.href = url;
|
|
147
|
+
link.download = formatSnapshotFilename();
|
|
148
|
+
document.body.appendChild(link);
|
|
149
|
+
link.click();
|
|
150
|
+
link.remove();
|
|
151
|
+
URL.revokeObjectURL(url);
|
|
59
152
|
}
|
|
60
153
|
|
|
61
154
|
private injectCSS(): void {
|
|
@@ -204,13 +297,13 @@ export default class UIController {
|
|
|
204
297
|
<div class="c64-menu-body">
|
|
205
298
|
<div class="c64-settings-tabs" role="tablist" aria-label="Settings sections">
|
|
206
299
|
${sections
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
300
|
+
.map(
|
|
301
|
+
(section, i) =>
|
|
302
|
+
`<button class="c64-settings-tab${i === 0 ? ' active' : ''}" data-settings-tab="${section.id}" role="tab" aria-selected="${
|
|
303
|
+
i === 0 ? 'true' : 'false'
|
|
304
|
+
}">${section.label}</button>`,
|
|
305
|
+
)
|
|
306
|
+
.join('')}
|
|
214
307
|
</div>
|
|
215
308
|
|
|
216
309
|
<div class="c64-settings-sections">
|
|
@@ -266,6 +359,9 @@ export default class UIController {
|
|
|
266
359
|
<label><input type="radio" name="c64-input-mode" value="mixed" checked /> Mixed</label>
|
|
267
360
|
</div>
|
|
268
361
|
<div id="c64-input-mode-hint" class="c64-section-hint">Arrows + Z + Ctrl = joystick & all other keys → C64 keyboard</div>
|
|
362
|
+
<label class="c64-section-label">Gamepads</label>
|
|
363
|
+
<div id="c64-gamepad-list" class="c64-gamepad-list"></div>
|
|
364
|
+
<div id="c64-gamepad-empty" class="c64-section-hint">To use a gamepad, connect it to your computer and press any button.</div>
|
|
269
365
|
</section>
|
|
270
366
|
|
|
271
367
|
<section class="c64-settings-section" data-settings-section="display" hidden>
|
|
@@ -284,6 +380,7 @@ export default class UIController {
|
|
|
284
380
|
<section class="c64-settings-section" data-settings-section="system" hidden>
|
|
285
381
|
<label class="c64-section-label">System Actions</label>
|
|
286
382
|
<div class="c64-system-actions">
|
|
383
|
+
<button class="c64-btn" id="c64-save-snapshot-btn">Save Snapshot</button>
|
|
287
384
|
<button class="c64-btn" id="c64-detach-btn">Detach Cartridge</button>
|
|
288
385
|
<button class="c64-btn" id="c64-reset-btn">Hard Reset</button>
|
|
289
386
|
<button class="c64-btn" id="c64-reboot-btn">Reboot Emulator</button>
|
|
@@ -313,18 +410,18 @@ export default class UIController {
|
|
|
313
410
|
|
|
314
411
|
const activateSection = (sectionId: string) => {
|
|
315
412
|
tabButtons.forEach((tab) => {
|
|
316
|
-
const active = tab.
|
|
413
|
+
const active = tab.getAttribute('data-settings-tab') === sectionId;
|
|
317
414
|
tab.classList.toggle('active', active);
|
|
318
415
|
tab.setAttribute('aria-selected', active ? 'true' : 'false');
|
|
319
416
|
});
|
|
320
417
|
sectionEls.forEach((section) => {
|
|
321
|
-
section.hidden = section.
|
|
418
|
+
section.hidden = section.getAttribute('data-settings-section') !== sectionId;
|
|
322
419
|
});
|
|
323
420
|
};
|
|
324
421
|
|
|
325
422
|
tabButtons.forEach((tab) => {
|
|
326
423
|
tab.addEventListener('click', () => {
|
|
327
|
-
const sectionId = tab.
|
|
424
|
+
const sectionId = tab.getAttribute('data-settings-tab');
|
|
328
425
|
if (sectionId) activateSection(sectionId);
|
|
329
426
|
});
|
|
330
427
|
});
|
|
@@ -424,7 +521,7 @@ export default class UIController {
|
|
|
424
521
|
: [];
|
|
425
522
|
|
|
426
523
|
return entries
|
|
427
|
-
.map((entry) => {
|
|
524
|
+
.map((entry: unknown) => {
|
|
428
525
|
const path =
|
|
429
526
|
typeof entry === 'string'
|
|
430
527
|
? entry
|
|
@@ -446,7 +543,7 @@ export default class UIController {
|
|
|
446
543
|
);
|
|
447
544
|
return { name: filename, url, type } satisfies ToolItem;
|
|
448
545
|
})
|
|
449
|
-
.filter((v): v is ToolItem => !!v);
|
|
546
|
+
.filter((v: ToolItem | null): v is ToolItem => !!v);
|
|
450
547
|
};
|
|
451
548
|
|
|
452
549
|
const loadToolsManifest = async () => {
|
|
@@ -480,6 +577,7 @@ export default class UIController {
|
|
|
480
577
|
|
|
481
578
|
const section = panel.querySelector('[data-settings-section="system"]');
|
|
482
579
|
// Detach cartridge / hard reset controls
|
|
580
|
+
const saveSnapshotBtn = section?.querySelector('#c64-save-snapshot-btn') as HTMLButtonElement | null;
|
|
483
581
|
const detachBtn = section?.querySelector('#c64-detach-btn') as HTMLButtonElement | null;
|
|
484
582
|
const resetBtn = section?.querySelector('#c64-reset-btn') as HTMLButtonElement | null;
|
|
485
583
|
const rebootBtn = section?.querySelector('#c64-reboot-btn') as HTMLButtonElement | null;
|
|
@@ -498,6 +596,22 @@ export default class UIController {
|
|
|
498
596
|
this.player?.setCrtPreloadChecksDisabled(disabled);
|
|
499
597
|
});
|
|
500
598
|
}
|
|
599
|
+
if (saveSnapshotBtn) {
|
|
600
|
+
saveSnapshotBtn.addEventListener('click', () => {
|
|
601
|
+
if (!this.player || typeof this.player.getSnapshot !== 'function') return;
|
|
602
|
+
const statusEl = document.getElementById('status');
|
|
603
|
+
try {
|
|
604
|
+
this.downloadSnapshot(this.player.getSnapshot());
|
|
605
|
+
if (statusEl) {
|
|
606
|
+
statusEl.textContent = 'Snapshot saved';
|
|
607
|
+
}
|
|
608
|
+
} catch (err) {
|
|
609
|
+
if (statusEl) {
|
|
610
|
+
statusEl.textContent = `Snapshot save failed: ${String((err as Error)?.message ?? err)}`;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
});
|
|
614
|
+
}
|
|
501
615
|
if (detachBtn) {
|
|
502
616
|
detachBtn.addEventListener('click', () => {
|
|
503
617
|
if (!this.player) return;
|
|
@@ -595,6 +709,7 @@ export default class UIController {
|
|
|
595
709
|
if (r.checked) applyInputMode(r.value);
|
|
596
710
|
});
|
|
597
711
|
});
|
|
712
|
+
this.renderGamepadButtons();
|
|
598
713
|
|
|
599
714
|
// ── Display section wiring ─────────────────────────────────────────────
|
|
600
715
|
const displayRadios = panel.querySelectorAll(
|
|
@@ -668,6 +783,7 @@ export default class UIController {
|
|
|
668
783
|
window.addEventListener('c64-close-dialog', () => {
|
|
669
784
|
this.closeMenu();
|
|
670
785
|
});
|
|
786
|
+
|
|
671
787
|
// Close settings when a load completes or errors so the user sees the result
|
|
672
788
|
// window.addEventListener('c64-load-success', () => {
|
|
673
789
|
// this.settingsOverlay?.classList.remove('visible');
|