aboutsummaryrefslogtreecommitdiff
path: root/bundle/src/main.js
blob: 56cbff609fe0a69cea090ed9ddd6a4b3b50c6fdf (plain)
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

import { invoke, Channel } from '@tauri-apps/api/core';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { open, save, message } from '@tauri-apps/plugin-dialog';
import { createEditor } from './editor.js';
import './style.css';

const status = document.querySelector('#status');
const filename = document.querySelector('#filename');
const input = document.querySelector('#input');
const output = document.querySelector('#output');
const runButton = document.querySelector('#run');
const window = getCurrentWindow();
const filters = [{ name: 'Pseudocode', extensions: ['cps'] }];
let path = null;
let savedText = '';
let busy = false;
let closing = false;
let editor;
let running = false;

function setRunning(value) {
	running = value;
	runButton.textContent = value ? 'Stop' : 'Run';
	for (const id of ['new', 'open', 'save']) document.getElementById(id).disabled = value;
	input.disabled = value;
	editor.updateOptions({ readOnly: value });
}

async function runFile() {
	if (!await saveFile()) return;
	setRunning(true);
	output.textContent = '';
	status.textContent = 'Running';
	const decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
	let pending = '';
	let frame = null;
	function flush() {
		frame = null;
		if (!pending) return;
		output.append(document.createTextNode(pending));
		pending = '';
		output.scrollTop = output.scrollHeight;
	}
	function append(text) {
		pending += text;
		if (frame === null) frame = requestAnimationFrame(flush);
	}
	let finish;
	const finished = new Promise(resolve => { finish = resolve; });
	const channel = new Channel(event => {
		if (event.event === 'data') {
			append(decoders[event.stream].decode(Uint8Array.from(event.bytes), { stream: true }));
		} else if (event.event === 'finished') {
			for (const decoder of Object.values(decoders)) append(decoder.decode());
			if (frame !== null) cancelAnimationFrame(frame);
			flush();
			status.textContent = event.stopped ? 'Stopped' : `Exit code: ${event.code ?? 'terminated'}`;
			finish();
		}
	});
	try {
		await invoke('run_file', { path, input: input.value, output: channel });
		await finished;
	} finally {
		if (frame !== null) cancelAnimationFrame(frame);
		flush();
		setRunning(false);
	}
}

function dirty() { return editor.getValue() !== savedText; }
function refreshTitle() {
	const name = path ? path.split(/[\\/]/).pop() : 'Untitled.cps';
	filename.textContent = `${dirty() ? '* ' : ''}${name}`;
	filename.title = path || name;
	window.setTitle(`${dirty() ? '* ' : ''}${name} — CPSC Bundle`);
}
function report(error) { status.textContent = String(error); }
async function saveFile() {
	const target = path || await save({ filters, defaultPath: 'Untitled.cps' });
	if (!target) return false;
	const text = editor.getValue();
	await invoke('write_file', { path: target, text });
	path = target;
	savedText = text;
	refreshTitle();
	status.textContent = 'Saved';
	return true;
}
async function canReplace() {
	if (!dirty()) return true;
	const answer = await message('Save changes?', {
		title: 'CPSC Bundle', kind: 'warning',
		buttons: { yes: 'Save', no: 'Discard', cancel: 'Cancel' }
	});
	if (answer === 'Cancel') return false;
	return answer === 'Discard' || await saveFile();
}
async function action(callback) {
	if (busy || running) return;
	busy = true;
	try { await callback(); } catch (error) { report(error); } finally { busy = false; }
}

try {
	editor = await createEditor(document.querySelector('#editor'));
	editor.onDidChangeModelContent(refreshTitle);
	runButton.onclick = () => {
		if (running) {
			invoke('stop_run').catch(report);
		} else {
			action(runFile);
		}
	};
	document.querySelector('#save').onclick = () => action(saveFile);
	document.querySelector('#new').onclick = () => action(async () => {
		if (!await canReplace()) return;
		path = null;
		savedText = '';
		editor.setValue('');
		refreshTitle();
		status.textContent = 'Ready';
	});
	document.querySelector('#open').onclick = () => action(async () => {
		if (!await canReplace()) return;
		const target = await open({ filters, multiple: false });
		if (!target) return;
		const text = await invoke('read_file', { path: target });
		path = target;
		savedText = text;
		editor.setValue(text);
		refreshTitle();
		status.textContent = 'Ready';
	});
	document.addEventListener('keydown', event => {
		if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
			event.preventDefault();
			action(saveFile);
		}
	});
	await window.onCloseRequested(async event => {
		if (closing) return;
		event.preventDefault();
		if (running) {
			try { await invoke('stop_run'); } catch (error) { report(error); return; }
			// The command drains pipes before completing; let runFile release its UI lock.
			busy = false;
			setRunning(false);
		}
		await action(async () => {
			if (!await canReplace()) return;
			closing = true;
			await window.close();
		});
	});
	editor.focus();
} catch (error) { report(error); }