This repository has been archived by the owner on Dec 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathmachine.js
412 lines (391 loc) · 14.3 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
/**
* @fileoverview Manages a collection of devices as a single machine
* @author <a href="mailto:[email protected]">Jeff Parsons</a>
* @copyright © 2012-2019 Jeff Parsons
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* PCjs is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* PCjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCjs. If not,
* see <http://www.gnu.org/licenses/gpl.html>.
*
* You are required to include the above copyright notice in every modified copy of this work
* and to display that copyright notice when the software starts running; see COPYRIGHT in
* <https://www.pcjs.org/modules/devices/machine.js>.
*
* Some PCjs files also attempt to load external resource files, such as character-image files,
* ROM files, and disk image files. Those external resource files are not considered part of PCjs
* for purposes of the GNU General Public License, and the author does not claim any copyright
* as to their contents.
*/
"use strict";
/**
* @class {Machine}
* @unrestricted
* @property {CPU} cpu
* @property {string} sConfigFile
* @property {boolean} fConfigLoaded
* @property {boolean} fPageLoaded
*/
class Machine extends Device {
/**
* Machine(idMachine, sConfig)
*
* 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)
*/
constructor(idMachine, sConfig)
{
super(idMachine, idMachine);
let machine = this;
this.cpu = null;
this.ready = false;
this.powered = false;
this.sConfigFile = "";
this.fConfigLoaded = false;
this.fPageLoaded = false;
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' : undefined);
window.addEventListener(sEvent || 'beforeunload', function onUnloadPage(event) {
machine.killDevices();
});
}
/**
* 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() {
if (machine.ready) {
machine.onPower();
}
};
break;
case Machine.BINDING.RESET:
element.onclick = function onClickReset() {
if (machine.ready) {
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()
{
if (this.fConfigLoaded && this.fPageLoaded) {
for (let idDevice in this.deviceConfigs) {
let device, sClass;
try {
let config = this.deviceConfigs[idDevice];
sClass = config['class'];
if (!Machine.CLASSES[sClass]) {
this.printf("unrecognized %s device class: %s\n", idDevice, sClass);
}
else if (sClass == Machine.CLASS.MACHINE) {
this.printf("PCjs %s v%3.2f\n%s\n%s\n", config['name'], +VERSION, Machine.COPYRIGHT, Machine.LICENSE);
if (this.sConfigFile) this.printf("Configuration: %s\n", this.sConfigFile);
} else {
device = new Machine.CLASSES[sClass](this.idMachine, idDevice, config);
if (sClass == Machine.CLASS.CPU) {
if (!this.cpu) {
this.cpu = device;
} else {
this.printf("too many CPU devices: %s\n", idDevice);
continue;
}
}
this.printf("%s device: %s\n", sClass, device.status);
}
}
catch (err) {
this.printf("error initializing %s device '%s': %s\n", sClass, idDevice, err.message);
this.removeDevice(idDevice);
}
}
if (this.fAutoSave) {
let state = this.loadLocalStorage();
this.enumDevices(function onDeviceLoad(device) {
if (device.onLoad) {
device.onLoad(state);
}
});
}
this.onPower(true);
}
}
/**
* killDevices()
*
* @this {Machine}
*/
killDevices()
{
if (this.fAutoSave) {
let state = [];
this.enumDevices(function onDeviceSave(device) {
if (device.onSave) {
device.onSave(state);
}
});
this.saveLocalStorage(state);
}
this.onPower(false);
}
/**
* loadConfig(sConfig)
*
* @this {Machine}
* @param {string} sConfig
*/
loadConfig(sConfig)
{
try {
this.deviceConfigs = JSON.parse(sConfig);
this.checkConfig(this.deviceConfigs[this.idMachine]);
this.fAutoSave = (this.config['autoSave'] !== false);
this.fAutoStart = (this.config['autoStart'] !== false);
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.powered)
{
let machine = this;
if (on) this.println("power on");
this.enumDevices(function onDevicePower(device) {
if (device.onPower && device != machine) {
if (device != machine.cpu || machine.fAutoStart || this.ready) {
device.onPower(on);
}
}
});
this.ready = true;
this.powered = on;
if (!on) this.println("power off");
}
/**
* onReset()
*
* @this {Machine}
*/
onReset()
{
let machine = this;
this.enumDevices(function onDeviceReset(device) {
if (device.onReset && device != machine) {
device.onReset();
}
});
}
}
Machine.BINDING = {
POWER: "power",
RESET: "reset",
};
Machine.CLASS = {
BUS: "Bus",
CPU: "CPU",
CHIP: "Chip",
DEBUGGER: "Debugger",
INPUT: "Input",
LED: "LED",
MACHINE: "Machine",
MEMORY: "Memory",
RAM: "RAM",
ROM: "ROM",
TIME: "Time",
VIDEO: "Video"
};
Machine.CLASSES = {};
/*
* Since not all machines use all the classes, we have to initialize our class table like so.
*/
if (typeof Bus != "undefined") Machine.CLASSES[Machine.CLASS.BUS] = Bus;
if (typeof CPU != "undefined") Machine.CLASSES[Machine.CLASS.CPU] = CPU;
if (typeof Chip != "undefined") Machine.CLASSES[Machine.CLASS.CHIP] = Chip;
if (typeof Debugger != "undefined") Machine.CLASSES[Machine.CLASS.DEBUGGER] = Debugger;
if (typeof Input != "undefined") Machine.CLASSES[Machine.CLASS.INPUT] = Input;
if (typeof LED != "undefined") Machine.CLASSES[Machine.CLASS.LED] = LED;
if (typeof Machine != "undefined") Machine.CLASSES[Machine.CLASS.MACHINE] = Machine;
if (typeof Memory != "undefined") Machine.CLASSES[Machine.CLASS.MEMORY] = Memory;
if (typeof RAM != "undefined") Machine.CLASSES[Machine.CLASS.RAM] = RAM;
if (typeof ROM != "undefined") Machine.CLASSES[Machine.CLASS.ROM] = ROM;
if (typeof Time != "undefined") Machine.CLASSES[Machine.CLASS.TIME] = Time;
if (typeof Video != "undefined") Machine.CLASSES[Machine.CLASS.VIDEO] = Video;
Machine.COPYRIGHT = "Copyright © 2012-2019 Jeff Parsons <[email protected]>";
Machine.LICENSE = "License: GPL version 3 or later <http://gnu.org/licenses/gpl.html>";
/*
* 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(idMachine, sConfig) {
let machine = new Machine(idMachine, sConfig);
window[COMMAND] = function(command) {
return machine.parseCommand(command);
};
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.
*/
if (FACTORY == "Machine") {
window['Invaders'] = window[FACTORY];
window['LEDs'] = window[FACTORY];
window['TMS1500'] = window[FACTORY];
}