This repository has been archived by the owner on Dec 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.ts
377 lines (332 loc) · 13.5 KB
/
Main.ts
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
import {
CanvasScreen,
CassettePlayer,
ControlPanel,
DriveIndicators,
PanelType,
SettingsPanel,
Trs80
} from "trs80-emulator";
import firebase from 'firebase/app';
// These imports load individual services into the firebase namespace.
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/analytics';
import * as firebaseui from "firebaseui";
import {makeIcon, makeIconButton, makeTextButton} from "./Utils";
import {PanelManager} from "./PanelManager";
import {LibraryPanel} from "./LibraryPanel";
import {Context} from "./Context";
import {Library} from "./Library";
import {FileBuilder} from "./File";
import {DialogBox} from "./DialogBox";
import {AuthUser} from "./User";
import {Database} from "./Database";
import {File} from "./File";
import {Editor} from "trs80-emulator/dist/Editor";
import {isRegisterSetField, isWordReg, Register, toHexWord} from "z80-base";
import {disasmForTrs80, disasmForTrs80Program} from "trs80-disasm";
class EmptyCassette extends CassettePlayer {
// Nothing to do.
}
function createNavbar(openLibrary: () => void, signIn: () => void, signOut: () => void): HTMLElement {
const body = document.querySelector("body") as HTMLElement;
const navbar = document.createElement("div");
navbar.classList.add("navbar");
const title = document.createElement("a");
title.classList.add("home-button");
title.textContent = "My TRS-80";
title.href = "/";
navbar.append(title);
const libraryButton = makeIconButton(makeIcon("folder_open"), "Open library (Ctrl-L)", openLibrary);
libraryButton.classList.add("library-button");
navbar.append(libraryButton);
const themeButton = makeIconButton(makeIcon("brightness_medium"), "Toggle theme", () => {
body.classList.toggle("light-mode");
body.classList.toggle("dark-mode");
});
themeButton.classList.add("theme-button");
navbar.append(themeButton);
const signInButton = makeTextButton("Sign In", "person", "sign-in-button", signIn);
const signOutButton = makeTextButton("Sign Out", "person", "sign-out-button", signOut);
navbar.append(signInButton, signOutButton);
return navbar;
}
const FLAG_STRING = "CNP3H5ZS"; // From LSB to MSB.
/**
* Convert an 8-bit flag byte to a debug string.
* TODO: Move this to z80-base.
*/
function makeFlagString(f: number): string {
let flagString = "";
for (let i = 0; i < 8; i++) {
flagString += (f & 0x01) !== 0 ? FLAG_STRING[i] : "-";
f >>= 1;
}
return flagString;
}
export function main() {
const args = Context.parseFragment(window.location.hash);
const runFileId = args.get("runFile")?.[0];
const userId = args.get("user")?.[0];
const body = document.querySelector("body") as HTMLElement;
body.classList.add("signed-out");
// Configuration for Firebase.
firebase.initializeApp({
apiKey: "AIzaSyAfGZY9BaDUmy4qNtg11JHd_kLd1JmgdBI",
authDomain: "my-trs-80.firebaseapp.com",
projectId: "my-trs-80",
storageBucket: "my-trs-80.appspot.com",
messagingSenderId: "438103442091",
appId: "1:438103442091:web:0fe42c43917ba1add52dee"
});
firebase.analytics();
// Configuration for Firebase sign-in screen.
const uiConfig = {
signInSuccessUrl: '/',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
// firebase.auth.FacebookAuthProvider.PROVIDER_ID,
// firebase.auth.TwitterAuthProvider.PROVIDER_ID,
// firebase.auth.GithubAuthProvider.PROVIDER_ID,
// firebase.auth.EmailAuthProvider.PROVIDER_ID,
// firebase.auth.PhoneAuthProvider.PROVIDER_ID,
// firebaseui.auth.AnonymousAuthProvider.PROVIDER_ID
],
// Pop up a browser window for the actual sign-in page:
signInFlow: "popup",
callbacks: {
signInSuccessWithAuthResult: (authResult: any): boolean => {
// Don't use stuff here, the user will get passed to onAuthStateChanged().
// I don't see much else useful in authResult.
// console.log(authResult);
// Don't redirect, we've taken care of it.
return false;
},
},
};
let firebaseAuth = firebase.auth();
const firebaseAuthUi = new firebaseui.auth.AuthUI(firebaseAuth);
const signInDiv = document.createElement("div");
const signInInstructions = document.createElement("div");
signInInstructions.classList.add("sign-in-instructions");
signInInstructions.innerText = "Sign in to My TRS-80 to have a persistent place to store your files.";
const signInFirebase = document.createElement("div");
signInDiv.append(signInInstructions, signInFirebase);
let signInDialog: DialogBox | undefined = undefined;
const db = new Database(firebase.firestore());
firebaseAuth.onAuthStateChanged(firebaseUser => {
if (firebaseUser !== null) {
//console.log(firebaseUser);
const authUser = AuthUser.fromFirebaseUser(firebaseUser);
db.userFromAuthUser(authUser)
.then(user => context.user = user)
.catch(error => {
// TODO.
console.error(error);
});
if (signInDialog !== undefined) {
signInDialog.close();
signInDialog = undefined;
}
} else {
// No user signed in, render sign-in UI.
firebaseAuthUi.reset();
firebaseAuthUi.start(signInFirebase, uiConfig);
context.user = undefined;
}
});
const panelManager = new PanelManager();
const library = new Library();
const navbar = createNavbar(
() => panelManager.open(),
() => {
if (signInDialog !== undefined) {
signInDialog.close();
}
signInDialog = new DialogBox("Sign In", signInDiv, "sign-in-dialog-box");
},
() => firebase.auth().signOut());
const screenDiv = document.createElement("div");
screenDiv.classList.add("main-computer-screen");
const screen = new CanvasScreen(1.5);
let cassette = new EmptyCassette();
const trs80 = new Trs80(screen, cassette);
const editor = new Editor(trs80, screen);
screenDiv.append(editor.node);
const reboot = () => {
trs80.reset();
trs80.start();
};
const hardwareSettingsPanel = new SettingsPanel(screen.getNode(), trs80, PanelType.HARDWARE);
const viewPanel = new SettingsPanel(screen.getNode(), trs80, PanelType.VIEW);
const controlPanel = new ControlPanel(screen.getNode());
controlPanel.addResetButton(reboot);
/* We don't currently mount a cassette.
controlPanel.addTapeRewindButton(() => {
// cassette.rewind();
});
*/
controlPanel.addSettingsButton(hardwareSettingsPanel);
controlPanel.addSettingsButton(viewPanel);
// const progressBar = new ProgressBar(screen.getNode());
// cassette.setProgressBar(progressBar);
controlPanel.addMuteButton(trs80.soundPlayer);
const driveIndicators = new DriveIndicators(screen.getNode());
trs80.onMotorOn.subscribe(drive => driveIndicators.setActiveDrive(drive));
body.append(navbar);
body.append(screenDiv);
let createdLibraryPanel = false;
let wasTrs80Started = false;
panelManager.onOpenClose.subscribe(isOpen => {
if (isOpen && !createdLibraryPanel) {
panelManager.pushPanel(new LibraryPanel(context));
createdLibraryPanel = true;
}
if (isOpen) {
wasTrs80Started = trs80.stop();
} else {
if (wasTrs80Started) {
trs80.start();
}
}
});
reboot();
const context = new Context(library, trs80, db, panelManager);
const screenshotButton = controlPanel.addScreenshotButton(() => {
if (context.runningFile !== undefined) {
let file = context.runningFile;
const screenshot = trs80.getScreenshot();
const screenshots = [...file.screenshots, screenshot]; // Don't modify original array.
file = file.builder()
.withScreenshots(screenshots)
.withModifiedAt(new Date())
.build();
context.db.updateFile(context.runningFile, file)
.then(() => context.library.modifyFile(file))
.catch(error => {
// TODO.
console.error(error);
});
}
});
// Start hidden, since the user isn't signed in until later.
screenshotButton.classList.add("hidden");
controlPanel.addEditorButton(() => editor.startEdit());
let logging = false;
const logs: string[] = [];
const MAX_LOGS = 16*1024;
const disasm = disasmForTrs80();
const readMemory = (address: number): number => trs80.readMemory(address);
let stepPc = 0;
trs80.onPreStep.subscribe(() => {
stepPc = trs80.z80.regs.pc;
});
trs80.onPostStep.subscribe(() => {
if (logging) {
const instruction = disasm.disassembleTrace(stepPc, readMemory);
const values: string[] = [];
for (const arg of instruction.args) {
for (const reg of arg.split(/[^a-zA-Z']+/)) {
const regExpanded = reg.replace("'", "Prime");
if (isRegisterSetField(regExpanded)) {
const value = trs80.z80.regs.getValue(regExpanded);
values.push(reg + "=" + toHexWord(value));
}
}
}
const line = toHexWord(stepPc) + " " +
instruction.binText().padEnd(11) + " " +
instruction.toText().padEnd(20) + " " +
makeFlagString(trs80.z80.regs.f) + " " +
values.join(", ");
logs.push(line.trimEnd());
if (logs.length > MAX_LOGS) {
logs.splice(0, logs.length - MAX_LOGS);
}
}
});
controlPanel.addResetButton(() => {
if (logging) {
const dump = logs.join("\n");
const blob = new Blob([dump], {type: "text/plain"});
const a = document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "trace.lst";
a.click();
logging = false;
} else {
logs.splice(0, logs.length);
logging = true;
}
});
/**
* Update whether the user can take a screenshot of the running program.
*/
function updateScreenshotButtonVisibility() {
const canSaveScreenshot = context.runningFile !== undefined &&
context.user !== undefined &&
context.runningFile.uid === context.user.uid;
screenshotButton.classList.toggle("hidden", !canSaveScreenshot);
}
context.onRunningFile.subscribe(() => {
window.location.hash = context.getFragment();
updateScreenshotButtonVisibility();
});
context.onUser.subscribe(user => {
body.classList.toggle("signed-in", user !== undefined);
body.classList.toggle("signed-out", user === undefined);
updateScreenshotButtonVisibility();
library.removeAll();
if (user !== undefined) {
// Fetch all files.
context.db.getAllFiles(userId ?? user.uid)
.then((querySnapshot) => {
// Sort files before adding them to the library so that they show up in the UI in order
// and the screenshots get loaded with the visible ones first.
const files: File[] = [];
for (const doc of querySnapshot.docs) {
files.push(FileBuilder.fromDoc(doc).build());
}
files.sort(File.compare);
for (const file of files) {
library.addFile(file);
// Update hash if necessary.
if (file.binary.length !== 0 && file.isOldHash()) {
// This updates the hash.
const newFile = file.builder().withBinary(file.binary).build();
console.log("Hash for " + file.name + " has been recomputed");
context.db.updateFile(file, newFile)
.then(() => {
library.modifyFile(newFile);
});
}
}
// We should now be in sync with the cloud database.
library.setInSync(true);
})
.catch(error => {
// TODO
console.error(error);
if (error.name === "FirebaseError") {
// code can be "permission-denied".
console.error(error.code, error.message);
}
});
}
});
// See if we should run an app right away.
context.onUserResolved.subscribe(() => {
// We're signed in, or not, and can now read the database.
if (runFileId !== undefined) {
db.getFile(runFileId)
.then(file => {
context.runProgram(file);
})
.catch(() => {
// TODO Should probably display error message.
});
}
});
}