-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathformat.ts
More file actions
256 lines (245 loc) · 8.35 KB
/
format.ts
File metadata and controls
256 lines (245 loc) · 8.35 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
enum Justification {
None,
Left,
Right
}
const justificationFunctions: (((line: string, maxLength: number) => string) | null)[] = [
null,
(line, maxLength) => line.padEnd(maxLength),
(line, maxLength) => line.padStart(maxLength)
];
const BASE_64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
/*
Encoding substitutions.
This maps UTF8 characters to their BBC Micro Mode 7 counterparts
where they differ from vanilla 1967 ASCII (e.g. the BBC Micro uses the
codepoint of ASCII # for the UK pound sign £) or aren't directly
convertible.
*/
const substitutions = {
'€': 'EUR',
'¥': 'JPY',
'°': 'deg',
'®': '(R)',
'©': '(C)',
'Å': 'Aa',
'å': 'aa',
'Æ': 'Ae',
'æ': 'ae',
'IJ': 'Ij',
'ij': 'ij',
'Œ': 'Oe',
'Ø': 'Oe',
'œ': 'oe',
'ø': 'oe',
'ß': 'ss',
'Þ': 'Th',
'þ': 'th',
'μ': 'u',
'‐': '-',
'‑': '-',
'‒': '`',
'–': '`',
'—': '`',
'―': '`',
'_': '`',
'£': '#',
'#': '_',
'`': '\'',
'‘': '\'',
'’': '\'',
'“': '"',
'”': '"',
'\\': '/',
'[': '(',
']': ')',
'←': '[',
'→': ']',
'↑': '^',
'½': '\\',
'¼': '{',
'¾': '}',
'~': 'approx.',
'÷': '~',
'‖': '|',
'ǀ': '|'
};
const getLines = (utf8Text: string, lineMaxLength: number, maxLines: number, justification: Justification):string[] => {
if (typeof utf8Text !== 'string' || utf8Text.length === 0) return [];
let text = transcodeUtf8ToBeeb(utf8Text);
let words = text.toString().match(/\S+/g) || [];
let lines = [];
let line = '';
while (words.length > 0) {
if (line.length == lineMaxLength) {
lines.push(line);
line = '';
}
let word = words.shift();
let wordStartToLineEnd = (lineMaxLength - (line.length + Math.min(line.length, 1)));
let overrun = word.length - wordStartToLineEnd;
if (overrun > 0) {
// The word is longer than the space left on the current line
// firstPart: the part of the word that would still fit
let firstPart = word.substring(0,wordStartToLineEnd);
if (firstPart.lastIndexOf('-') > 0) {
// There's already a hyphen in the firstPart
words.unshift(word.substring(firstPart.lastIndexOf('-')+1));
word = firstPart.substring(0,firstPart.lastIndexOf('-')+1);
} else if (wordStartToLineEnd > 4 && word.length > 7) {
// Hyphenate if the word is long enough and enough space would be lost
words.unshift(word.substring(wordStartToLineEnd-1));
word = word.substring(0,wordStartToLineEnd-1)+'-';
} else {
// Bump the word down to the next line
lines.push(line);
line = '';
if (word.length > lineMaxLength) {
words.unshift(word.substring(lineMaxLength-2));
word = word.substring(0,lineMaxLength-2)+'-';
}
}
}
line = line + ((line.length > 0) ? ' ' : '') + word;
}
if (line) lines.push(line);
if (maxLines && lines.length > maxLines) {
lines = lines.slice(0,maxLines);
let truncatedLine = maxLines - 1;
let truncatedText = lines[truncatedLine];
if (truncatedText.length + 3 > lineMaxLength || truncatedText.endsWith('-')) {
truncatedText = truncatedText.
substring(0,Math.min(truncatedText.length - 1, lineMaxLength - 3)) +
'...';
} else {
truncatedText = truncatedText + '...';
}
lines[truncatedLine] = truncatedText;
}
if (justification) {
for (let l = 0; l<lines.length; l++) {
lines[l] = justificationFunctions[justification](lines[l], lineMaxLength);
}
}
return lines;
}
/*
Transcodes UTF-8 text (such as might be fetched from web/RSS feeds) to text for BBC Micro display mode 7. Only
outputs printable characters, not control, colour or graphics codes.
*/
const transcodeUtf8ToBeeb = (inputText: string): string => {
const normalisedInput = inputText.normalize('NFKC');
let outputCharBuffers = [] as Buffer[];
for (let utfChar of normalisedInput) {
let outputBytes = Buffer.from(utfChar);
if (substitutions[utfChar]) {
outputBytes = Buffer.from(substitutions[utfChar]);
} else if (outputBytes.length > 1) {
// We have a chonky UTF8 character which we haven't found a known substitution
// for. The only characters we will still try to translate at this point are
// latin ones with diacritics e.g. ē to e.
// This did used to use iconv, but it was more hassle than it was worth in this
// situation given the native dependency and that it doesn't directly support
// our antiquated target charset ;) iconv-lite doesn't do even basic latin
// transliteration, so just switching from composed to decomposed form and then
// stripping diacritics here directly instead. More complex substitutions like
// æ to ae are already handled above.
outputBytes = Buffer.from(utfChar.normalize('NFD').replace(/[\u0300-\u036f]/g, ''));
// If we still don't have an ETSI-friendly 1-byte character, use a
// space instead
if (outputBytes.length > 1 || outputBytes[0] > 126 || outputBytes[0] < 32) {
outputBytes = Buffer.from([0x20]);
}
}
outputCharBuffers.push(outputBytes);
}
const outputBuffer = Buffer.concat(outputCharBuffers);
let beebString = '';
for (let outChar of outputBuffer) {
beebString += String.fromCharCode(outChar);
}
return beebString;
};
/*
To and from b64 onversion functions lifted from edit.tf
Convert a frame in Base64 to BBC Micro Mode 7 display RAM format
*/
const b64ToMode7RAM = (frame: string): string => {
let currentcode = 0;
let rawOutput = '';
for (let p = 0; p < frame.length; p++) {
let pc = frame.charAt(p);
let pc_dec = BASE_64.indexOf(pc);
for (let b = 0; b < 6; b++) {
let charbit = (6*p + b) % 7;
let b64bit = pc_dec & (1 << (5 - b) );
if (b64bit > 0) {
b64bit = 1;
}
currentcode |= b64bit << (6 - charbit);
if (charbit == 6) {
// we have all the bits for a complete character code!
rawOutput += String.fromCharCode(currentcode);
currentcode = 0;
}
}
}
return rawOutput;
};
/*
Writes out a raw memory frame as base-64.
*/
const rawToB64 = (raw: string): string => {
let sextets = [];
let encoding = '';
for ( let i = 0; i < 1167; i++ ) {
sextets[i] = 0;
}
for ( let p=0; p<raw.length; p++) {
for ( let b=0; b<7; b++ ) {
// How many bits into the frame information we
// are.
const framebit = 7 * p + b;
// Work out the position of the character in the
// base-64 encoding and the bit in that position.
const b64bitoffset = framebit % 6;
const b64charoffset = ( framebit - b64bitoffset ) / 6;
// Read a bit and write a bit.
var bitval = raw.charCodeAt(p) & ( 1 << ( 6 - b ));
if ( bitval > 0 ) { bitval = 1; }
sextets[b64charoffset] |= bitval << ( 5 - b64bitoffset );
}
}
for ( var i = 0; i < 1167; i++ ) {
encoding += BASE_64.charAt(sextets[i]);
}
return encoding;
}
/*
Writes out a raw memory frame as a JavaScript literal string.
Escapes any Mode 7 control codes and the double quote mark.
*/
const rawToJsStringLiteral = (raw: string): string => {
let literal = '"';
for (let p = 0; p < raw.length; p++) {
if (p % 40 === 0 && p > 0) literal += '" + \n"';
let pchar = raw.charAt(p);
let pcode = pchar.charCodeAt(0);
if (pcode > 0x7f) { throw new Error(`Invalid videotex codepoint ${pcode}`) };
if (pcode < 0x20 || pcode === 0x7f || pcode === 0x22) {
literal += ('\\u00' + pcode.toString(16).padStart(2, '0'));
} else {
literal += pchar;
}
}
literal += '"';
return literal;
};
export {
Justification,
getLines,
transcodeUtf8ToBeeb,
b64ToMode7RAM,
rawToB64,
rawToJsStringLiteral
};