-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.html
More file actions
719 lines (650 loc) · 26.9 KB
/
index.html
File metadata and controls
719 lines (650 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pebble Emulator</title>
<script src="coi-serviceworker.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #1a1a2e;
color: #e0e0e0;
font-family: monospace;
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px;
}
h1 { margin-bottom: 10px; font-size: 18px; }
#status {
margin-bottom: 10px;
padding: 5px 10px;
background: #16213e;
border-radius: 4px;
font-size: 14px;
}
#progress-bar {
width: 400px;
height: 6px;
background: #16213e;
border-radius: 3px;
margin-bottom: 15px;
overflow: hidden;
display: none;
}
#progress-fill {
height: 100%;
background: #4cc9f0;
border-radius: 3px;
width: 0%;
transition: width 0.2s;
}
#display-wrapper {
position: relative;
margin-bottom: 15px;
}
canvas#canvas {
image-rendering: pixelated;
border: 2px solid #333;
border-radius: 8px;
width: 200px;
height: 228px;
}
#buttons {
display: flex;
gap: 10px;
margin-bottom: 15px;
}
#buttons button {
padding: 8px 16px;
background: #16213e;
color: #e0e0e0;
border: 1px solid #444;
border-radius: 4px;
cursor: pointer;
font-family: monospace;
font-size: 14px;
user-select: none;
}
#buttons button:active, #buttons button.pressed { background: #0f3460; }
#buttons button:hover { border-color: #888; }
#console-wrapper {
width: 600px;
max-height: 300px;
}
#console-wrapper h3 {
font-size: 12px;
color: #888;
margin-bottom: 5px;
}
#console {
width: 100%;
height: 250px;
background: #0a0a0a;
color: #0f0;
font-size: 12px;
padding: 8px;
overflow-y: auto;
border: 1px solid #333;
border-radius: 4px;
white-space: pre-wrap;
word-wrap: break-word;
}
.key-hint {
font-size: 11px;
color: #666;
margin-top: 5px;
}
#controls {
margin-bottom: 10px;
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
#controls select, #controls button {
background: #16213e;
color: #e0e0e0;
border: 1px solid #444;
border-radius: 4px;
font-family: monospace;
font-size: 14px;
}
#controls select { padding: 4px 8px; }
#controls button { padding: 4px 12px; cursor: pointer; }
#controls button:hover { border-color: #888; }
#controls button:disabled { opacity: 0.5; cursor: default; }
#btn-boot {
background: linear-gradient(135deg, #ff6b35, #e91e63, #9c27b0) !important;
color: #fff !important;
border: none !important;
padding: 6px 18px !important;
font-size: 15px !important;
font-weight: bold;
letter-spacing: 0.5px;
box-shadow: 0 2px 8px rgba(233, 30, 99, 0.4);
transition: transform 0.1s, box-shadow 0.1s;
}
#btn-boot:hover:not(:disabled) {
transform: scale(1.05);
box-shadow: 0 4px 14px rgba(233, 30, 99, 0.6);
}
#btn-boot:active:not(:disabled) { transform: scale(0.97); }
#btn-boot:disabled { opacity: 0.5; filter: grayscale(0.4); }
@media (max-width: 640px) {
body { padding: 12px 8px; }
h1 { font-size: 16px; }
#controls { flex-wrap: wrap; justify-content: center; }
#progress-bar { width: 100%; }
#console-wrapper { width: 100%; }
#console { height: 150px; font-size: 11px; }
#buttons { gap: 6px; }
#buttons button { padding: 10px 14px; font-size: 13px; }
}
</style>
</head>
<body>
<h1>Pebble Emulator</h1>
<p style="color: #999; font-size: 13px; margin: -5px 0 12px 0; max-width: 600px; line-height: 1.5;">Runs entirely in your browser — no server, no install. QEMU is compiled to WebAssembly, emulating the original Pebble ARM hardware and booting real PebbleOS firmware. Tested on desktop, doesn't work well on mobile yet.</p>
<div id="controls">
<label for="fw-select">Firmware:</label>
<select id="fw-select">
<option value="full" selected>Full PebbleOS</option>
<option value="sdk">SDK PebbleOS</option>
</select>
<button id="btn-boot">Boot</button>
<span style="font-size: 12px; color: #888; margin-left: 8px;">May take 2-4 mins to boot</span>
</div>
<div id="status">Select firmware and click Boot</div>
<div id="progress-bar"><div id="progress-fill"></div></div>
<div id="fps-counter" style="font-size: 12px; color: #4cc9f0; margin-bottom: 5px;">FPS: --</div>
<div id="display-wrapper">
<canvas id="canvas" width="200" height="228"></canvas>
</div>
<div id="buttons">
<button id="btn-back" title="Back (Escape)">Back</button>
<button id="btn-up" title="Up (Arrow Up)">Up</button>
<button id="btn-select" title="Select (Enter)">Select</button>
<button id="btn-down" title="Down (Arrow Down)">Down</button>
</div>
<div class="key-hint">Keys: Left=Back, Up/Down=Navigate, Right=Select</div>
<div id="console-wrapper">
<h3>Serial Console</h3>
<div id="console"></div>
</div>
<div style="margin-top: 15px; font-size: 11px; color: #666;">
<a href="https://github.com/ericmigi/pebble-qemu-wasm" style="color: #4cc9f0; text-decoration: none;">Source on GitHub</a>
</div>
<script>
var ASSET_BASE = 'web/';
var statusEl = document.getElementById('status');
var consoleEl = document.getElementById('console');
var progressBar = document.getElementById('progress-bar');
var progressFill = document.getElementById('progress-fill');
var bootBtn = document.getElementById('btn-boot');
var fwSelect = document.getElementById('fw-select');
// Default to SDK firmware on mobile (smaller, faster boot)
if (window.innerWidth <= 640) {
fwSelect.value = 'sdk';
}
// URL parameter support (e.g. ?fw=sdk&shift=0)
var params = new URLSearchParams(window.location.search);
if (params.has('fw')) {
fwSelect.value = params.get('fw');
}
// icount shift parameter: ?shift=0..10, ?shift=auto, ?shift=off
var shiftParam = params.get('shift');
function buildIcountArgs() {
if (shiftParam === 'off') return [];
if (shiftParam !== null && /^(\d+|auto)$/.test(shiftParam)) {
return ['-icount', 'shift=' + shiftParam];
}
return []; // default: no icount (wall-clock time)
}
function ts() {
var d = new Date();
return d.toTimeString().slice(0, 8) + '.' +
String(d.getMilliseconds()).padStart(3, '0');
}
function log(msg) {
console.log(msg);
consoleEl.textContent += ts() + ' ' + msg + '\n';
if (consoleEl.textContent.length > 100000) {
consoleEl.textContent = consoleEl.textContent.slice(-50000);
}
consoleEl.scrollTop = consoleEl.scrollHeight;
}
function setStatus(msg) {
statusEl.textContent = msg;
log('[status] ' + msg);
}
function showProgress(pct) {
progressBar.style.display = 'block';
progressFill.style.width = pct + '%';
}
function hideProgress() {
progressBar.style.display = 'none';
}
async function fetchWithProgress(url, label, expectedSize) {
var resp = await fetch(url);
if (!resp.ok) throw new Error(label + ': HTTP ' + resp.status);
var reader = resp.body.getReader();
var total = parseInt(resp.headers.get('content-length')) || expectedSize;
var received = 0;
var chunks = [];
while (true) {
var result = await reader.read();
if (result.done) break;
chunks.push(result.value);
received += result.value.length;
if (total) {
var pct = Math.round(received / total * 100);
setStatus(label + '... ' + Math.round(received / 1024) + 'KB');
showProgress(pct);
}
}
hideProgress();
var data = new Uint8Array(received);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
data.set(chunks[i], offset);
offset += chunks[i].length;
}
return data;
}
// QEMU stderr noise filter — ported from boot_with_logs.sh
var QEMU_NOISE = [
'write 0x', 'read 0x', // register access spam
'DMA:', 'dma:', // DMA transfer details
'unimp', // unimplemented stubs
'guest_errors', // harmless guest errors
'CPU AS read', 'CPU AS write', // CPU address space reads
'DEBUG: CPU AS', // CPU address space debug
'CS changed to', // display chip-select toggles
'cmd=', 'cmd_set=', // display command details
'ps_display_execute_current_cmd', // display command dispatch
'state change from', // display state machine transitions
'Frame data start', // frame data start
'Asserting done interrupt', // display interrupt
'Resetting state to accept', // display state reset
'received scene ID', // scene details
'pebble_control_write: bytes:', // control protocol hex dumps
'pebble_control_write: qemu_chr', // control write confirmations
'exception', 'Exception', // ARMv7M exception traces
'unsupported', // unsupported feature warnings
'Not implemented', // unimplemented stubs
];
var DISPLAY_SHOW = [
'Executing command:',
'Exiting programming mode',
'determine_command_set:',
'Got last byte in frame',
];
function matchesAny(text, patterns) {
for (var i = 0; i < patterns.length; i++) {
if (text.indexOf(patterns[i]) >= 0) return true;
}
return false;
}
function filterAndLog(text) {
if (!text || text.indexOf('...') === 0) return;
// Condense frame renders
if (text.indexOf('Got last byte in frame') >= 0) {
var bi = text.indexOf('bytes:');
if (bi >= 0) {
log('Display: frame rendered (' + text.slice(bi + 6).trim() + ' total bytes)');
}
return;
}
// Display events — show meaningful ones, drop noise
if (text.indexOf('PEBBLE_SNOWY_DISPLAY:') >= 0) {
if (matchesAny(text, DISPLAY_SHOW)) {
log(text.replace('PEBBLE_SNOWY_DISPLAY: ', 'Display: '));
} else if (!matchesAny(text, QEMU_NOISE)) {
log(text);
}
return;
}
// Control events — show packet sends, drop noise
if (text.indexOf('PEBBLE_CONTROL:') >= 0) {
if (text.indexOf('Sending packet') >= 0) {
log(text.replace('PEBBLE_CONTROL: pebble_control_write: ', 'Control: '));
} else if (!matchesAny(text, QEMU_NOISE)) {
log(text);
}
return;
}
// General noise filter
if (matchesAny(text, QEMU_NOISE)) return;
log('[err] ' + text);
}
var runtimeReady = false;
var Module = {
canvas: document.getElementById('canvas'),
noInitialRun: false,
arguments: [
'-machine', 'pebble-snowy-emery-bb',
'-display', 'none',
'-monitor', 'none',
'-parallel', 'none',
'-kernel', '/firmware/qemu_micro_flash.bin',
'-drive', 'if=none,id=spi-flash,file=/firmware/qemu_spi_flash.bin,format=raw',
'-serial', 'null',
'-serial', 'null',
'-serial', 'file:/tmp/pebble_serial.log',
].concat(buildIcountArgs()),
print: function(text) {
log(text);
},
printErr: function(text) {
filterAndLog(text);
},
onRuntimeInitialized: function() {
setStatus('QEMU runtime initialized, booting Pebble firmware...');
runtimeReady = true;
},
locateFile: function(path) {
return ASSET_BASE + path;
},
preRun: [],
};
bootBtn.addEventListener('click', function() {
bootBtn.disabled = true;
fwSelect.disabled = true;
bootEmulator();
});
// Auto-boot via URL parameter (e.g. ?fw=sdk&auto)
if (params.has('auto')) {
bootBtn.click();
}
async function bootEmulator() {
var variant = fwSelect.value;
var fwBase = ASSET_BASE + 'firmware/' + variant + '/';
try {
setStatus('Fetching micro flash (' + variant + ')...');
var microData = await fetchWithProgress(
fwBase + 'qemu_micro_flash.bin', 'Micro flash', 968704
);
log('Downloaded micro flash: ' + microData.length + ' bytes');
setStatus('Fetching SPI flash (16MB)...');
var spiData = await fetchWithProgress(
fwBase + 'qemu_spi_flash.bin', 'SPI flash', 16777216
);
log('Downloaded SPI flash: ' + spiData.length + ' bytes');
Module.preRun.push(function() {
try { FS.mkdir('/firmware'); } catch(e) {}
try { FS.mkdir('/tmp'); } catch(e) {}
// Pass browser timezone offset to RTC code
// getTimezoneOffset() returns minutes west of UTC (positive = behind UTC)
// We need seconds east of UTC (negative = behind UTC)
var offsetSec = -new Date().getTimezoneOffset() * 60;
ENV.TZ_OFFSET_SEC = String(offsetSec);
FS.writeFile('/firmware/qemu_micro_flash.bin', microData);
FS.writeFile('/firmware/qemu_spi_flash.bin', spiData);
log('Firmware written to virtual filesystem (' + variant + ')');
});
var icountArgs = buildIcountArgs();
log('[config] icount: ' + (icountArgs.length ? icountArgs[1] : 'off'));
setStatus('Loading QEMU WASM module (17MB)...');
var script = document.createElement('script');
script.src = ASSET_BASE + 'qemu-system-arm.js';
script.onerror = function() {
setStatus('Failed to load qemu-system-arm.js');
};
document.body.appendChild(script);
} catch(e) {
setStatus('Error: ' + e.message);
log(e.stack || e.toString());
bootBtn.disabled = false;
fwSelect.disabled = false;
}
}
// ================================================================
// Framebuffer rendering
// ================================================================
var lastFrameCount = 0;
var totalFrames = 0;
var canvasCtx = document.getElementById('canvas').getContext('2d');
// FPS measurement (3-second window, fractional for sub-1 rates)
var fpsFrameCount = 0;
var fpsLastTime = performance.now();
var currentFps = 0;
var fpsEl = document.getElementById('fps-counter');
window.pebbleFps = function() { return currentFps; };
// Cached ImageData — reused across frames to avoid allocation per render
var cachedImgData = null;
var cachedWidth = 0;
var cachedHeight = 0;
function renderLoop() {
if (!runtimeReady) return;
try {
var frameCount = Module._pebble_display_frame_count();
if (frameCount === lastFrameCount) return;
lastFrameCount = frameCount;
totalFrames++;
fpsFrameCount++;
var now = performance.now();
var elapsed = now - fpsLastTime;
if (elapsed >= 3000) {
currentFps = Math.round(fpsFrameCount / (elapsed / 1000) * 10) / 10;
fpsEl.textContent = 'FPS: ' + currentFps.toFixed(1);
console.log('[fps] ' + currentFps.toFixed(1));
fpsFrameCount = 0;
fpsLastTime = now;
}
var width = Module._pebble_display_width();
var height = Module._pebble_display_height();
var stride = Module._pebble_display_stride();
var dataPtr = Module._pebble_display_data();
if (!dataPtr || !width || !height) return;
if (totalFrames === 1) {
setStatus('Display active: ' + width + 'x' + height);
}
// Reuse ImageData across frames (avoid GC pressure)
if (!cachedImgData || cachedWidth !== width || cachedHeight !== height) {
cachedImgData = canvasCtx.createImageData(width, height);
cachedWidth = width;
cachedHeight = height;
}
// Bulk pixel copy using Uint32Array for ~4x fewer writes
// Source: BGRA (heap[s]=B, [s+1]=G, [s+2]=R)
// Dest: RGBA ImageData, but as Uint32 on little-endian: 0xAABBGGRR
var dst32 = new Uint32Array(cachedImgData.data.buffer);
var heap = Module.HEAPU8;
for (var y = 0; y < height; y++) {
var rowSrc = dataPtr + y * stride;
var rowDst = y * width;
for (var x = 0; x < width; x++) {
var s = rowSrc + x * 4;
dst32[rowDst + x] = heap[s+2] | (heap[s+1] << 8) | (heap[s] << 16) | 0xFF000000;
}
}
canvasCtx.putImageData(cachedImgData, 0, 0);
} catch(e) {}
}
setInterval(renderLoop, 16);
// ================================================================
// Firmware serial log parser (UART protocol from serial2)
// Ported from boot_with_logs.sh process_serial()
// ================================================================
var serialReadPos = 0;
var serialBuf = new Uint8Array(0);
var SYNC = [0x03, 0x50, 0x21];
var MARKER = [0x2a, 0x2a];
function findBytes(buf, pattern, start) {
for (var i = start; i <= buf.length - pattern.length; i++) {
var match = true;
for (var j = 0; j < pattern.length; j++) {
if (buf[i + j] !== pattern[j]) { match = false; break; }
}
if (match) return i;
}
return -1;
}
function parseSerialFrames() {
while (true) {
var idx = findBytes(serialBuf, SYNC, 0);
if (idx < 0) {
if (serialBuf.length > 512) {
serialBuf = serialBuf.slice(serialBuf.length - 512);
}
break;
}
var star = findBytes(serialBuf, MARKER, idx);
if (star < 0) break;
// Skip \x01 padding after **
var pos = star + 2;
while (pos < serialBuf.length && serialBuf[pos] === 0x01) pos++;
if (pos >= serialBuf.length) break;
// Find next sync (end of this frame)
var nextSync = findBytes(serialBuf, SYNC, pos);
if (nextSync < 0) {
if (serialBuf.length - pos > 4096) {
serialBuf = serialBuf.slice(pos);
}
break;
}
// Strip trailing padding
var end = nextSync;
while (end > pos && serialBuf[end - 1] === 0x55) end--;
if (end - pos >= 4) end -= 3;
// Extract printable text from payload
var text = '';
for (var i = pos; i < end; i++) {
var b = serialBuf[i];
if ((b >= 32 && b <= 126) || b === 9 || b === 10 || b === 13) {
text += String.fromCharCode(b);
}
}
text = text.trim();
serialBuf = serialBuf.slice(nextSync);
if (text.length >= 2) {
log('FIRM | ' + text);
}
}
}
function pollSerialLog() {
if (!runtimeReady) return;
try {
var stat = FS.stat('/tmp/pebble_serial.log');
if (stat.size <= serialReadPos) return;
var stream = FS.open('/tmp/pebble_serial.log', 'r');
var newBytes = stat.size - serialReadPos;
var chunk = new Uint8Array(newBytes);
FS.read(stream, chunk, 0, newBytes, serialReadPos);
FS.close(stream);
serialReadPos = stat.size;
// Append to parse buffer
var combined = new Uint8Array(serialBuf.length + chunk.length);
combined.set(serialBuf);
combined.set(chunk, serialBuf.length);
serialBuf = combined;
parseSerialFrames();
} catch(e) {
// File doesn't exist yet during early boot
}
}
setInterval(pollSerialLog, 200);
// ================================================================
// Button input
// ================================================================
var buttonState = 0;
var BUTTON_BACK = 1 << 0;
var BUTTON_UP = 1 << 1;
var BUTTON_SELECT = 1 << 2;
var BUTTON_DOWN = 1 << 3;
var keyMap = {
'ArrowLeft': BUTTON_BACK,
'ArrowUp': BUTTON_UP,
'ArrowRight': BUTTON_SELECT,
'ArrowDown': BUTTON_DOWN,
'Escape': BUTTON_BACK,
'Backspace': BUTTON_BACK,
'Enter': BUTTON_SELECT,
};
var buttonStateAddr = 0;
function updateButtons(bit, pressed) {
if (pressed) {
buttonState |= bit;
} else {
buttonState &= ~bit;
}
if (!runtimeReady) return;
if (buttonStateAddr) {
Atomics.store(Module.HEAPU32, buttonStateAddr, buttonState);
} else if (Module._pebble_button_state_addr) {
var addr = Module._pebble_button_state_addr();
if (addr) {
buttonStateAddr = addr >> 2;
Atomics.store(Module.HEAPU32, buttonStateAddr, buttonState);
log('[button] Direct memory at 0x' + addr.toString(16));
}
}
}
var keyHoldTimers = {};
// With icount, CPU is slow so keyup needs a long delay for firmware to register.
// Without icount, CPU runs at real-time so release immediately.
var useIcount = shiftParam !== 'off' && shiftParam !== null;
var keyUpDelay = useIcount ? 1000 : 0;
document.addEventListener('keydown', function(e) {
var bit = keyMap[e.key];
if (bit !== undefined) {
e.preventDefault();
if (e.repeat) return;
updateButtons(bit, true);
if (keyHoldTimers[e.key]) clearTimeout(keyHoldTimers[e.key]);
keyHoldTimers[e.key] = null;
}
});
document.addEventListener('keyup', function(e) {
var bit = keyMap[e.key];
if (bit !== undefined) {
e.preventDefault();
if (keyHoldTimers[e.key]) clearTimeout(keyHoldTimers[e.key]);
if (keyUpDelay > 0) {
keyHoldTimers[e.key] = setTimeout(function() {
updateButtons(bit, false);
keyHoldTimers[e.key] = null;
}, keyUpDelay);
} else {
updateButtons(bit, false);
}
}
});
var btnMap = {
'btn-back': BUTTON_BACK,
'btn-up': BUTTON_UP,
'btn-select': BUTTON_SELECT,
'btn-down': BUTTON_DOWN,
};
Object.keys(btnMap).forEach(function(id) {
var el = document.getElementById(id);
var bit = btnMap[id];
el.addEventListener('mousedown', function(e) {
e.preventDefault();
el.classList.add('pressed');
updateButtons(bit, true);
});
el.addEventListener('mouseup', function(e) {
el.classList.remove('pressed');
updateButtons(bit, false);
});
el.addEventListener('mouseleave', function(e) {
el.classList.remove('pressed');
updateButtons(bit, false);
});
el.addEventListener('touchstart', function(e) {
e.preventDefault();
el.classList.add('pressed');
updateButtons(bit, true);
});
el.addEventListener('touchend', function(e) {
el.classList.remove('pressed');
updateButtons(bit, false);
});
});
</script>
</body>
</html>