forked from jeffpar/pcjs.v1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine.js
426 lines (405 loc) · 15.2 KB
/
machine.js
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
/**
* @fileoverview Manages a collection of devices as a single machine
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2020 Jeff Parsons
* @license MIT
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*/
"use strict";
/**
* @class {Machine}
* @unrestricted
* @property {CPU} cpu
* @property {string} sConfigFile
* @property {boolean} fConfigLoaded
* @property {boolean} fPageLoaded
*/
class Machine extends Device {
/**
* Machine(idMachine, sConfig, sParms)
*
* If sConfig contains a JSON object definition, then we parse it immediately and save the result in this.config;
* otherwise, we assume it's the URL of an JSON object definition, so we request the resource, and once it's loaded,
* we parse it.
*
* One important change in v2: the order of the device objects in the JSON file determines creation/initialization order.
* In general, the Machine object should always be first (it's always created first anyway), and the Time object should
* be listed next, so that its services are available to any other device when they're created/initialized.
*
* Sample config:
*
* {
* "ti57": {
* "class": "Machine",
* "type": "TI57",
* "name": "TI-57 Programmable Calculator Simulation",
* "version": 2.00,
* "autoSave": true,
* "autoStart": true,
* "bindings": {
* "power": "powerTI57",
* "reset": "resetTI57",
* "clear": "clearTI57",
* "print": "printTI57"
* }
* },
* "clock": {
* "class": "Time",
* "cyclesPerSecond": 650000
* "bindings": {
* "run": "runTI57",
* "speed": "speedTI57",
* "step": "stepTI57"
* },
* "overrides": ["cyclesPerSecond"]
* },
* "display": {
* "class": "LED",
* "type": 3,
* "cols": 12,
* "rows": 1,
* "color": "red",
* "bindings": {
* "container": "displayTI57"
* },
* "overrides": ["color","backgroundColor"]
* },
* "buttons": {
* "class": "Input",
* "map": [
* ["2nd", "inv", "lnx", "\\b", "clr"],
* ["lrn", "xchg", "sq", "sqrt", "rcp"],
* ["sst", "sto", "rcl", "sum", "exp"],
* ["bst", "ee", "(", ")", "/"],
* ["gto", "7", "8", "9", "*"],
* ["sbr", "4", "5", "6", "-"],
* ["rst", "1", "2", "3", "+"],
* ["r/s", "0", ".", "+/-", "=|\\r"]
* ],
* "location": [139, 325, 368, 478, 0.34, 0.5, 640, 853, 418, 180, 75, 36],
* "bindings": {
* "surface": "imageTI57"
* }
* },
* "rom": {
* "class": "ROM",
* "wordSize": 13,
* "valueSize": 16,
* "valueTotal": 2048,
* "littleEndian": true,
* "file": "ti57le.bin",
* "reference": "",
* "values": [
* ]
* },
* "cpu": {
* "class": "CPU",
* "type": "TMS-1500",
* "input": "buttons",
* "output": "display"
* }
* }
*
* @this {Machine}
* @param {string} idMachine (of both the machine AND the <div> to contain it)
* @param {string} sConfig (JSON configuration for entire machine, including any static resources)
* @param {string} [sParms] (optional JSON parameters that can supplement or override the configuration)
*/
constructor(idMachine, sConfig, sParms)
{
super(idMachine, idMachine);
let machine = this;
this.fPowered = false;
this.sParms = sParms;
this.sConfigFile = "";
this.fConfigLoaded = false;
this.fPageLoaded = false;
this.setReady(false);
/*
* You can pass "m" commands to the machine via the "commands" parameter to turn on any desired
* message groups, but since the Debugger is responsible for parsing those commands, and since the
* Debugger is usually not initialized until last, messages from any earlier constructor calls will
* not appear.
*
* One alternative is to hard-code any MESSAGE groups here, to ensure that the relevant messages
* from all device constructors get displayed.
*/
this.messages = DEBUG? MESSAGE.WARN : MESSAGE.DEFAULT;
sConfig = sConfig.trim();
if (sConfig[0] == '{') {
this.loadConfig(sConfig);
} else {
this.sConfigFile = sConfig;
this.getResource(this.sConfigFile, function onLoadConfig(sURL, sResource, readyState, nErrorCode) {
if (readyState == 4) {
if (!nErrorCode && sResource) {
machine.loadConfig(sResource);
machine.initDevices();
}
else {
machine.printf("error (%d) loading configuration: %s\n", nErrorCode, sURL);
}
}
});
}
/*
* Device initialization is now deferred until after the page is fully loaded, for the benefit
* of devices (eg, Input) that may be dependent on page resources.
*
* Strangely, for these page events, I must use the window object rather than the document object.
*/
window.addEventListener('load', function onLoadPage(event) {
machine.fPageLoaded = true;
machine.initDevices();
});
let sEvent = this.isUserAgent("iOS")? 'pagehide' : (this.isUserAgent("Opera")? 'unload' : 'beforeunload');
window.addEventListener(sEvent, function onUnloadPage(event) {
machine.stopDevices();
});
window.addEventListener('pageshow', function onShowPage(event) {
if (!machine.fPowered) machine.onPower(true);
});
}
/**
* addBinding(binding, element)
*
* @this {Machine}
* @param {string} binding
* @param {Element} element
*/
addBinding(binding, element)
{
let machine = this;
switch(binding) {
case Machine.BINDING.POWER:
element.onclick = function onClickPower() {
machine.onPower();
};
break;
case Machine.BINDING.RESET:
element.onclick = function onClickReset() {
machine.onReset();
};
break;
}
super.addBinding(binding, element);
}
/**
* initDevices()
*
* Initializes devices in the proper order. For example, any Time devices should be initialized first,
* to ensure that their timer services are available to other devices within their constructor.
*
* However, we should avoid device order dependencies whenever possible, so if a Device can defer a call
* to another Device until its onLoad() or onPower() handler can be called, even better.
*
* @this {Machine}
*/
initDevices()
{
let power = true;
if (this.fConfigLoaded && this.fPageLoaded) {
for (let idDevice in this.deviceConfigs) {
let sClass;
let config = this.deviceConfigs[idDevice];
try {
sClass = config['class'];
if (!Defs.CLASSES[sClass]) {
this.printf('unrecognized %s device "%s"\n', sClass, idDevice);
}
else if (sClass == "Machine") {
this.printf("PCjs %s v%3.2f\n%s\n", config['name'], +VERSION, Machine.COPYRIGHT);
if (this.sConfigFile) this.printf("Configuration: %s\n", this.sConfigFile);
} else {
let device = new Defs.CLASSES[sClass](this.idMachine, idDevice, config);
if (MAXDEBUG) this.printf('%s device "%s"\n', sClass, idDevice);
}
}
catch (err) {
if (!config['optional']) {
this.printf('error initializing %s device "%s": %s\n', sClass, idDevice, err.message);
power = false;
}
this.removeDevice(idDevice);
}
}
if (this.fAutoSave) {
let state = this.loadLocalStorage();
this.enumDevices(function onDeviceLoad(device) {
if (device.onLoad) {
if (!device.onLoad(state)) {
device.printf('unable to restore state for device "%s"\n', device.idDevice);
return false;
}
}
return true;
});
}
this.setReady(true);
if (!this.whenReady(this.onPower.bind(this, power))) {
this.printf("machine %s not ready to power, waiting for device(s)\n", this.idMachine);
}
}
}
/**
* isPowered()
*
* @this {Machine}
* @returns {boolean} true if the machine is powered, false if not
*/
isPowered()
{
return this.fPowered;
}
/**
* loadConfig(sConfig)
*
* @this {Machine}
* @param {string} sConfig
*/
loadConfig(sConfig)
{
try {
this.deviceConfigs = JSON.parse(sConfig);
this.checkConfig(this.deviceConfigs[this.idMachine], ['autoSave', 'autoStart']);
this.fAutoSave = (this.config['autoSave'] !== false);
this.fAutoStart = (this.config['autoStart'] !== false);
if (this.sParms) {
/*
* Historically, my web servers have not been consistent about quoting property names inside
* the optional parameters object, so we must use eval() instead of JSON.parse() to parse them.
* Of couse, the REAL problem is that JSON.parse() is being a dick about otherwise perfectly
* legitimate Object syntax, but I shall not repeat my long list of gripes about JSON here.
*/
let parms = /** @type {Object} */ (eval("(" + this.sParms + ")"));
/*
* Slam all these parameters into the machine's config, overriding any matching machine configuration
* properties. Any other devices that need access to these properties should use getMachineConfig().
*/
for (let prop in parms) {
this.config[prop] = parms[prop];
}
}
this.fConfigLoaded = true;
} catch(err) {
let sError = err.message;
let match = sError.match(/position ([0-9]+)/);
if (match) {
sError += " ('" + sConfig.substr(+match[1], 40).replace(/\s+/g, ' ') + "...')";
}
this.println("machine '" + this.idMachine + "' initialization error: " + sError);
}
}
/**
* onPower(on)
*
* @this {Machine}
* @param {boolean} [on]
*/
onPower(on = !this.fPowered)
{
if (this.isReady()) {
let machine = this;
if (on) this.println("power on");
this.enumDevices(function onDevicePower(device) {
if (device.onPower && device != machine) {
if (device.config['class'] != "CPU" || machine.fAutoStart || machine.isReady()) {
device.onPower(on);
} else {
/*
* If we're not going to start the CPU on the first power notification, then we should
* we fake a transition to the "stopped" state, so that the Debugger will display the current
* machine state.
*/
device.time.update(true);
}
}
return true;
});
this.fPowered = on;
if (!on) this.println("power off");
}
}
/**
* onReset()
*
* @this {Machine}
*/
onReset()
{
if (this.isReady()) {
let machine = this;
this.enumDevices(function onDeviceReset(device) {
if (device.onReset && device != machine) {
device.onReset();
}
return true;
});
this.println("reset");
}
}
/**
* stopDevices()
*
* @this {Machine}
*/
stopDevices()
{
if (this.fAutoSave) {
let state = [];
this.enumDevices(function onDeviceSave(device) {
if (device.onSave) {
device.onSave(state);
}
return true;
});
this.saveLocalStorage(state);
}
this.onPower(false);
}
}
Machine.BINDING = {
POWER: "power",
RESET: "reset",
};
Machine.COPYRIGHT = "Copyright © 2012-2020 Jeff Parsons <[email protected]>";
/*
* Create the designated machine FACTORY function (this should suffice for all compiled versions).
*
* In addition, expose the machine's COMMAND handler interface, so that it's easy to access any of the
* machine's built-in commands from a browser or IDE debug console:
*
* window.command("?")
*
* Normally, access to the COMMAND handlers will be through the machine's WebIO.BINDING.PRINT textarea,
* but not all machines will have such a control, and sometimes that control will be inaccessible (eg, if
* the browser is currently debugging the machine).
*/
window[FACTORY] = function createMachine(idMachine, sConfig, sParms) {
let machine = new Machine(idMachine, sConfig, sParms);
window[COMMAND] = function(commands) {
return machine.parseCommands(commands);
};
return machine;
};
/*
* If we're NOT running a compiled release (ie, FACTORY wasn't overriden from "Machine" to something else),
* then create hard-coded aliases for all known factories; only DEBUG servers should be running uncompiled code.
*
* Why is the PDP11 factory called 'PDP11V2' instead of simply 'PDP11'? Because the CPU class for PDP11 machines
* is already called PDP11, and we can't have both a class and a global function with the same name. Besides,
* these factory functions are creating entire "machines", not just "processors", so it makes sense for the names
* to reflect that.
*
* And yes, by the same logic, one might think that 'TMS1500' should really be called 'TI57', except that the
* TMS1500 factory can produce any of the TI-42, TI-55, or TI-57. Naming is hard.
*/
if (FACTORY == "Machine") {
window['Invaders'] = window[FACTORY];
window['LEDs'] = window[FACTORY];
window['PDP11V2'] = window[FACTORY];
window['TMS1500'] = window[FACTORY];
window['VT100'] = window[FACTORY];
}
Defs.CLASSES["Machine"] = Machine;