-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzxspectrum-iframe.html
More file actions
709 lines (630 loc) · 36.2 KB
/
zxspectrum-iframe.html
File metadata and controls
709 lines (630 loc) · 36.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ZX Spectrum Emulator (Iframe)</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000;
overflow: hidden;
}
#qaop-container {
width: 100%;
height: 100vh;
position: relative;
}
#qaop-iframe {
width: 100%;
height: 100%;
border: none;
background-color: #000;
}
#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 ZX Spectrum emulator...</div>
<div id="qaop-container">
<iframe id="qaop-iframe" allow="fullscreen"></iframe>
</div>
<script>
// Get URL parameters from parent page
const urlParams = new URLSearchParams(window.location.search);
// Default 128k: full-keyword typing in BASIC; 48k uses single-letter tokens (R→RUN, etc.)
const modelParam = urlParams.get('model') || '128k';
const loadParam = urlParams.get('load');
// Build qaop URL with parameters
let qaopUrl = './qaop/qaop.html';
const hashParams = [];
// Set model (48k or 128k)
if (modelParam === '128k') {
hashParams.push('128');
} else {
hashParams.push('~128'); // 48k mode
}
// Add load parameter if provided
if (loadParam) {
hashParams.push('l=' + encodeURIComponent(loadParam));
}
if (hashParams.length > 0) {
qaopUrl += '#' + hashParams.join('&');
}
// Set up load event listener BEFORE setting src
const qaopIframe = document.getElementById('qaop-iframe');
let iframeLoaded = false;
// Notify parent when iframe is ready
qaopIframe.addEventListener('load', function() {
console.log('ZX Spectrum iframe: qaop iframe loaded');
iframeLoaded = true;
updateStatus('ZX Spectrum emulator ready');
// Ensure emulator is not paused on load
// Wait a bit for qaop to fully initialize, then ensure it's running
setTimeout(() => {
const qaopWindow = qaopIframe.contentWindow;
if (qaopWindow && qaopWindow.emu) {
// Check if emulator is paused and resume if needed
// qaop might pause on blur/focus, so we ensure it's running
try {
// Try to resume by sending a resume command if paused
// We'll check pause state via emulator state if available
console.log('ZX Spectrum iframe: Ensuring emulator is running after load');
} catch (e) {
console.log('ZX Spectrum iframe: Could not check/resume emulator state:', e);
}
}
}, 1000);
// Hide status after a delay
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.style.display = 'none';
}
}, 2000);
// Notify parent window
if (window.parent) {
window.parent.postMessage({
type: 'emulator_ready',
platform: 'zxspectrum'
}, '*');
}
});
// Handle errors
qaopIframe.addEventListener('error', function(e) {
console.error('ZX Spectrum iframe: Error loading qaop:', e);
updateStatus('Error loading emulator - check console');
});
// Now set the iframe source
qaopIframe.src = qaopUrl;
// Update status
function updateStatus(message) {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.textContent = message;
statusEl.style.display = 'block'; // Make sure it's visible
// Only hide status after "ready" message, not for loading messages
if (message.includes('ready') || message.includes('loaded')) {
setTimeout(() => {
statusEl.style.display = 'none';
}, 2000);
}
}
}
// Send keyboard input to qaop emulator
function sendKeyboardInput(qaopFrame, command) {
try {
const qaopWindow = qaopFrame.contentWindow;
if (!qaopWindow) {
console.warn('ZX Spectrum iframe: qaop window not available');
return;
}
console.log('ZX Spectrum iframe: Sending keyboard command:', command);
// Use qaop's h.kbd() API directly - it accepts a string
// This is the proper way to send keyboard input to qaop
if (qaopWindow.emu && qaopWindow.emu.h && typeof qaopWindow.emu.h.kbd === 'function') {
qaopWindow.emu.h.kbd(command);
console.log('ZX Spectrum iframe: Sent command via emu.h.kbd()');
return;
}
// Fallback: try emu.kbd() if h.kbd() doesn't exist
if (qaopWindow.emu && typeof qaopWindow.emu.kbd === 'function') {
qaopWindow.emu.kbd(command);
console.log('ZX Spectrum iframe: Sent command via emu.kbd()');
return;
}
console.warn('ZX Spectrum iframe: emu.kbd() not available');
} catch (e) {
console.error('ZX Spectrum iframe: Error sending keyboard command:', e);
}
}
// Send keyboard input character by character (for complex commands like RANDOMIZE USR)
function sendKeyboardInputCharacterByCharacter(qaopFrame, command) {
try {
const qaopWindow = qaopFrame.contentWindow;
if (!qaopWindow) {
console.warn('ZX Spectrum iframe: qaop window not available');
return;
}
console.log('ZX Spectrum iframe: Sending keyboard command character by character:', command);
const kbdFunc = qaopWindow.emu?.h?.kbd || qaopWindow.emu?.kbd;
if (!kbdFunc || typeof kbdFunc !== 'function') {
console.warn('ZX Spectrum iframe: emu.kbd() not available, falling back to single call');
sendKeyboardInput(qaopFrame, command);
return;
}
// Send each character with a small delay
let index = 0;
const sendNextChar = () => {
if (index < command.length) {
const char = command[index];
kbdFunc(char);
index++;
// Small delay between characters (20ms)
setTimeout(sendNextChar, 20);
} else {
console.log('ZX Spectrum iframe: Finished sending command character by character');
}
};
sendNextChar();
} catch (e) {
console.error('ZX Spectrum iframe: Error sending keyboard command character by character:', e);
// Fallback to regular method
sendKeyboardInput(qaopFrame, command);
}
}
// Send Ctrl+Del (reset) to qaop emulator
function sendReset(qaopFrame) {
try {
const qaopWindow = qaopFrame.contentWindow;
if (!qaopWindow) {
console.warn('ZX Spectrum iframe: qaop window not available for reset');
return;
}
console.log('ZX Spectrum iframe: Sending reset');
// Try using qaop's cmd function (if ui is available)
if (qaopWindow.ui && typeof qaopWindow.ui.cmd === 'function') {
qaopWindow.ui.cmd('reset');
console.log('ZX Spectrum iframe: Sent reset via ui.cmd()');
return;
}
// Fallback: use emu's reset function if available
if (qaopWindow.emu && typeof qaopWindow.emu.reset === 'function') {
qaopWindow.emu.reset();
console.log('ZX Spectrum iframe: Sent reset via emu.reset()');
return;
}
// Last resort: send Ctrl+Del as keyboard input
// qaop's h.kbd() can accept key codes with modifiers
// Looking at qaop code: h.kbd(~keyCode, keydown, shiftKey+2*(ctrlKey|altKey|metaKey))
// For Ctrl+Del: ~46 (Delete), true (keydown), 2 (Ctrl)
if (qaopWindow.emu && qaopWindow.emu.h && typeof qaopWindow.emu.h.kbd === 'function') {
qaopWindow.emu.h.kbd(~46, true, 2); // ~46 = Delete, true = keydown, 2 = Ctrl
console.log('ZX Spectrum iframe: Sent Ctrl+Del via emu.h.kbd()');
return;
}
console.warn('ZX Spectrum iframe: Could not send reset');
} catch (e) {
console.error('ZX Spectrum iframe: Error sending reset:', e);
}
}
// Expose test functions to console for debugging
window.testZXKeyboard = function(command) {
const qaopFrame = document.getElementById('qaop-iframe');
if (!qaopFrame) {
console.error('qaop-iframe not found');
return;
}
// If no command provided, check model and send appropriate command
if (!command) {
const qaopWindow = qaopFrame.contentWindow;
let model = 0; // Default to 48k
try {
if (qaopWindow && qaopWindow.emu && qaopWindow.emu.zx) {
const state = qaopWindow.emu.zx.getState();
model = state.model || 0;
}
} catch (e) {
console.log('Could not get model, defaulting to 48k:', e);
}
command = (model === 1) ? 'RUN\n' : 'r\n';
}
console.log('Testing keyboard input:', command);
sendKeyboardInput(qaopFrame, command);
};
// Get current model (0 = 48k, 1 = 128k)
window.getZXModel = function() {
const qaopFrame = document.getElementById('qaop-iframe');
if (!qaopFrame) {
console.error('qaop-iframe not found');
return null;
}
const qaopWindow = qaopFrame.contentWindow;
try {
if (qaopWindow && qaopWindow.emu && qaopWindow.emu.zx) {
const state = qaopWindow.emu.zx.getState();
const model = state.model || 0;
console.log('Current model:', model, '(0 = 48k, 1 = 128k)');
return model;
}
} catch (e) {
console.error('Could not get model:', e);
}
return null;
};
// Set model (0 = 48k, 1 = 128k) and reset after change
window.setZXModel = function(model, resetAfterChange) {
const qaopFrame = document.getElementById('qaop-iframe');
if (!qaopFrame) {
console.error('qaop-iframe not found');
return Promise.resolve(false);
}
const qaopWindow = qaopFrame.contentWindow;
return new Promise((resolve) => {
try {
if (qaopWindow && qaopWindow.emu && typeof qaopWindow.emu.setModel === 'function') {
const oldModel = qaopWindow.emu.zx ? qaopWindow.emu.zx.getState().model : null;
qaopWindow.emu.setModel(model);
console.log('Set model to:', model, '(0 = 48k, 1 = 128k)');
// Wait for the change to take effect
const checkModel = () => {
try {
const currentModel = qaopWindow.emu.zx ? qaopWindow.emu.zx.getState().model : null;
if (currentModel === model) {
console.log('Model change confirmed:', currentModel);
// If resetAfterChange is true (default), send reset
if (resetAfterChange !== false) {
setTimeout(() => {
sendReset(qaopFrame);
resolve(true);
}, 100);
} else {
resolve(true);
}
} else if (oldModel !== currentModel) {
// Model is changing, wait a bit more
setTimeout(checkModel, 50);
} else {
// Model hasn't changed yet, keep waiting
setTimeout(checkModel, 50);
}
} catch (e) {
console.error('Error checking model:', e);
resolve(false);
}
};
// Start checking after a short delay
setTimeout(checkModel, 100);
} else {
resolve(false);
}
} catch (e) {
console.error('Could not set model:', e);
resolve(false);
}
});
};
// Switch to 128k mode (with reset)
window.switchTo128k = function() {
return window.setZXModel(1, true);
};
// Switch to 48k mode (with reset)
window.switchTo48k = function() {
return window.setZXModel(0, true);
};
// Send reset (Ctrl+Del)
window.resetZX = function() {
const qaopFrame = document.getElementById('qaop-iframe');
if (!qaopFrame) {
console.error('qaop-iframe not found');
return;
}
sendReset(qaopFrame);
};
// Listen for messages from parent window
window.addEventListener('message', function(event) {
// Accept messages from any origin (in production, you might want to check event.origin)
const data = event.data;
if (!data || !data.cmd) return;
const qaopFrame = document.getElementById('qaop-iframe');
if (!qaopFrame) return;
switch (data.cmd) {
case 'load':
// Load a file into qaop
if (data.url) {
const qaopWindow = qaopFrame.contentWindow;
// Variables for processLoadedFile
let processLoadedFileCalled = false;
let statusTimeout = null;
let errorHandler = null;
// Function to process the loaded file
const processLoadedFile = () => {
console.log('ZX Spectrum iframe: processLoadedFile called, called flag:', processLoadedFileCalled);
if (processLoadedFileCalled) {
console.log('ZX Spectrum iframe: processLoadedFile already called, skipping');
return;
}
processLoadedFileCalled = true;
if (statusTimeout) clearTimeout(statusTimeout);
if (errorHandler) qaopFrame.removeEventListener('error', errorHandler);
console.log('ZX Spectrum iframe: qaop iframe loaded with file URL');
console.log('ZX Spectrum iframe: File loaded, contentType:', data.contentType, 'filename:', data.filename);
// Debug: Log all data properties
console.log('ZX Spectrum iframe: Full data object:', JSON.stringify({
cmd: data.cmd,
contentType: data.contentType,
filename: data.filename,
url: data.url ? data.url.substring(0, 100) + '...' : null
}));
// Give qaop time to process the file
setTimeout(() => {
// Z80 / SNA: qaop loads via #l= / MIME; CPU resumes from snapshot (no tape LOAD / USR)
if (data.contentType === 'application/x.zx.z80' || data.contentType === 'application/x.zx.sna') {
console.log('ZX Spectrum iframe: snapshot loaded (Z80/SNA), should auto-execute');
updateStatus('Program loaded and executing');
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.style.display = 'none';
}
}, 2000);
}
// Check if it's a BASIC TAP file (not a C program)
// A BASIC TAP file is either:
// 1. A TAP file with a .bas filename, OR
// 2. A TAP file that's not from a .c file
else if (data.contentType === 'application/x.zx.tap') {
const isCFile = data.filename && (data.filename.endsWith('.c') || data.filename.endsWith('.C'));
const isBasFile = data.filename && (data.filename.endsWith('.bas') || data.filename.endsWith('.BAS'));
// Check TAP file header to detect CODE blocks (type 0x03) vs BASIC (type 0x00)
let isCodeBlock = false;
let codeStartAddress = 0x8000; // Default start address
try {
// Decode base64 data URL to check TAP header
if (data.url && data.url.startsWith('data:')) {
const base64Data = data.url.split(',')[1];
const tapData = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
console.log('ZX Spectrum iframe: TAP file size:', tapData.length, 'bytes');
console.log('ZX Spectrum iframe: First 30 bytes of TAP:', Array.from(tapData.slice(0, 30)).map(b => '0x' + b.toString(16).padStart(2, '0')).join(' '));
// TAP header format: flag (0x13) + length (2 bytes) + data (17 bytes) + checksum
// Full header: [0x13] [len_low] [len_high] [type] [filename 10 bytes] [data_len_low] [data_len_high] [param1_low] [param1_high] [param2_low] [param2_high] [checksum]
// Type is at offset 3, start address (param1) is at offsets 16-17 (little-endian)
if (tapData.length > 20 && tapData[0] === 0x13) {
const tapType = tapData[3]; // Type is at offset 3
console.log('ZX Spectrum iframe: TAP header type:', tapType, '(0x00=BASIC, 0x03=CODE)');
if (tapType === 0x03) {
isCodeBlock = true;
// Start address (parameter 1) is at bytes 16-17 (little-endian)
// Offset 3 (type) + 10 (filename) + 2 (data length) + 1 (param1_low) = 16
codeStartAddress = tapData[16] | (tapData[17] << 8);
console.log('ZX Spectrum iframe: First CODE block load address: 0x' + codeStartAddress.toString(16));
} else if (tapType === 0x00) {
console.log('ZX Spectrum iframe: TAP file is BASIC program (type 0x00)');
}
} else {
console.log('ZX Spectrum iframe: TAP file does not start with 0x13 or is too short');
}
}
} catch (e) {
console.error('ZX Spectrum iframe: Could not parse TAP header:', e);
}
console.log('ZX Spectrum iframe: TAP file detected, isCFile:', isCFile, 'isBasFile:', isBasFile, 'isCodeBlock:', isCodeBlock, 'filename:', data.filename);
// If it's a CODE block or C file, use RANDOMIZE USR
if (isCodeBlock || isCFile) {
console.log('ZX Spectrum iframe: CODE block/C program detected, will use RANDOMIZE USR', codeStartAddress);
updateStatus('Program loaded - executing...');
// ui.load() starts tape LOAD; ROM prints "Bytes: …" until load finishes.
// If we send RANDOMIZE USR too soon, BASIC runs while tape is still loading → stuck loop.
const usrDelayMs = 6000;
setTimeout(() => {
const usrCommand = `RANDOMIZE USR ${codeStartAddress}\n`;
console.log('ZX Spectrum iframe: Sending RANDOMIZE USR (after ' + usrDelayMs + 'ms tape settle):', usrCommand.trim());
sendKeyboardInput(qaopFrame, usrCommand);
}, usrDelayMs);
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.style.display = 'none';
}
}, usrDelayMs + 2000);
} else {
// BASIC program - send RUN command
// Check the actual model from emu.zx.getState().model
// 0 = 48k, 1 = 128k
const qaopWindow = qaopFrame.contentWindow;
let model = 0; // Default to 48k
try {
if (qaopWindow && qaopWindow.emu && qaopWindow.emu.zx) {
const state = qaopWindow.emu.zx.getState();
model = state.model || 0;
}
} catch (e) {
console.log('ZX Spectrum iframe: Could not get model, defaulting to 48k:', e);
}
// Determine command based on model: 'r\n' for 48k, empty for 128k (128k auto-runs)
const command = (model === 1) ? '' : 'r\n';
console.log('ZX Spectrum iframe: BASIC TAP file detected (contentType:', data.contentType, ', filename:', data.filename, '), model:', model, ' (0=48k, 1=128k), sending command:', command || '(none)');
updateStatus('Program loaded - running...');
// Send command to execute the BASIC program (only if command is not empty)
if (command) {
setTimeout(() => {
console.log('ZX Spectrum iframe: Sending command now:', command);
sendKeyboardInput(qaopFrame, command);
}, 1500); // Wait a bit longer for TAP to fully load
} else {
console.log('ZX Spectrum iframe: No command needed for 128k mode (auto-runs)');
}
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.style.display = 'none';
}
}, 3000);
}
} else {
console.log('ZX Spectrum iframe: Unknown file type, contentType:', data.contentType);
updateStatus('Program loaded');
setTimeout(() => {
const statusEl = document.getElementById('status');
if (statusEl) {
statusEl.style.display = 'none';
}
}, 2000);
}
}, 1000);
};
// Z80/SNA/TAP: use ui.load in current model (default 128k, matches TRSE spectrum_model).
// Do not force #~128 — 48K RAM snapshots load into 128K machines; forcing 48K caused black screen.
if (data.url.startsWith('data:') && qaopWindow && qaopWindow.ui && typeof qaopWindow.ui.load === 'function') {
console.log('ZX Spectrum iframe: Using qaop ui.load for data URL');
console.log('ZX Spectrum iframe: Content type from data:', data.contentType);
try {
qaopWindow.ui.load(data.url);
updateStatus('Loading program...');
setTimeout(() => {
processLoadedFile();
}, 1500);
} catch (e) {
console.error('ZX Spectrum iframe: Error using qaop load API:', e);
loadViaUrlHash();
}
} else {
loadViaUrlHash();
}
function loadViaUrlHash() {
const currentUrl = qaopFrame.src.split('#')[0];
const loadUrl = currentUrl + '#l=' + encodeURIComponent(data.url);
console.log('ZX Spectrum iframe: Loading URL (truncated):', loadUrl.substring(0, 220) + (loadUrl.length > 220 ? '...' : ''));
console.log('ZX Spectrum iframe: Content type from data:', data.contentType);
// Listen for errors
errorHandler = function(e) {
console.error('ZX Spectrum iframe: Error loading file:', e);
updateStatus('Error loading program');
};
qaopFrame.addEventListener('error', errorHandler);
statusTimeout = setTimeout(() => {
console.warn('ZX Spectrum iframe: Load timeout, processing file anyway');
qaopFrame.removeEventListener('error', errorHandler);
if (!processLoadedFileCalled) {
console.log('ZX Spectrum iframe: Calling processLoadedFile from timeout');
processLoadedFile();
} else {
console.log('ZX Spectrum iframe: processLoadedFile already called (flag:', processLoadedFileCalled, '), not calling again');
}
}, 8000);
// Wait for iframe to load
qaopFrame.addEventListener('load', processLoadedFile, { once: true });
// First, load with just the file URL
qaopFrame.src = loadUrl;
updateStatus('Loading program...');
}
}
break;
case 'reset':
// Reset emulator by reloading without the load parameter
// This prevents "Failed to fetch" errors from trying to reload data URLs
const resetUrl = qaopFrame.src.split('#')[0];
const currentHash = qaopFrame.src.split('#')[1] || '';
// Remove the load parameter (l=...) but keep model parameter
const hashParts = currentHash.split('&').filter(part => !part.startsWith('l='));
const resetHash = hashParts.length > 0 ? hashParts.join('&') : '';
qaopFrame.src = resetUrl + (resetHash ? '#' + resetHash : '');
updateStatus('Resetting...');
break;
case 'pause':
// Pause/resume - qaop uses Pause key for pause/unpause
// Only send pause command if explicitly requested (not on click/focus)
if (qaopFrame && qaopFrame.contentWindow && data.pause !== undefined) {
const qaopWindow = qaopFrame.contentWindow;
const qaopDoc = qaopWindow.document;
const qaopCanvas = qaopDoc ? qaopDoc.querySelector('canvas') : null;
// Send Pause key event (keyCode 19 for Pause/Break)
// Pause key toggles pause/unpause in qaop
const pauseEvent = new KeyboardEvent('keydown', {
key: 'Pause',
code: 'Pause',
keyCode: 19,
which: 19,
bubbles: true,
cancelable: true
});
// Dispatch to window, document, and canvas
if (qaopWindow) {
qaopWindow.dispatchEvent(pauseEvent);
}
if (qaopDoc) {
qaopDoc.dispatchEvent(pauseEvent);
}
if (qaopCanvas) {
qaopCanvas.dispatchEvent(pauseEvent);
}
updateStatus(data.pause !== false ? 'Paused' : 'Resumed');
console.log('ZX Spectrum iframe: Sent Pause key event, pause:', data.pause);
}
break;
case 'model':
// Switch between 48k and 128k
const model = data.model || '128k';
const modelUrl = qaopFrame.src.split('#')[0];
const modelHashParts = [];
if (model === '128k') {
modelHashParts.push('128');
} else {
modelHashParts.push('~128');
}
// Preserve load parameter if present
const modelCurrentHash = qaopFrame.src.split('#')[1];
if (modelCurrentHash && modelCurrentHash.includes('l=')) {
modelHashParts.push(modelCurrentHash.match(/l=[^&]*/)[0]);
}
qaopFrame.src = modelUrl + '#' + modelHashParts.join('&');
updateStatus('Switching to ' + model + ' mode...');
break;
}
});
// Listen for messages from qaop iframe (for capabilities, etc.)
window.addEventListener('message', function(event) {
// Forward relevant messages to parent
const qaopIframe = document.getElementById('qaop-iframe');
if (qaopIframe && event.source === qaopIframe.contentWindow) {
const data = event.data;
if (data && (data.type === 'emulator_capabilities' || data.type === 'ready')) {
// Forward to parent window
if (window.parent) {
window.parent.postMessage({
type: 'emulator_capabilities',
capabilities: {
reset: true,
pause: true,
model: true
}
}, '*');
}
}
}
});
// Also check if iframe fails to load after timeout
setTimeout(() => {
if (!iframeLoaded) {
const statusEl = document.getElementById('status');
if (statusEl && statusEl.textContent.includes('Loading')) {
console.warn('ZX Spectrum iframe: qaop iframe may have failed to load');
updateStatus('Emulator loading timeout - check if qaop/qaop.html exists');
}
}
}, 10000);
</script>
</body>
</html>