-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrs80-iframe.html
More file actions
855 lines (762 loc) · 41.8 KB
/
trs80-iframe.html
File metadata and controls
855 lines (762 loc) · 41.8 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TRS-80 CoCo Emulator (Iframe)</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000;
overflow: hidden;
}
#xroar-container {
width: 100%;
height: 100vh;
position: relative;
}
#xroar-iframe {
width: 100%;
height: 100%;
border: none;
background-color: #000;
}
.tabs-container {display: none !important;}
#status {
position: fixed;
top: 10px;
left: 10px;
background-color: rgba(0, 0, 0, 0.8);
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
color: #fff;
z-index: 1000;
font-family: monospace;
}
</style>
</head>
<body>
<div id="status">Loading TRS-80 CoCo emulator...</div>
<div id="xroar-container">
<iframe id="xroar-iframe" allow="fullscreen"></iframe>
</div>
<script>
// Get URL parameters from parent page
const urlParams = new URLSearchParams(window.location.search);
// Map our machine names to xroar machine names
// xroar uses names like: cocous (CoCo 2 NTSC), coco2p (CoCo 2 PAL), coco3 (CoCo 3), etc.
const machineParam = urlParams.get('machine') || 'cocous'; // Default to CoCo 2 NTSC (cocous)
const loadParam = urlParams.get('load');
// Build xroar URL
// xroar should be symlinked or copied into 8bitworkshop/xroar
// So from trs80-iframe.html, the path is ./xroar/xroar-wasm.html
// Pass machine as a command-line argument via URL parameter starting with '-'
let xroarUrl = './xroar/xroar-wasm.html';
const urlParamsArray = [];
// xroar-wasm.html reads URL params starting with '-' and adds them to Module.arguments
// Use -default-machine to set the machine before initialization
if (machineParam) {
urlParamsArray.push('-default-machine=' + encodeURIComponent(machineParam));
}
if (loadParam) {
urlParamsArray.push('load=' + encodeURIComponent(loadParam));
}
if (urlParamsArray.length > 0) {
xroarUrl += '?' + urlParamsArray.join('&');
}
// Debug: log the URL we're trying to load
console.log('TRS-80 iframe: Loading xroar from:', xroarUrl);
// Set up iframe
const xroarIframe = document.getElementById('xroar-iframe');
let iframeLoaded = false;
let moduleReady = false;
let lastLoadedFile = null;
let lastLoadedType = null;
let checkCount = 0;
// SDL Scancode mapping for common keys
// Based on SDL scancodes (SDL_scancode.h)
const SCANCODE_MAP = {
'Enter': 40, // SDL_SCANCODE_RETURN
'Return': 40,
' ': 44, // SDL_SCANCODE_SPACE
'Backspace': 42, // SDL_SCANCODE_BACKSPACE
'Tab': 43, // SDL_SCANCODE_TAB
'Escape': 41, // SDL_SCANCODE_ESCAPE
'ArrowUp': 82, // SDL_SCANCODE_UP
'ArrowDown': 81, // SDL_SCANCODE_DOWN
'ArrowLeft': 80, // SDL_SCANCODE_LEFT
'ArrowRight': 79, // SDL_SCANCODE_RIGHT
};
// Map ASCII characters to SDL scancodes
function charToScancode(char) {
const upper = char.toUpperCase();
// Letters A-Z
if (upper >= 'A' && upper <= 'Z') {
return 4 + (upper.charCodeAt(0) - 'A'.charCodeAt(0)); // SDL_SCANCODE_A = 4
}
// Numbers 0-9
if (char >= '0' && char <= '9') {
return 30 + (char.charCodeAt(0) - '0'.charCodeAt(0)); // SDL_SCANCODE_1 = 30
}
// Special characters
const special = {
'!': 30, '@': 31, '#': 32, '$': 33, '%': 34, '^': 35, '&': 36, '*': 37, '(': 38, ')': 39,
'-': 45, '_': 45, '=': 46, '+': 46,
'[': 47, '{': 47, ']': 48, '}': 48,
'\\': 49, '|': 49,
';': 51, ':': 51, "'": 52, '"': 52,
'`': 53, '~': 53,
',': 54, '<': 54, '.': 55, '>': 55, '/': 56, '?': 56
};
if (special[char]) return special[char];
return null;
}
// Send keyboard input to xroar emulator
function sendKeyboardInput(xroarWindow, command) {
try {
if (!xroarWindow || !xroarWindow.Module) {
console.warn('TRS-80 iframe: xroar Module not available');
return;
}
const Module = xroarWindow.Module;
if (!Module.ccall) {
console.warn('TRS-80 iframe: Module.ccall not available');
return;
}
console.log('TRS-80 iframe: Sending keyboard command:', command);
// Send each character as scancode
for (let i = 0; i < command.length; i++) {
const char = command[i];
let scancode = SCANCODE_MAP[char] || charToScancode(char);
if (scancode !== null) {
// Press key
Module.ccall('wasm_scan_press', null, ['number'], [scancode]);
// Small delay
setTimeout(() => {
// Release key
Module.ccall('wasm_scan_release', null, ['number'], [scancode]);
}, 50);
} else if (char === '\n') {
// Enter key
Module.ccall('wasm_scan_press', null, ['number'], [40]);
setTimeout(() => {
Module.ccall('wasm_scan_release', null, ['number'], [40]);
}, 50);
}
}
console.log('TRS-80 iframe: Sent keyboard command via scancodes');
} catch (e) {
console.error('TRS-80 iframe: Error sending keyboard command:', e);
}
}
// Send keyboard input character by character with delays
function sendKeyboardInputCharacterByCharacter(xroarWindow, command) {
try {
if (!xroarWindow || !xroarWindow.Module) {
console.warn('TRS-80 iframe: xroar Module not available');
return;
}
const Module = xroarWindow.Module;
if (!Module.ccall) {
console.warn('TRS-80 iframe: Module.ccall not available');
return;
}
console.log('TRS-80 iframe: Sending keyboard command character by character:', command);
let index = 0;
const sendNextChar = () => {
if (index >= command.length) {
console.log('TRS-80 iframe: Finished sending command');
return;
}
const char = command[index];
let scancode = SCANCODE_MAP[char] || charToScancode(char);
if (scancode !== null) {
// Press key
Module.ccall('wasm_scan_press', null, ['number'], [scancode]);
// Release after short delay
setTimeout(() => {
Module.ccall('wasm_scan_release', null, ['number'], [scancode]);
index++;
setTimeout(sendNextChar, 100); // Delay between characters
}, 50);
} else if (char === '\n') {
// Enter key
Module.ccall('wasm_scan_press', null, ['number'], [40]);
setTimeout(() => {
Module.ccall('wasm_scan_release', null, ['number'], [40]);
index++;
setTimeout(sendNextChar, 100);
}, 50);
} else {
// Skip unknown characters
index++;
setTimeout(sendNextChar, 50);
}
};
sendNextChar();
} catch (e) {
console.error('TRS-80 iframe: Error sending keyboard command:', e);
}
}
// Load file into xroar via MEMFS
function loadFileIntoXroar(xroarWindow, data, filename, loadType) {
try {
if (!xroarWindow || !xroarWindow.Module) {
console.warn('TRS-80 iframe: xroar Module not available');
return false;
}
const Module = xroarWindow.Module;
if (!Module.FS || !Module.ccall) {
console.warn('TRS-80 iframe: Module.FS or Module.ccall not available');
return false;
}
console.log('TRS-80 iframe: Loading file into xroar:', filename, 'loadType:', loadType);
// Write file to MEMFS
const uint8Array = new Uint8Array(data);
Module.FS.writeFile(filename, uint8Array);
console.log('TRS-80 iframe: Wrote file to MEMFS:', filename, 'size:', uint8Array.length);
// Load file using wasm_load_file
// loadType: 0=load, 1=run, 2=tape, 3=disk, 4=text, 5=hd
Module.ccall('wasm_load_file', null, ['string', 'number', 'number'], [filename, loadType, 0]);
console.log('TRS-80 iframe: Called wasm_load_file with loadType:', loadType);
return true;
} catch (e) {
console.error('TRS-80 iframe: Error loading file into xroar:', e);
return false;
}
}
// Process loaded file and auto-execute if needed
function processLoadedFile(xroarWindow, contentType, filename) {
console.log('TRS-80 iframe: Processing loaded file:', filename, 'contentType:', contentType);
// For plain text BASIC files we now use loadType 1 (run) so xroar
// auto-detects and autoruns ASCII BASIC; no need to send RUN.
if (contentType === 'text/plain' || filename.endsWith('.bas')) {
console.log('TRS-80 iframe: Plain text BASIC detected - relying on xroar autorun');
} else if (contentType.includes('basic-cas') || filename.endsWith('.cas')) {
// For CAS files loaded as tape, need to CLOAD first
console.log('TRS-80 iframe: CAS file detected, will send CLOAD then RUN');
setTimeout(() => {
sendKeyboardInputCharacterByCharacter(xroarWindow, 'CLOAD\n');
setTimeout(() => {
sendKeyboardInputCharacterByCharacter(xroarWindow, 'RUN\n');
}, 5000);
}, 3000);
} else if (contentType.includes('binary') || filename.endsWith('.bin')) {
console.log('TRS-80 iframe: Compiled binary detected, will send EXEC command');
// For binary files loaded with loadType 1 (run), xroar should auto-execute
// But if not, send EXEC command
// Note: Soft reset is done immediately after loading (see loadFileIntoXroar call site)
setTimeout(() => {
sendKeyboardInputCharacterByCharacter(xroarWindow, 'EXEC\n');
}, 2000);
}
}
// Toggle emulator pause using the same key combo as the desktop build:
// Ctrl+Shift+H. The wasm build already maps this to the pause toggle,
// and we can synthesize it via SDL scancodes.
function togglePause(xroarWindow) {
try {
if (!xroarWindow || !xroarWindow.Module) {
console.warn('TRS-80 iframe: xroar Module not available for pause');
return;
}
const Module = xroarWindow.Module;
if (!Module.ccall) {
console.warn('TRS-80 iframe: Module.ccall not available for pause');
return;
}
// SDL scancodes: LCTRL=224, LSHIFT=225, H=11 (A=4 .. Z)
const CTRL_SCANCODE = 224;
const SHIFT_SCANCODE = 225;
const H_SCANCODE = 11;
console.log('TRS-80 iframe: Toggling pause via Ctrl+Shift+H scancodes');
// Press modifiers then H, then release in reverse order
Module.ccall('wasm_scan_press', null, ['number'], [CTRL_SCANCODE]);
Module.ccall('wasm_scan_press', null, ['number'], [SHIFT_SCANCODE]);
Module.ccall('wasm_scan_press', null, ['number'], [H_SCANCODE]);
// Short delay before releasing keys to ensure the combo is registered
setTimeout(() => {
Module.ccall('wasm_scan_release', null, ['number'], [H_SCANCODE]);
Module.ccall('wasm_scan_release', null, ['number'], [SHIFT_SCANCODE]);
Module.ccall('wasm_scan_release', null, ['number'], [CTRL_SCANCODE]);
}, 50);
} catch (e) {
console.error('TRS-80 iframe: Error toggling pause:', e);
}
}
// Send reset command
function sendReset(xroarWindow) {
try {
if (!xroarWindow || !xroarWindow.Module) {
console.warn('TRS-80 iframe: xroar Module not available for reset');
return;
}
const Module = xroarWindow.Module;
if (!Module.ccall) {
console.warn('TRS-80 iframe: Module.ccall not available for reset');
return;
}
console.log('TRS-80 iframe: Sending soft reset');
Module.ccall('xroar_soft_reset', null, [], []);
// Reload last file if available
if (lastLoadedFile && lastLoadedType !== null) {
setTimeout(() => {
loadFileIntoXroar(xroarWindow, lastLoadedFile, 'program', lastLoadedType);
processLoadedFile(xroarWindow, 'application/x-coco-basic', 'program');
}, 1000);
}
} catch (e) {
console.error('TRS-80 iframe: Error sending reset:', e);
}
}
// Update status
function updateStatus(message) {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.textContent = message;
statusEl.style.display = 'block';
if (message.includes('ready') || message.includes('loaded')) {
setTimeout(() => {
statusEl.style.display = 'none';
}, 2000);
}
}
}
// Check if Module is ready
function checkModuleReady() {
const xroarWindow = xroarIframe.contentWindow;
if (!xroarWindow) {
return false;
}
// Try to access Module from window
// Emscripten exposes Module on the window object
let Module = null;
try {
// Try window.Module (Emscripten standard)
// Note: In xroar-wasm.html, Module is defined as 'var Module' which might not be on window
// But Emscripten should expose it. Try multiple ways to access it.
Module = xroarWindow.Module;
// If not found, try accessing via the iframe's document context
if (!Module && xroarWindow.document) {
try {
// Try to access Module from the iframe's global scope
const scripts = Array.from(xroarWindow.document.querySelectorAll('script'));
// Check if xroar.js has loaded by looking for Module in the iframe's scope
// This is tricky due to same-origin policy, but we can try
} catch (e) {
// Cross-origin or other error
}
}
// Also check if wasm_load_file exists (created in onRuntimeInitialized)
const hasWasmLoadFile = typeof xroarWindow.wasm_load_file === 'function';
// Check if Module has the required properties
if (Module && typeof Module.ccall === 'function' && Module.FS) {
// Also check if onRuntimeInitialized has been called
// by checking if wasm_load_file exists
if (hasWasmLoadFile || (Module.ready !== undefined)) {
if (!moduleReady) {
moduleReady = true;
console.log('TRS-80 iframe: Module is ready');
console.log('TRS-80 iframe: Module properties:', {
hasCcall: typeof Module.ccall === 'function',
hasFS: !!Module.FS,
hasCwrap: typeof Module.cwrap === 'function',
hasWasmLoadFile: hasWasmLoadFile,
ready: Module.ready
});
updateStatus('TRS-80 CoCo emulator ready');
// Machine should already be set via -default-machine URL parameter
// But we can verify/set it again if needed
if (machineParam && typeof Module.ccall === 'function') {
try {
// wasm_set_machine_cart(machine, cart, cart_rom, cart_rom2)
Module.ccall('wasm_set_machine_cart', null, ['string', 'string', 'string', 'string'],
[machineParam, null, null, null]);
// Hard reset is required after changing machine (per xroar comment)
Module.ccall('xroar_hard_reset', null, [], []);
console.log('TRS-80 iframe: Verified/set machine to:', machineParam, 'and performed hard reset');
} catch (e) {
console.error('TRS-80 iframe: Failed to set machine:', e);
}
}
// Notify parent window
if (window.parent) {
window.parent.postMessage({
type: 'emulator_ready',
platform: 'trs80'
}, '*');
}
}
return true;
} else {
// Module exists but onRuntimeInitialized hasn't been called yet
if (checkCount % 10 === 0) { // Log every 10 checks
console.log('TRS-80 iframe: Module exists but onRuntimeInitialized not called yet');
}
}
} else if (Module) {
// Module exists but not fully initialized
if (checkCount % 10 === 0) { // Log every 10 checks
console.log('TRS-80 iframe: Module exists but not ready:', {
hasCcall: typeof Module.ccall === 'function',
hasFS: !!Module.FS,
hasCwrap: typeof Module.cwrap === 'function'
});
}
} else {
// Module doesn't exist yet
if (checkCount % 20 === 0) { // Log every 20 checks
console.log('TRS-80 iframe: Module not found yet, xroarWindow:', !!xroarWindow);
}
}
} catch (e) {
// Cross-origin error or other issue
if (checkCount % 20 === 0) { // Log every 20 checks
console.log('TRS-80 iframe: Error checking Module (may be cross-origin):', e.message);
}
}
return false;
}
// Set up load event listener
xroarIframe.addEventListener('load', function() {
console.log('TRS-80 iframe: xroar iframe loaded');
console.log('TRS-80 iframe: xroar iframe src:', xroarIframe.src);
iframeLoaded = true;
// Also listen for errors on the iframe
xroarIframe.addEventListener('error', function(e) {
console.error('TRS-80 iframe: Error in xroar iframe:', e);
});
// Try to hide any UI elements below the main canvas inside the iframe
function hideInnerUI() {
try {
const xroarWindow = xroarIframe.contentWindow;
const doc = xroarWindow && xroarWindow.document;
if (!doc) return;
const canvas = doc.querySelector('canvas');
if (!canvas) return;
// Hide all siblings of the canvas within its container
let container = canvas.parentElement;
while (container && container !== doc.body) {
Array.from(container.children).forEach((child) => {
if (child !== canvas) {
child.style.display = 'none';
}
});
container = container.parentElement;
}
// Additionally hide obvious controls like selects and buttons
doc.querySelectorAll('select, button, input, .controls, .tabs-container').forEach((el) => {
if (!el.closest('canvas')) {
el.style.display = 'none';
}
});
} catch (e) {
console.warn('TRS-80 iframe: Could not hide inner UI elements:', e);
}
}
// Wait longer for xroar.js to load (Emscripten scripts can take time)
// Check immediately and then periodically
const initialCheck = () => {
// First, check if xroar.js loaded and what's available
const xroarWindow = xroarIframe.contentWindow;
console.log('TRS-80 iframe: Checking xroar window:', {
exists: !!xroarWindow,
Module: !!xroarWindow?.Module,
wasm_load_file: typeof xroarWindow?.wasm_load_file,
document: !!xroarWindow?.document,
location: xroarWindow?.location?.href
});
// Check if there are any script errors or if scripts loaded
if (xroarWindow?.document) {
// Attempt to hide inner UI soon after the document is available
setTimeout(hideInnerUI, 1000);
// Wait a bit more for scripts to load, then check again
setTimeout(() => {
const scripts = xroarWindow.document.querySelectorAll('script');
console.log('TRS-80 iframe: Scripts in xroar (after delay):', scripts.length);
let xroarJsLoaded = false;
let xroarJsError = false;
scripts.forEach((script, i) => {
if (script.src) {
console.log(`TRS-80 iframe: Script ${i}:`, script.src);
if (script.src.includes('xroar.js')) {
xroarJsLoaded = true;
// Check if script has loaded
console.log(`TRS-80 iframe: xroar.js script element found, readyState:`, script.readyState);
// Check for onerror
script.onerror = function() {
console.error('TRS-80 iframe: xroar.js failed to load!');
xroarJsError = true;
};
}
} else if (script.textContent && script.textContent.includes('var Module')) {
console.log(`TRS-80 iframe: Found inline script with Module definition`);
}
});
if (!xroarJsLoaded) {
console.warn('TRS-80 iframe: xroar.js script tag not found in DOM!');
console.warn('TRS-80 iframe: This might mean:');
console.warn(' 1. xroar.js hasn\'t loaded yet');
console.warn(' 2. Script is added dynamically');
console.warn(' 3. Script failed to load (check Network tab)');
// Check all script tags again (including those without src)
const allScripts = xroarWindow.document.querySelectorAll('script');
console.log('TRS-80 iframe: All script tags:', allScripts.length);
allScripts.forEach((script, i) => {
console.log(`TRS-80 iframe: Script ${i}:`, {
src: script.src || '(inline)',
type: script.type,
async: script.async,
defer: script.defer
});
});
// Try to manually check if xroar.js is accessible
const xroarJsUrl = xroarWindow.location.href.replace('xroar-wasm.html', 'xroar.js');
console.warn('TRS-80 iframe: Expected xroar.js URL:', xroarJsUrl);
// Try to fetch it (from parent window, not iframe)
fetch(xroarJsUrl, { method: 'HEAD' })
.then(response => {
console.log('TRS-80 iframe: xroar.js HEAD request result:', response.status, response.ok);
if (!response.ok) {
console.error('TRS-80 iframe: xroar.js returned status:', response.status);
}
})
.catch(error => {
console.error('TRS-80 iframe: xroar.js not accessible:', error);
console.error('TRS-80 iframe: This might be a CORS issue or file not found');
});
} else {
console.log('TRS-80 iframe: xroar.js script tag found!');
}
}, 3000); // Wait 3 seconds for scripts to load and execute
// Also check for Module periodically (Emscripten takes time to initialize)
// Check for errors in console (we can't access them directly, but we can check if Module exists)
// Also try to access Module via the iframe's execution context
setTimeout(() => {
try {
// Try to execute code in the iframe's context to check for Module
const testResult = xroarWindow.eval('typeof Module !== "undefined" ? "Module exists" : "Module not found"');
console.log('TRS-80 iframe: eval test result (after 3s):', testResult);
// Try to get Module directly
const moduleTest = xroarWindow.eval('typeof Module');
console.log('TRS-80 iframe: typeof Module in iframe (after 3s):', moduleTest);
if (moduleTest !== 'undefined') {
// Module exists, try to access it
const m = xroarWindow.eval('Module');
console.log('TRS-80 iframe: Module object found!', {
hasCcall: typeof m?.ccall === 'function',
hasFS: !!m?.FS,
hasCwrap: typeof m?.cwrap === 'function'
});
// Also check window.Module
if (xroarWindow.Module) {
console.log('TRS-80 iframe: Module also accessible via xroarWindow.Module');
}
} else {
console.warn('TRS-80 iframe: Module still not found after 3 seconds');
console.warn('TRS-80 iframe: Please check:');
console.warn(' 1. Network tab - is xroar.js loading? (status 200?)');
console.warn(' 2. Console tab - are there any script errors?');
console.warn(' 3. Is xroar.js accessible at:', xroarWindow.location.href.replace('xroar-wasm.html', 'xroar.js'));
}
} catch (e) {
console.warn('TRS-80 iframe: Cannot eval in iframe (may be cross-origin or CSP):', e.message);
}
}, 3000);
}
// Wait for Module to be ready
const maxChecks = 200; // 20 seconds (200 * 100ms)
const checkInterval = setInterval(() => {
checkCount++;
if (checkModuleReady()) {
clearInterval(checkInterval);
console.log('TRS-80 iframe: Module ready after', checkCount, 'checks');
} else if (checkCount >= maxChecks) {
clearInterval(checkInterval);
console.warn('TRS-80 iframe: Module not ready after', maxChecks, 'checks');
// Detailed debugging
const xroarWindow = xroarIframe.contentWindow;
console.warn('TRS-80 iframe: Final debug info:', {
xroarWindow: !!xroarWindow,
Module: !!xroarWindow?.Module,
wasm_load_file: typeof xroarWindow?.wasm_load_file,
windowKeys: xroarWindow ? Object.keys(xroarWindow).slice(0, 20) : []
});
// Try to access Module properties for debugging
try {
const m = xroarWindow?.Module;
if (m) {
console.warn('TRS-80 iframe: Module found but:', {
hasCcall: typeof m.ccall === 'function',
hasFS: !!m.FS,
hasCwrap: typeof m.cwrap === 'function'
});
} else {
// Try to find Module in different ways
console.warn('TRS-80 iframe: Trying to find Module...');
try {
const testEval = xroarWindow?.eval('typeof Module');
console.warn('TRS-80 iframe: eval("typeof Module"):', testEval);
} catch (e) {
console.warn('TRS-80 iframe: Cannot eval (may be cross-origin):', e.message);
}
}
} catch (e) {
console.warn('TRS-80 iframe: Cannot access Module:', e);
}
updateStatus('Emulator loading... (check console)');
}
}, 100);
};
// Do initial check after 2 seconds (give xroar.js time to load)
setTimeout(initialCheck, 2000);
});
// Handle errors
xroarIframe.addEventListener('error', function(e) {
console.error('TRS-80 iframe: Error loading xroar:', e);
updateStatus('Error loading emulator - check console');
});
// Set iframe source
xroarIframe.src = xroarUrl;
// Listen for messages from parent window
window.addEventListener('message', function(event) {
const data = event.data;
if (!data || !data.cmd) return;
const xroarWindow = xroarIframe.contentWindow;
if (!xroarWindow) return;
switch (data.cmd) {
case 'load':
if (data.url) {
console.log('TRS-80 iframe: Received load command');
updateStatus('Loading program...');
// Extract data from data URL
let fileData = null;
let filename = data.filename || 'program';
let contentType = data.contentType || 'application/x-coco-basic';
if (data.url.startsWith('data:')) {
const base64Match = data.url.match(/data:[^;]+;base64,(.+)/);
if (base64Match) {
const base64Data = base64Match[1];
const binaryString = atob(base64Data);
fileData = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
fileData[i] = binaryString.charCodeAt(i);
}
}
} else if (data.data && Array.isArray(data.data)) {
fileData = new Uint8Array(data.data);
}
if (!fileData) {
console.error('TRS-80 iframe: Could not extract file data');
updateStatus('Error: Could not extract file data');
return;
}
// Determine load type based on content type and filename
// loadType: 0=load+autodetect, 1=run, 2=tape, 3=disk, 4=text, 5=hd
// Machine-code .bin: use 0 so xroar picks DECB/RS-DOS BIN (1 can mis-detect as cassette).
let loadType = 1; // Default to autorun for BASIC files
// TRSE main is .ras/.tru but payload is machine code — never treat as ASCII BASIC
const trseSource =
/\.(ras|tru|trse)$/i.test(filename);
if (trseSource && contentType === 'text/plain') {
contentType = 'application/x-coco-binary';
}
if (contentType === 'text/plain' || filename.endsWith('.bas')) {
loadType = 1; // Autorun (autodetect type, including ASCII BASIC)
if (!filename.endsWith('.bas')) filename += '.bas';
} else if (contentType.includes('basic-cas') || filename.endsWith('.cas')) {
loadType = 2; // Tape (cassette) - attach tape, then CLOAD will load it
if (!filename.endsWith('.cas')) filename += '.cas';
} else if (contentType.includes('basic-dsk') || filename.endsWith('.dsk')) {
loadType = 3; // Disk
if (!filename.endsWith('.dsk')) filename += '.dsk';
} else if (contentType.includes('binary') || filename.endsWith('.bin')) {
loadType = 0; // Autodetect DECB / RS-DOS binary (avoids tape path for short .bin)
if (!filename.endsWith('.bin')) filename += '.bin';
}
// Wait for Module to be ready
const waitForModule = () => {
if (checkModuleReady()) {
// Store for reset
lastLoadedFile = fileData;
lastLoadedType = loadType;
// Load file
const loadResult = loadFileIntoXroar(xroarWindow, fileData, filename, loadType);
console.log('TRS-80 iframe: loadFileIntoXroar returned:', loadResult);
if (loadResult) {
updateStatus('Program loaded');
// Always send Ctrl+Shift+H after loading to clear display (works manually)
console.log('TRS-80 iframe: File loaded - contentType:', contentType, 'filename:', filename);
console.log('TRS-80 iframe: Sending Ctrl+Shift+H to clear display after load');
setTimeout(() => {
console.log('TRS-80 iframe: Sending Ctrl+Shift+H to clear display');
// Use togglePause which sends Ctrl+Shift+H - this clears the display
togglePause(xroarWindow);
// Process and auto-execute after clearing display
setTimeout(() => {
processLoadedFile(xroarWindow, contentType, filename);
}, 1000);
}, 500);
} else {
updateStatus('Error loading program');
}
} else {
setTimeout(waitForModule, 100);
}
};
waitForModule();
}
break;
case 'reset':
console.log('TRS-80 iframe: Received reset command');
if (checkModuleReady()) {
sendReset(xroarWindow);
}
break;
case 'pause':
console.log('TRS-80 iframe: Received pause command (toggle)');
if (checkModuleReady()) {
togglePause(xroarWindow);
}
break;
case 'resume':
console.log('TRS-80 iframe: Received resume command (toggle)');
if (checkModuleReady()) {
togglePause(xroarWindow);
}
break;
case 'toggle_pause':
console.log('TRS-80 iframe: Received explicit toggle_pause command');
if (checkModuleReady()) {
togglePause(xroarWindow);
}
break;
case 'keyboard':
if (data.command && checkModuleReady()) {
console.log('TRS-80 iframe: Received keyboard command:', data.command);
sendKeyboardInputCharacterByCharacter(xroarWindow, data.command);
}
break;
}
});
// Expose functions for console debugging
window.getTRS80Module = function() {
return xroarIframe.contentWindow?.Module;
};
window.resetTRS80 = function() {
const xroarWindow = xroarIframe.contentWindow;
if (xroarWindow) {
sendReset(xroarWindow);
}
};
window.testTRS80Keyboard = function(command) {
const xroarWindow = xroarIframe.contentWindow;
if (xroarWindow) {
sendKeyboardInputCharacterByCharacter(xroarWindow, command);
}
};
</script>
</body>
</html>