@willwade/aac-processors 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/browser/index.browser.js +15 -1
- package/dist/browser/processors/gridset/password.js +11 -0
- package/dist/browser/processors/gridsetProcessor.js +42 -46
- package/dist/browser/processors/obfProcessor.js +47 -63
- package/dist/browser/processors/snapProcessor.js +1031 -0
- package/dist/browser/processors/touchchatProcessor.js +1004 -0
- package/dist/browser/utils/io.js +36 -2
- package/dist/browser/utils/sqlite.js +109 -0
- package/dist/browser/utils/zip.js +54 -0
- package/dist/browser/validation/gridsetValidator.js +7 -27
- package/dist/browser/validation/obfValidator.js +9 -4
- package/dist/browser/validation/snapValidator.js +197 -0
- package/dist/browser/validation/touchChatValidator.js +201 -0
- package/dist/index.browser.d.ts +7 -0
- package/dist/index.browser.js +19 -2
- package/dist/processors/gridset/helpers.js +3 -4
- package/dist/processors/gridset/index.d.ts +1 -1
- package/dist/processors/gridset/index.js +3 -2
- package/dist/processors/gridset/password.d.ts +3 -2
- package/dist/processors/gridset/password.js +12 -0
- package/dist/processors/gridset/wordlistHelpers.js +107 -51
- package/dist/processors/gridsetProcessor.js +40 -44
- package/dist/processors/obfProcessor.js +46 -62
- package/dist/processors/snapProcessor.js +60 -54
- package/dist/processors/touchchatProcessor.js +38 -36
- package/dist/utils/io.d.ts +4 -0
- package/dist/utils/io.js +40 -2
- package/dist/utils/sqlite.d.ts +21 -0
- package/dist/utils/sqlite.js +137 -0
- package/dist/utils/zip.d.ts +7 -0
- package/dist/utils/zip.js +80 -0
- package/dist/validation/applePanelsValidator.js +11 -28
- package/dist/validation/astericsValidator.js +11 -30
- package/dist/validation/dotValidator.js +11 -30
- package/dist/validation/excelValidator.js +5 -6
- package/dist/validation/gridsetValidator.js +29 -26
- package/dist/validation/index.d.ts +2 -1
- package/dist/validation/index.js +9 -32
- package/dist/validation/obfValidator.js +8 -3
- package/dist/validation/obfsetValidator.js +11 -30
- package/dist/validation/opmlValidator.js +11 -30
- package/dist/validation/snapValidator.js +6 -9
- package/dist/validation/touchChatValidator.js +6 -7
- package/docs/BROWSER_USAGE.md +2 -10
- package/examples/README.md +3 -75
- package/examples/vitedemo/README.md +13 -7
- package/examples/vitedemo/index.html +51 -2
- package/examples/vitedemo/package-lock.json +9 -0
- package/examples/vitedemo/package.json +1 -0
- package/examples/vitedemo/src/main.ts +132 -2
- package/examples/vitedemo/src/vite-env.d.ts +1 -0
- package/examples/vitedemo/vite.config.ts +26 -7
- package/package.json +3 -1
- package/examples/browser-test-server.js +0 -81
|
@@ -0,0 +1,1004 @@
|
|
|
1
|
+
import { BaseProcessor, } from '../core/baseProcessor';
|
|
2
|
+
import { AACTree, AACPage, AACButton, AACSemanticCategory, AACSemanticIntent, } from '../core/treeStructure';
|
|
3
|
+
import { generateCloneId } from '../utilities/analytics/utils/idGenerator';
|
|
4
|
+
import { detectCasing, isNumericOrEmpty } from '../core/stringCasing';
|
|
5
|
+
import { TouchChatValidator } from '../validation/touchChatValidator';
|
|
6
|
+
import { getFs, getNodeRequire, getOs, getPath, isNodeRuntime, readBinaryFromInput, } from '../utils/io';
|
|
7
|
+
import { extractAllButtonsForTranslation, validateTranslationResults, } from '../utilities/translation/translationProcessor';
|
|
8
|
+
import { openSqliteDatabase, requireBetterSqlite3, } from '../utils/sqlite';
|
|
9
|
+
import { openZipFromInput } from '../utils/zip';
|
|
10
|
+
const toNumberOrUndefined = (value) => typeof value === 'number' ? value : undefined;
|
|
11
|
+
const toStringOrUndefined = (value) => typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
12
|
+
const toBooleanOrUndefined = (value) => typeof value === 'number' ? value !== 0 : undefined;
|
|
13
|
+
function intToHex(colorInt) {
|
|
14
|
+
if (colorInt === null || typeof colorInt === 'undefined') {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
// Assuming the color is in ARGB format, we mask out the alpha channel
|
|
18
|
+
return `#${(colorInt & 0x00ffffff).toString(16).padStart(6, '0')}`;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Map TouchChat visible value to AAC standard visibility
|
|
22
|
+
* TouchChat: 0 = Hidden, 1 = Visible
|
|
23
|
+
* Maps to: 'Hidden' | 'Visible' | undefined
|
|
24
|
+
*/
|
|
25
|
+
function mapTouchChatVisibility(visible) {
|
|
26
|
+
if (visible === null || visible === undefined) {
|
|
27
|
+
return undefined; // Default to visible
|
|
28
|
+
}
|
|
29
|
+
return visible === 0 ? 'Hidden' : 'Visible';
|
|
30
|
+
}
|
|
31
|
+
class TouchChatProcessor extends BaseProcessor {
|
|
32
|
+
constructor(options) {
|
|
33
|
+
super(options);
|
|
34
|
+
this.tree = null;
|
|
35
|
+
this.sourceFile = null;
|
|
36
|
+
}
|
|
37
|
+
async extractTexts(filePathOrBuffer) {
|
|
38
|
+
// Extracts all button labels/texts from TouchChat .ce file
|
|
39
|
+
if (!this.tree && filePathOrBuffer) {
|
|
40
|
+
this.tree = await this.loadIntoTree(filePathOrBuffer);
|
|
41
|
+
}
|
|
42
|
+
if (!this.tree) {
|
|
43
|
+
throw new Error('No tree available - call loadIntoTree first');
|
|
44
|
+
}
|
|
45
|
+
const texts = [];
|
|
46
|
+
for (const pageId in this.tree.pages) {
|
|
47
|
+
const page = this.tree.pages[pageId];
|
|
48
|
+
page.buttons.forEach((btn) => {
|
|
49
|
+
if (btn.label)
|
|
50
|
+
texts.push(btn.label);
|
|
51
|
+
if (btn.message && btn.message !== btn.label)
|
|
52
|
+
texts.push(btn.message);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return texts;
|
|
56
|
+
}
|
|
57
|
+
async loadIntoTree(filePathOrBuffer) {
|
|
58
|
+
await Promise.resolve();
|
|
59
|
+
// Unzip .ce file, extract the .c4v SQLite DB, and parse pages/buttons
|
|
60
|
+
let db = null;
|
|
61
|
+
let cleanup;
|
|
62
|
+
try {
|
|
63
|
+
// Store source file path or buffer
|
|
64
|
+
this.sourceFile = filePathOrBuffer;
|
|
65
|
+
// Step 1: Unzip
|
|
66
|
+
const zipInput = readBinaryFromInput(filePathOrBuffer);
|
|
67
|
+
const { zip } = await openZipFromInput(zipInput);
|
|
68
|
+
const vocabEntry = zip.listFiles().find((name) => name.endsWith('.c4v'));
|
|
69
|
+
if (!vocabEntry) {
|
|
70
|
+
throw new Error('No .c4v vocab DB found in TouchChat export');
|
|
71
|
+
}
|
|
72
|
+
const dbBuffer = await zip.readFile(vocabEntry);
|
|
73
|
+
const dbResult = await openSqliteDatabase(dbBuffer, { readonly: true });
|
|
74
|
+
db = dbResult.db;
|
|
75
|
+
cleanup = dbResult.cleanup;
|
|
76
|
+
// Step 3: Create tree and load pages
|
|
77
|
+
const tree = new AACTree();
|
|
78
|
+
// Set root ID to the first page ID (will be updated if we find a better root)
|
|
79
|
+
let rootPageId = null;
|
|
80
|
+
const getTableColumns = (tableName) => {
|
|
81
|
+
if (!db)
|
|
82
|
+
return new Set();
|
|
83
|
+
try {
|
|
84
|
+
const rows = db.prepare(`PRAGMA table_info(${tableName})`).all();
|
|
85
|
+
return new Set(rows.map((row) => row.name));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return new Set();
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
// Load ID mappings first
|
|
92
|
+
const idMappings = new Map();
|
|
93
|
+
const numericToRid = new Map();
|
|
94
|
+
try {
|
|
95
|
+
const mappingQuery = 'SELECT numeric_id, string_id FROM page_id_mapping';
|
|
96
|
+
const mappings = db.prepare(mappingQuery).all();
|
|
97
|
+
mappings.forEach((mapping) => {
|
|
98
|
+
idMappings.set(mapping.numeric_id, mapping.string_id);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
// No mapping table, use numeric IDs as strings
|
|
103
|
+
}
|
|
104
|
+
// Load styles
|
|
105
|
+
const buttonStyles = new Map();
|
|
106
|
+
const pageStyles = new Map();
|
|
107
|
+
try {
|
|
108
|
+
const buttonStyleRows = db
|
|
109
|
+
.prepare('SELECT * FROM button_styles')
|
|
110
|
+
.all();
|
|
111
|
+
buttonStyleRows.forEach((style) => {
|
|
112
|
+
buttonStyles.set(style.id, style);
|
|
113
|
+
});
|
|
114
|
+
const pageStyleRows = db.prepare('SELECT * FROM page_styles').all();
|
|
115
|
+
pageStyleRows.forEach((style) => {
|
|
116
|
+
pageStyles.set(style.id, style);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
// console.log('No styles found:', e);
|
|
121
|
+
}
|
|
122
|
+
// First, load all pages and get their names from resources
|
|
123
|
+
const resourceColumns = getTableColumns('resources');
|
|
124
|
+
const hasRid = resourceColumns.has('rid');
|
|
125
|
+
const pageQuery = `
|
|
126
|
+
SELECT p.*, r.name${hasRid ? ', r.rid' : ''}
|
|
127
|
+
FROM pages p
|
|
128
|
+
JOIN resources r ON r.id = p.resource_id
|
|
129
|
+
`;
|
|
130
|
+
const pages = db.prepare(pageQuery).all();
|
|
131
|
+
pages.forEach((pageRow) => {
|
|
132
|
+
// Use resource RID (UUID) if available, otherwise mapped string ID, then numeric ID
|
|
133
|
+
const pageId = (hasRid ? pageRow.rid : null) || idMappings.get(pageRow.id) || String(pageRow.id);
|
|
134
|
+
numericToRid.set(pageRow.id, pageId);
|
|
135
|
+
const style = pageStyles.get(pageRow.page_style_id);
|
|
136
|
+
const page = new AACPage({
|
|
137
|
+
id: pageId,
|
|
138
|
+
name: pageRow.name || '',
|
|
139
|
+
grid: [],
|
|
140
|
+
buttons: [],
|
|
141
|
+
parentId: null,
|
|
142
|
+
style: {
|
|
143
|
+
backgroundColor: intToHex(style?.bg_color),
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
tree.addPage(page);
|
|
147
|
+
// Set the first page as root if no root is set
|
|
148
|
+
if (!rootPageId) {
|
|
149
|
+
rootPageId = pageId;
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
// Load button boxes and their cells
|
|
153
|
+
const buttonBoxQuery = `
|
|
154
|
+
SELECT bbc.*, b.*, bb.id as box_id, bb.layout_x, bb.layout_y
|
|
155
|
+
FROM button_box_cells bbc
|
|
156
|
+
JOIN buttons b ON b.resource_id = bbc.resource_id
|
|
157
|
+
JOIN button_boxes bb ON bb.id = bbc.button_box_id
|
|
158
|
+
`;
|
|
159
|
+
try {
|
|
160
|
+
const buttonBoxCells = db.prepare(buttonBoxQuery).all();
|
|
161
|
+
const buttonBoxes = new Map();
|
|
162
|
+
buttonBoxCells.forEach((cell) => {
|
|
163
|
+
let boxData = buttonBoxes.get(cell.box_id);
|
|
164
|
+
if (!boxData) {
|
|
165
|
+
boxData = {
|
|
166
|
+
layoutX: cell.layout_x || 10,
|
|
167
|
+
layoutY: cell.layout_y || 6,
|
|
168
|
+
buttons: [],
|
|
169
|
+
};
|
|
170
|
+
buttonBoxes.set(cell.box_id, boxData);
|
|
171
|
+
}
|
|
172
|
+
const style = buttonStyles.get(cell.button_style_id);
|
|
173
|
+
// Create semantic action for TouchChat button
|
|
174
|
+
const semanticAction = {
|
|
175
|
+
category: AACSemanticCategory.COMMUNICATION,
|
|
176
|
+
intent: AACSemanticIntent.SPEAK_TEXT,
|
|
177
|
+
text: cell.message || cell.label || '',
|
|
178
|
+
platformData: {
|
|
179
|
+
touchChat: {
|
|
180
|
+
actionCode: 0, // Default speak action
|
|
181
|
+
actionData: cell.message || cell.label || '',
|
|
182
|
+
resourceId: cell.resource_id,
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
fallback: {
|
|
186
|
+
type: 'SPEAK',
|
|
187
|
+
message: cell.message || cell.label || '',
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
const button = new AACButton({
|
|
191
|
+
id: String(cell.id),
|
|
192
|
+
label: cell.label || '',
|
|
193
|
+
message: cell.message || '',
|
|
194
|
+
semanticAction: semanticAction,
|
|
195
|
+
semantic_id: (cell.symbol_link_id || cell.symbolLinkId) || undefined, // Extract semantic_id from symbol_link_id
|
|
196
|
+
visibility: mapTouchChatVisibility(cell.visible || undefined),
|
|
197
|
+
// Note: TouchChat does not use scan blocks in the file
|
|
198
|
+
// Scanning is a runtime feature (linear/row-column patterns)
|
|
199
|
+
// scanBlock defaults to 1 (no grouping)
|
|
200
|
+
style: {
|
|
201
|
+
backgroundColor: intToHex(style?.body_color),
|
|
202
|
+
borderColor: intToHex(style?.border_color),
|
|
203
|
+
borderWidth: toNumberOrUndefined(style?.border_width),
|
|
204
|
+
fontColor: intToHex(style?.font_color),
|
|
205
|
+
fontSize: toNumberOrUndefined(style?.font_height),
|
|
206
|
+
fontFamily: toStringOrUndefined(style?.font_name),
|
|
207
|
+
fontWeight: style?.font_bold ? 'bold' : undefined,
|
|
208
|
+
fontStyle: style?.font_italic ? 'italic' : undefined,
|
|
209
|
+
textUnderline: toBooleanOrUndefined(style?.font_underline),
|
|
210
|
+
transparent: toBooleanOrUndefined(style?.transparent),
|
|
211
|
+
labelOnTop: toBooleanOrUndefined(style?.label_on_top),
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
boxData.buttons.push({
|
|
215
|
+
button,
|
|
216
|
+
location: cell.location || 0,
|
|
217
|
+
spanX: cell.span_x || 1,
|
|
218
|
+
spanY: cell.span_y || 1,
|
|
219
|
+
});
|
|
220
|
+
});
|
|
221
|
+
// Map button boxes to pages
|
|
222
|
+
const boxInstances = db.prepare('SELECT * FROM button_box_instances').all();
|
|
223
|
+
// Create a map to track page grid layouts
|
|
224
|
+
const pageGrids = new Map();
|
|
225
|
+
boxInstances.forEach((instance) => {
|
|
226
|
+
// Use mapped string ID if available, otherwise use numeric ID as string
|
|
227
|
+
const pageId = numericToRid.get(instance.page_id) || String(instance.page_id);
|
|
228
|
+
const page = tree.getPage(pageId);
|
|
229
|
+
const boxData = buttonBoxes.get(instance.button_box_id);
|
|
230
|
+
if (page && boxData) {
|
|
231
|
+
// Initialize page grid if not exists (assume max 10x10 grid)
|
|
232
|
+
if (!pageGrids.has(pageId)) {
|
|
233
|
+
const grid = [];
|
|
234
|
+
for (let r = 0; r < 10; r++) {
|
|
235
|
+
grid[r] = new Array(10).fill(null);
|
|
236
|
+
}
|
|
237
|
+
pageGrids.set(pageId, grid);
|
|
238
|
+
}
|
|
239
|
+
const pageGrid = pageGrids.get(pageId);
|
|
240
|
+
if (!pageGrid)
|
|
241
|
+
return;
|
|
242
|
+
const boxX = Number(instance.position_x) || 0;
|
|
243
|
+
const boxY = Number(instance.position_y) || 0;
|
|
244
|
+
const boxWidth = boxData.layoutX; // Use layout_x from button_boxes, not size_x from instance
|
|
245
|
+
// boxHeight not currently used but kept for future span calculations
|
|
246
|
+
// const boxHeight = boxData.layoutY;
|
|
247
|
+
boxData.buttons.forEach(({ button, location, spanX, spanY }) => {
|
|
248
|
+
const safeLocation = Number(location) || 0;
|
|
249
|
+
const safeSpanX = Number(spanX) || 1;
|
|
250
|
+
const safeSpanY = Number(spanY) || 1;
|
|
251
|
+
// Calculate button position within the button box
|
|
252
|
+
// location is a linear index, convert to grid coordinates
|
|
253
|
+
const buttonX = safeLocation % boxWidth;
|
|
254
|
+
const buttonY = Math.floor(safeLocation / boxWidth);
|
|
255
|
+
// Calculate absolute position on page
|
|
256
|
+
const absoluteX = boxX + buttonX;
|
|
257
|
+
const absoluteY = boxY + buttonY;
|
|
258
|
+
// Set button's x and y coordinates
|
|
259
|
+
button.x = absoluteX;
|
|
260
|
+
button.y = absoluteY;
|
|
261
|
+
// Add button to page
|
|
262
|
+
page.addButton(button);
|
|
263
|
+
// Place button in grid (handle span)
|
|
264
|
+
for (let r = absoluteY; r < absoluteY + safeSpanY && r < 10; r++) {
|
|
265
|
+
for (let c = absoluteX; c < absoluteX + safeSpanX && c < 10; c++) {
|
|
266
|
+
if (pageGrid && pageGrid[r] && pageGrid[r][c] === null) {
|
|
267
|
+
pageGrid[r][c] = button;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
// Set grid layouts for all pages
|
|
275
|
+
pageGrids.forEach((grid, pageId) => {
|
|
276
|
+
const page = tree.getPage(pageId);
|
|
277
|
+
if (page) {
|
|
278
|
+
page.grid = grid;
|
|
279
|
+
// Generate clone_id for each button in the grid
|
|
280
|
+
const semanticIds = [];
|
|
281
|
+
const cloneIds = [];
|
|
282
|
+
grid.forEach((row, rowIndex) => {
|
|
283
|
+
row.forEach((btn, colIndex) => {
|
|
284
|
+
if (btn) {
|
|
285
|
+
// Generate clone_id based on position and label
|
|
286
|
+
const rows = grid.length;
|
|
287
|
+
const cols = grid[0] ? grid[0].length : 10;
|
|
288
|
+
btn.clone_id = generateCloneId(rows, cols, rowIndex, colIndex, btn.label);
|
|
289
|
+
cloneIds.push(btn.clone_id);
|
|
290
|
+
// Track semantic_id if present
|
|
291
|
+
if (btn.semantic_id) {
|
|
292
|
+
semanticIds.push(btn.semantic_id);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
// Track IDs on the page
|
|
298
|
+
if (semanticIds.length > 0) {
|
|
299
|
+
page.semantic_ids = semanticIds;
|
|
300
|
+
}
|
|
301
|
+
if (cloneIds.length > 0) {
|
|
302
|
+
page.clone_ids = cloneIds;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
catch (e) {
|
|
308
|
+
// console.log('No button box cells found:', e);
|
|
309
|
+
}
|
|
310
|
+
// Load buttons directly linked to pages via resources
|
|
311
|
+
const pageButtonsQuery = `
|
|
312
|
+
SELECT b.*, r.*
|
|
313
|
+
FROM buttons b
|
|
314
|
+
JOIN resources r ON r.id = b.resource_id
|
|
315
|
+
WHERE r.type = 7
|
|
316
|
+
`;
|
|
317
|
+
try {
|
|
318
|
+
const pageButtons = db.prepare(pageButtonsQuery).all();
|
|
319
|
+
pageButtons.forEach((btnRow) => {
|
|
320
|
+
const style = buttonStyles.get(btnRow.button_style_id);
|
|
321
|
+
// Create semantic action for TouchChat button
|
|
322
|
+
const semanticAction = {
|
|
323
|
+
category: AACSemanticCategory.COMMUNICATION,
|
|
324
|
+
intent: AACSemanticIntent.SPEAK_TEXT,
|
|
325
|
+
text: btnRow.message || btnRow.label || '',
|
|
326
|
+
platformData: {
|
|
327
|
+
touchChat: {
|
|
328
|
+
actionCode: 0, // Default speak action
|
|
329
|
+
actionData: btnRow.message || btnRow.label || '',
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
fallback: {
|
|
333
|
+
type: 'SPEAK',
|
|
334
|
+
message: btnRow.message || btnRow.label || '',
|
|
335
|
+
},
|
|
336
|
+
};
|
|
337
|
+
const button = new AACButton({
|
|
338
|
+
id: String(btnRow.id),
|
|
339
|
+
label: btnRow.label || '',
|
|
340
|
+
message: btnRow.message || '',
|
|
341
|
+
semanticAction: semanticAction,
|
|
342
|
+
visibility: mapTouchChatVisibility(btnRow.visible),
|
|
343
|
+
// Note: TouchChat does not use scan blocks in the file
|
|
344
|
+
// Scanning is a runtime feature (linear/row-column patterns)
|
|
345
|
+
// scanBlock defaults to 1 (no grouping)
|
|
346
|
+
style: {
|
|
347
|
+
backgroundColor: intToHex(style?.body_color),
|
|
348
|
+
borderColor: intToHex(style?.border_color),
|
|
349
|
+
borderWidth: toNumberOrUndefined(style?.border_width),
|
|
350
|
+
fontColor: intToHex(style?.font_color),
|
|
351
|
+
fontSize: toNumberOrUndefined(style?.font_height),
|
|
352
|
+
fontFamily: toStringOrUndefined(style?.font_name),
|
|
353
|
+
fontWeight: style?.font_bold ? 'bold' : undefined,
|
|
354
|
+
fontStyle: style?.font_italic ? 'italic' : undefined,
|
|
355
|
+
textUnderline: toBooleanOrUndefined(style?.font_underline),
|
|
356
|
+
transparent: toBooleanOrUndefined(style?.transparent),
|
|
357
|
+
labelOnTop: toBooleanOrUndefined(style?.label_on_top),
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
// Find the page that references this resource
|
|
361
|
+
const page = Object.values(tree.pages).find((p) => p.id === (numericToRid.get(btnRow.id) || String(btnRow.id)));
|
|
362
|
+
if (page)
|
|
363
|
+
page.addButton(button);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
catch (e) {
|
|
367
|
+
// console.log('No direct page buttons found:', e);
|
|
368
|
+
}
|
|
369
|
+
// Load navigation actions
|
|
370
|
+
const navActionsQuery = `
|
|
371
|
+
SELECT a.resource_id, COALESCE(${hasRid ? 'r_rid.rid, r_id.rid, ' : ''}r_id.id, ad.value) as target_page_id
|
|
372
|
+
FROM actions a
|
|
373
|
+
JOIN action_data ad ON ad.action_id = a.id
|
|
374
|
+
${hasRid ? 'LEFT JOIN resources r_rid ON r_rid.rid = ad.value AND r_rid.type = 7' : ''}
|
|
375
|
+
LEFT JOIN resources r_id ON (CASE WHEN ad.value GLOB '[0-9]*' THEN CAST(ad.value AS INTEGER) ELSE -1 END) = r_id.id AND r_id.type = 7
|
|
376
|
+
WHERE a.code IN (1, 8, 9)
|
|
377
|
+
`;
|
|
378
|
+
try {
|
|
379
|
+
const navActions = db.prepare(navActionsQuery).all();
|
|
380
|
+
navActions.forEach((nav) => {
|
|
381
|
+
// Find button in any page by its resourceId
|
|
382
|
+
for (const pageId in tree.pages) {
|
|
383
|
+
const page = tree.pages[pageId];
|
|
384
|
+
const button = page.buttons.find((b) => b.semanticAction?.platformData?.touchChat?.resourceId === nav.resource_id);
|
|
385
|
+
if (button) {
|
|
386
|
+
// Use mapped string ID for target page if available
|
|
387
|
+
const numericTargetId = parseInt(String(nav.target_page_id));
|
|
388
|
+
const targetPageId = !isNaN(numericTargetId)
|
|
389
|
+
? numericToRid.get(numericTargetId) || String(numericTargetId)
|
|
390
|
+
: String(nav.target_page_id);
|
|
391
|
+
button.targetPageId = targetPageId;
|
|
392
|
+
// Create semantic action for navigation
|
|
393
|
+
button.semanticAction = {
|
|
394
|
+
category: AACSemanticCategory.NAVIGATION,
|
|
395
|
+
intent: AACSemanticIntent.NAVIGATE_TO,
|
|
396
|
+
targetId: String(targetPageId),
|
|
397
|
+
platformData: {
|
|
398
|
+
touchChat: {
|
|
399
|
+
actionCode: 1, // TouchChat navigation code
|
|
400
|
+
actionData: String(targetPageId),
|
|
401
|
+
},
|
|
402
|
+
},
|
|
403
|
+
fallback: {
|
|
404
|
+
type: 'NAVIGATE',
|
|
405
|
+
targetPageId: String(targetPageId),
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
catch (e) {
|
|
414
|
+
// console.log('No navigation actions found:', e);
|
|
415
|
+
}
|
|
416
|
+
// Try to load root ID from multiple sources in order of priority
|
|
417
|
+
try {
|
|
418
|
+
// First, try to get HOME page from special_pages table (TouchChat specific)
|
|
419
|
+
const specialPagesQuery = "SELECT page_id FROM special_pages WHERE name = 'HOME'";
|
|
420
|
+
const homePageRow = db.prepare(specialPagesQuery).get();
|
|
421
|
+
if (homePageRow) {
|
|
422
|
+
// The page_id is the page's id (not resource_id), need to get the RID
|
|
423
|
+
const homePageIdQuery = `
|
|
424
|
+
SELECT p.id, r.rid
|
|
425
|
+
FROM pages p
|
|
426
|
+
JOIN resources r ON r.id = p.resource_id
|
|
427
|
+
WHERE p.id = ?
|
|
428
|
+
LIMIT 1
|
|
429
|
+
`;
|
|
430
|
+
const homePage = db.prepare(homePageIdQuery).get(homePageRow.page_id);
|
|
431
|
+
if (homePage) {
|
|
432
|
+
const homePageUUID = homePage.rid || String(homePage.id);
|
|
433
|
+
if (tree.getPage(homePageUUID)) {
|
|
434
|
+
tree.rootId = homePageUUID;
|
|
435
|
+
tree.metadata.defaultHomePageId = homePageUUID;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
// If no HOME page found, try tree_metadata table (general fallback)
|
|
440
|
+
if (!tree.rootId) {
|
|
441
|
+
const metadataQuery = "SELECT value FROM tree_metadata WHERE key = 'rootId'";
|
|
442
|
+
const rootIdRow = db.prepare(metadataQuery).get();
|
|
443
|
+
if (rootIdRow && tree.getPage(rootIdRow.value)) {
|
|
444
|
+
tree.rootId = rootIdRow.value;
|
|
445
|
+
tree.metadata.defaultHomePageId = rootIdRow.value;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
// Final fallback: first page
|
|
449
|
+
if (!tree.rootId && rootPageId) {
|
|
450
|
+
tree.rootId = rootPageId;
|
|
451
|
+
tree.metadata.defaultHomePageId = rootPageId;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
catch (e) {
|
|
455
|
+
// No metadata table or other error, use first page as root
|
|
456
|
+
if (rootPageId) {
|
|
457
|
+
tree.rootId = rootPageId;
|
|
458
|
+
tree.metadata.defaultHomePageId = rootPageId;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
// Set metadata for TouchChat files
|
|
462
|
+
tree.metadata.format = 'touchchat';
|
|
463
|
+
return tree;
|
|
464
|
+
}
|
|
465
|
+
finally {
|
|
466
|
+
// Clean up
|
|
467
|
+
if (cleanup) {
|
|
468
|
+
cleanup();
|
|
469
|
+
}
|
|
470
|
+
else if (db) {
|
|
471
|
+
db.close();
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
async processTexts(filePathOrBuffer, translations, outputPath) {
|
|
476
|
+
if (!isNodeRuntime()) {
|
|
477
|
+
throw new Error('processTexts is only supported in Node.js environments for TouchChat files.');
|
|
478
|
+
}
|
|
479
|
+
// Load the tree, apply translations, and save to new file
|
|
480
|
+
const tree = await this.loadIntoTree(filePathOrBuffer);
|
|
481
|
+
// Apply translations to all text content
|
|
482
|
+
Object.values(tree.pages).forEach((page) => {
|
|
483
|
+
// Translate page names
|
|
484
|
+
if (page.name && translations.has(page.name)) {
|
|
485
|
+
const translatedName = translations.get(page.name);
|
|
486
|
+
if (translatedName !== undefined) {
|
|
487
|
+
page.name = translatedName;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
// Translate button labels and messages
|
|
491
|
+
page.buttons.forEach((button) => {
|
|
492
|
+
if (button.label && translations.has(button.label)) {
|
|
493
|
+
const translatedLabel = translations.get(button.label);
|
|
494
|
+
if (translatedLabel !== undefined) {
|
|
495
|
+
button.label = translatedLabel;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
if (button.message && translations.has(button.message)) {
|
|
499
|
+
const translatedMessage = translations.get(button.message);
|
|
500
|
+
if (translatedMessage !== undefined) {
|
|
501
|
+
button.message = translatedMessage;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
});
|
|
505
|
+
});
|
|
506
|
+
// Save the translated tree and return its content
|
|
507
|
+
await this.saveFromTree(tree, outputPath);
|
|
508
|
+
const fs = getFs();
|
|
509
|
+
return fs.readFileSync(outputPath);
|
|
510
|
+
}
|
|
511
|
+
async saveFromTree(tree, outputPath) {
|
|
512
|
+
await Promise.resolve();
|
|
513
|
+
if (!isNodeRuntime()) {
|
|
514
|
+
throw new Error('saveFromTree is only supported in Node.js environments for TouchChat files.');
|
|
515
|
+
}
|
|
516
|
+
const fs = getFs();
|
|
517
|
+
const path = getPath();
|
|
518
|
+
const os = getOs();
|
|
519
|
+
// Create a TouchChat database that matches the expected schema for loading
|
|
520
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'touchchat-export-'));
|
|
521
|
+
const dbPath = path.join(tmpDir, 'vocab.c4v');
|
|
522
|
+
try {
|
|
523
|
+
const Database = requireBetterSqlite3();
|
|
524
|
+
const db = new Database(dbPath);
|
|
525
|
+
// Create schema that matches what loadIntoTree expects
|
|
526
|
+
db.exec(`
|
|
527
|
+
CREATE TABLE IF NOT EXISTS resources (
|
|
528
|
+
id INTEGER PRIMARY KEY,
|
|
529
|
+
name TEXT,
|
|
530
|
+
type INTEGER DEFAULT 0
|
|
531
|
+
);
|
|
532
|
+
|
|
533
|
+
CREATE TABLE IF NOT EXISTS pages (
|
|
534
|
+
id INTEGER PRIMARY KEY,
|
|
535
|
+
resource_id INTEGER,
|
|
536
|
+
name TEXT,
|
|
537
|
+
symbol_link_id INTEGER,
|
|
538
|
+
page_style_id INTEGER DEFAULT 1,
|
|
539
|
+
button_style_id INTEGER DEFAULT 1,
|
|
540
|
+
feature INTEGER,
|
|
541
|
+
FOREIGN KEY (resource_id) REFERENCES resources (id)
|
|
542
|
+
);
|
|
543
|
+
|
|
544
|
+
CREATE TABLE IF NOT EXISTS buttons (
|
|
545
|
+
id INTEGER PRIMARY KEY,
|
|
546
|
+
resource_id INTEGER,
|
|
547
|
+
label TEXT,
|
|
548
|
+
message TEXT,
|
|
549
|
+
symbol_link_id INTEGER,
|
|
550
|
+
visible INTEGER DEFAULT 1,
|
|
551
|
+
button_style_id INTEGER DEFAULT 1,
|
|
552
|
+
pronunciation TEXT,
|
|
553
|
+
skin_tone_override INTEGER,
|
|
554
|
+
FOREIGN KEY (resource_id) REFERENCES resources (id)
|
|
555
|
+
);
|
|
556
|
+
|
|
557
|
+
CREATE TABLE IF NOT EXISTS button_boxes (
|
|
558
|
+
id INTEGER PRIMARY KEY,
|
|
559
|
+
resource_id INTEGER,
|
|
560
|
+
layout_x INTEGER DEFAULT 10,
|
|
561
|
+
layout_y INTEGER DEFAULT 6,
|
|
562
|
+
init_size_x INTEGER DEFAULT 10000,
|
|
563
|
+
init_size_y INTEGER DEFAULT 10000,
|
|
564
|
+
scan_pattern_id INTEGER DEFAULT 0,
|
|
565
|
+
FOREIGN KEY (resource_id) REFERENCES resources (id)
|
|
566
|
+
);
|
|
567
|
+
|
|
568
|
+
CREATE TABLE IF NOT EXISTS button_box_cells (
|
|
569
|
+
id INTEGER PRIMARY KEY,
|
|
570
|
+
button_box_id INTEGER,
|
|
571
|
+
resource_id INTEGER,
|
|
572
|
+
location INTEGER,
|
|
573
|
+
span_x INTEGER DEFAULT 1,
|
|
574
|
+
span_y INTEGER DEFAULT 1,
|
|
575
|
+
button_style_id INTEGER DEFAULT 1,
|
|
576
|
+
label TEXT,
|
|
577
|
+
message TEXT,
|
|
578
|
+
box_id INTEGER,
|
|
579
|
+
FOREIGN KEY (button_box_id) REFERENCES button_boxes (id),
|
|
580
|
+
FOREIGN KEY (resource_id) REFERENCES resources (id),
|
|
581
|
+
FOREIGN KEY (button_style_id) REFERENCES button_styles (id)
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
CREATE TABLE IF NOT EXISTS button_box_instances (
|
|
585
|
+
id INTEGER PRIMARY KEY,
|
|
586
|
+
page_id INTEGER,
|
|
587
|
+
button_box_id INTEGER,
|
|
588
|
+
position_x INTEGER DEFAULT 0,
|
|
589
|
+
position_y INTEGER DEFAULT 0,
|
|
590
|
+
size_x INTEGER DEFAULT 1,
|
|
591
|
+
size_y INTEGER DEFAULT 1,
|
|
592
|
+
FOREIGN KEY (page_id) REFERENCES pages (id),
|
|
593
|
+
FOREIGN KEY (button_box_id) REFERENCES button_boxes (id)
|
|
594
|
+
);
|
|
595
|
+
|
|
596
|
+
CREATE TABLE IF NOT EXISTS actions (
|
|
597
|
+
id INTEGER PRIMARY KEY,
|
|
598
|
+
resource_id INTEGER,
|
|
599
|
+
code INTEGER,
|
|
600
|
+
FOREIGN KEY (resource_id) REFERENCES resources (id)
|
|
601
|
+
);
|
|
602
|
+
|
|
603
|
+
CREATE TABLE IF NOT EXISTS action_data (
|
|
604
|
+
id INTEGER PRIMARY KEY,
|
|
605
|
+
action_id INTEGER,
|
|
606
|
+
value TEXT,
|
|
607
|
+
FOREIGN KEY (action_id) REFERENCES actions (id)
|
|
608
|
+
);
|
|
609
|
+
|
|
610
|
+
CREATE TABLE IF NOT EXISTS tree_metadata (
|
|
611
|
+
key TEXT PRIMARY KEY,
|
|
612
|
+
value TEXT
|
|
613
|
+
);
|
|
614
|
+
|
|
615
|
+
CREATE TABLE IF NOT EXISTS page_id_mapping (
|
|
616
|
+
numeric_id INTEGER PRIMARY KEY,
|
|
617
|
+
string_id TEXT UNIQUE
|
|
618
|
+
);
|
|
619
|
+
|
|
620
|
+
CREATE TABLE IF NOT EXISTS button_styles (
|
|
621
|
+
id INTEGER PRIMARY KEY,
|
|
622
|
+
label_on_top INTEGER DEFAULT 0,
|
|
623
|
+
force_label_on_top INTEGER DEFAULT 0,
|
|
624
|
+
transparent INTEGER DEFAULT 0,
|
|
625
|
+
force_transparent INTEGER DEFAULT 0,
|
|
626
|
+
font_color INTEGER,
|
|
627
|
+
force_font_color INTEGER DEFAULT 0,
|
|
628
|
+
body_color INTEGER,
|
|
629
|
+
force_body_color INTEGER DEFAULT 0,
|
|
630
|
+
border_color INTEGER,
|
|
631
|
+
force_border_color INTEGER DEFAULT 0,
|
|
632
|
+
border_width REAL,
|
|
633
|
+
force_border_width INTEGER DEFAULT 0,
|
|
634
|
+
font_name TEXT,
|
|
635
|
+
font_bold INTEGER DEFAULT 0,
|
|
636
|
+
font_underline INTEGER DEFAULT 0,
|
|
637
|
+
font_italic INTEGER DEFAULT 0,
|
|
638
|
+
font_height REAL,
|
|
639
|
+
force_font INTEGER DEFAULT 0
|
|
640
|
+
);
|
|
641
|
+
|
|
642
|
+
CREATE TABLE IF NOT EXISTS page_styles (
|
|
643
|
+
id INTEGER PRIMARY KEY,
|
|
644
|
+
bg_color INTEGER,
|
|
645
|
+
force_bg_color INTEGER DEFAULT 0,
|
|
646
|
+
bg_alignment INTEGER DEFAULT 0,
|
|
647
|
+
force_bg_alignment INTEGER DEFAULT 0
|
|
648
|
+
);
|
|
649
|
+
`);
|
|
650
|
+
// Insert default styles
|
|
651
|
+
db.prepare('INSERT INTO button_styles (id) VALUES (1)').run();
|
|
652
|
+
db.prepare('INSERT INTO page_styles (id) VALUES (1)').run();
|
|
653
|
+
// Helper function to convert hex color to integer
|
|
654
|
+
const hexToInt = (hexColor) => {
|
|
655
|
+
if (!hexColor)
|
|
656
|
+
return null;
|
|
657
|
+
const hex = hexColor.replace('#', '');
|
|
658
|
+
return parseInt(hex, 16);
|
|
659
|
+
};
|
|
660
|
+
// Insert pages and buttons using the proper schema
|
|
661
|
+
let resourceIdCounter = 1;
|
|
662
|
+
let pageIdCounter = 1;
|
|
663
|
+
let buttonIdCounter = 1;
|
|
664
|
+
let buttonBoxIdCounter = 1;
|
|
665
|
+
let buttonBoxInstanceIdCounter = 1;
|
|
666
|
+
let actionIdCounter = 1;
|
|
667
|
+
let buttonStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
|
|
668
|
+
let pageStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
|
|
669
|
+
// Create mapping from string IDs to numeric IDs
|
|
670
|
+
const pageIdMap = new Map();
|
|
671
|
+
const insertedButtonIds = new Set();
|
|
672
|
+
const buttonStyleMap = new Map();
|
|
673
|
+
const pageStyleMap = new Map();
|
|
674
|
+
// First pass: create pages and map IDs
|
|
675
|
+
Object.values(tree.pages).forEach((page) => {
|
|
676
|
+
// Try to use numeric ID if possible, otherwise assign sequential ID
|
|
677
|
+
const numericPageId = /^\d+$/.test(page.id) ? parseInt(page.id) : pageIdCounter++;
|
|
678
|
+
pageIdMap.set(page.id, numericPageId);
|
|
679
|
+
// Create page style if needed
|
|
680
|
+
let pageStyleId = 1; // default style
|
|
681
|
+
if (page.style && page.style.backgroundColor) {
|
|
682
|
+
const styleKey = JSON.stringify(page.style);
|
|
683
|
+
if (!pageStyleMap.has(styleKey)) {
|
|
684
|
+
pageStyleId = pageStyleIdCounter++;
|
|
685
|
+
pageStyleMap.set(styleKey, pageStyleId);
|
|
686
|
+
const insertPageStyle = db.prepare('INSERT INTO page_styles (id, bg_color, force_bg_color) VALUES (?, ?, ?)');
|
|
687
|
+
insertPageStyle.run(pageStyleId, hexToInt(page.style.backgroundColor), page.style.backgroundColor ? 1 : 0);
|
|
688
|
+
}
|
|
689
|
+
else {
|
|
690
|
+
const existingPageStyleId = pageStyleMap.get(styleKey);
|
|
691
|
+
if (typeof existingPageStyleId === 'number') {
|
|
692
|
+
pageStyleId = existingPageStyleId;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// Insert resource for page name
|
|
697
|
+
const pageResourceId = resourceIdCounter++;
|
|
698
|
+
const insertResource = db.prepare('INSERT INTO resources (id, name, type) VALUES (?, ?, ?)');
|
|
699
|
+
insertResource.run(pageResourceId, page.name || 'Page', 0);
|
|
700
|
+
// Insert page with original ID preserved and style
|
|
701
|
+
const insertPage = db.prepare('INSERT INTO pages (id, resource_id, name, page_style_id) VALUES (?, ?, ?, ?)');
|
|
702
|
+
insertPage.run(numericPageId, pageResourceId, page.name || 'Page', pageStyleId);
|
|
703
|
+
// Store ID mapping
|
|
704
|
+
const insertIdMapping = db.prepare('INSERT INTO page_id_mapping (numeric_id, string_id) VALUES (?, ?)');
|
|
705
|
+
insertIdMapping.run(numericPageId, page.id);
|
|
706
|
+
});
|
|
707
|
+
// Second pass: create buttons and their relationships
|
|
708
|
+
Object.values(tree.pages).forEach((page) => {
|
|
709
|
+
const numericPageId = pageIdMap.get(page.id);
|
|
710
|
+
if (numericPageId === undefined) {
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (page.buttons.length > 0) {
|
|
714
|
+
// Calculate grid dimensions from page.grid or use fallback
|
|
715
|
+
let gridWidth = 4; // Default fallback
|
|
716
|
+
let gridHeight = Math.ceil(page.buttons.length / gridWidth);
|
|
717
|
+
if (page.grid && page.grid.length > 0) {
|
|
718
|
+
gridHeight = page.grid.length;
|
|
719
|
+
gridWidth = page.grid[0] ? page.grid[0].length : gridWidth;
|
|
720
|
+
}
|
|
721
|
+
// Create a button box for this page's buttons
|
|
722
|
+
const buttonBoxId = buttonBoxIdCounter++;
|
|
723
|
+
// Create a resource for the button box
|
|
724
|
+
const buttonBoxResourceId = resourceIdCounter++;
|
|
725
|
+
const insertButtonBoxResource = db.prepare('INSERT INTO resources (id, name, type) VALUES (?, ?, ?)');
|
|
726
|
+
insertButtonBoxResource.run(buttonBoxResourceId, page.name || 'ButtonBox', 0);
|
|
727
|
+
// Insert button box with layout dimensions
|
|
728
|
+
const insertButtonBox = db.prepare('INSERT INTO button_boxes (id, resource_id, layout_x, layout_y, init_size_x, init_size_y) VALUES (?, ?, ?, ?, ?, ?)');
|
|
729
|
+
insertButtonBox.run(buttonBoxId, buttonBoxResourceId, gridWidth, gridHeight, 10000, // init_size_x in internal units
|
|
730
|
+
10000 // init_size_y in internal units
|
|
731
|
+
);
|
|
732
|
+
// Create button box instance with calculated dimensions
|
|
733
|
+
const insertButtonBoxInstance = db.prepare('INSERT INTO button_box_instances (id, page_id, button_box_id, position_x, position_y, size_x, size_y) VALUES (?, ?, ?, ?, ?, ?, ?)');
|
|
734
|
+
insertButtonBoxInstance.run(buttonBoxInstanceIdCounter++, numericPageId, buttonBoxId, 0, // Box starts at origin
|
|
735
|
+
0, gridWidth, gridHeight);
|
|
736
|
+
// Insert buttons
|
|
737
|
+
page.buttons.forEach((button, index) => {
|
|
738
|
+
// Find button position in grid layout
|
|
739
|
+
let buttonLocation = index; // Default fallback
|
|
740
|
+
let buttonSpanX = 1;
|
|
741
|
+
let buttonSpanY = 1;
|
|
742
|
+
if (page.grid && page.grid.length > 0) {
|
|
743
|
+
// Search for button in grid layout
|
|
744
|
+
for (let y = 0; y < page.grid.length; y++) {
|
|
745
|
+
for (let x = 0; x < page.grid[y].length; x++) {
|
|
746
|
+
const gridButton = page.grid[y][x];
|
|
747
|
+
if (gridButton && gridButton.id === button.id) {
|
|
748
|
+
// Convert grid coordinates to linear location
|
|
749
|
+
buttonLocation = y * gridWidth + x;
|
|
750
|
+
// Calculate span (find how many consecutive cells this button occupies)
|
|
751
|
+
// For now, assume 1x1 span (can be enhanced later for multi-cell buttons)
|
|
752
|
+
buttonSpanX = 1;
|
|
753
|
+
buttonSpanY = 1;
|
|
754
|
+
break;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
const buttonResourceId = resourceIdCounter++;
|
|
760
|
+
const insertResource = db.prepare('INSERT INTO resources (id, name, type) VALUES (?, ?, ?)');
|
|
761
|
+
insertResource.run(buttonResourceId, button.label || 'Button', 7);
|
|
762
|
+
const numericButtonId = parseInt(button.id) || buttonIdCounter++;
|
|
763
|
+
// Create button style if needed
|
|
764
|
+
let buttonStyleId = 1; // default style
|
|
765
|
+
if (button.style) {
|
|
766
|
+
const styleKey = JSON.stringify(button.style);
|
|
767
|
+
if (!buttonStyleMap.has(styleKey)) {
|
|
768
|
+
buttonStyleId = buttonStyleIdCounter++;
|
|
769
|
+
buttonStyleMap.set(styleKey, buttonStyleId);
|
|
770
|
+
const insertButtonStyle = db.prepare('INSERT INTO button_styles (id, label_on_top, transparent, font_color, body_color, border_color, border_width, font_name, font_bold, font_underline, font_italic, font_height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
771
|
+
insertButtonStyle.run(buttonStyleId, button.style.labelOnTop ? 1 : 0, button.style.transparent ? 1 : 0, hexToInt(button.style.fontColor), hexToInt(button.style.backgroundColor), hexToInt(button.style.borderColor), button.style.borderWidth, button.style.fontFamily, button.style.fontWeight === 'bold' ? 1 : 0, button.style.textUnderline ? 1 : 0, button.style.fontStyle === 'italic' ? 1 : 0, button.style.fontSize);
|
|
772
|
+
}
|
|
773
|
+
else {
|
|
774
|
+
const existingButtonStyleId = buttonStyleMap.get(styleKey);
|
|
775
|
+
if (typeof existingButtonStyleId === 'number') {
|
|
776
|
+
buttonStyleId = existingButtonStyleId;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (!insertedButtonIds.has(numericButtonId)) {
|
|
781
|
+
const insertButton = db.prepare('INSERT INTO buttons (id, resource_id, label, message, visible, button_style_id) VALUES (?, ?, ?, ?, ?, ?)');
|
|
782
|
+
insertButton.run(numericButtonId, buttonResourceId, button.label || '', button.message || button.label || '', 1, buttonStyleId);
|
|
783
|
+
insertedButtonIds.add(numericButtonId);
|
|
784
|
+
}
|
|
785
|
+
// Insert button box cell with styling
|
|
786
|
+
const insertButtonBoxCell = db.prepare('INSERT INTO button_box_cells (button_box_id, resource_id, location, span_x, span_y, button_style_id, label, message, box_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
|
|
787
|
+
insertButtonBoxCell.run(buttonBoxId, buttonResourceId, buttonLocation, buttonSpanX, buttonSpanY, buttonStyleId, button.label || '', button.message || button.label || '', buttonLocation);
|
|
788
|
+
// Handle actions - prefer semantic actions
|
|
789
|
+
if (button.semanticAction?.intent === AACSemanticIntent.NAVIGATE_TO) {
|
|
790
|
+
const targetId = button.semanticAction.targetId || button.targetPageId;
|
|
791
|
+
const targetPageId = targetId ? pageIdMap.get(targetId) : null;
|
|
792
|
+
if (targetPageId) {
|
|
793
|
+
// Insert navigation action
|
|
794
|
+
const insertAction = db.prepare('INSERT INTO actions (id, resource_id, code) VALUES (?, ?, ?)');
|
|
795
|
+
const actionCode = button.semanticAction.platformData?.touchChat?.actionCode || 1;
|
|
796
|
+
insertAction.run(actionIdCounter, buttonResourceId, actionCode);
|
|
797
|
+
// Insert action data
|
|
798
|
+
const insertActionData = db.prepare('INSERT INTO action_data (action_id, value) VALUES (?, ?)');
|
|
799
|
+
const actionData = button.semanticAction.platformData?.touchChat?.actionData || String(targetPageId);
|
|
800
|
+
insertActionData.run(actionIdCounter, actionData);
|
|
801
|
+
actionIdCounter++;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
// Save tree metadata (root ID)
|
|
808
|
+
if (tree.rootId) {
|
|
809
|
+
const insertMetadata = db.prepare('INSERT INTO tree_metadata (key, value) VALUES (?, ?)');
|
|
810
|
+
insertMetadata.run('rootId', tree.rootId);
|
|
811
|
+
}
|
|
812
|
+
db.close();
|
|
813
|
+
// Create zip file with the database
|
|
814
|
+
const AdmZip = getNodeRequire()('adm-zip');
|
|
815
|
+
const zip = new AdmZip();
|
|
816
|
+
zip.addLocalFile(dbPath, '', 'vocab.c4v');
|
|
817
|
+
zip.writeZip(outputPath);
|
|
818
|
+
}
|
|
819
|
+
finally {
|
|
820
|
+
// Clean up
|
|
821
|
+
if (fs.existsSync(tmpDir)) {
|
|
822
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Alias method for aac-tools-platform compatibility
|
|
828
|
+
* Extracts strings with TouchChat-specific metadata required for database storage
|
|
829
|
+
* @param filePath - Path to the TouchChat .ce file
|
|
830
|
+
* @returns Promise with extracted strings and any errors
|
|
831
|
+
*/
|
|
832
|
+
async extractStringsWithMetadata(filePath) {
|
|
833
|
+
try {
|
|
834
|
+
const tree = await this.loadIntoTree(filePath);
|
|
835
|
+
const extractedMap = new Map();
|
|
836
|
+
// Process all pages and buttons with TouchChat-specific logic
|
|
837
|
+
Object.values(tree.pages).forEach((page) => {
|
|
838
|
+
page.buttons.forEach((button) => {
|
|
839
|
+
// Process button labels
|
|
840
|
+
if (button.label && button.label.trim().length > 1 && !isNumericOrEmpty(button.label)) {
|
|
841
|
+
const key = button.label.trim().toLowerCase();
|
|
842
|
+
const vocabLocation = {
|
|
843
|
+
table: 'buttons',
|
|
844
|
+
id: parseInt(button.id) || 0,
|
|
845
|
+
column: 'LABEL',
|
|
846
|
+
casing: detectCasing(button.label),
|
|
847
|
+
};
|
|
848
|
+
this.addToExtractedMap(extractedMap, key, button.label.trim(), vocabLocation);
|
|
849
|
+
}
|
|
850
|
+
// Process button messages (if different from label)
|
|
851
|
+
if (button.message &&
|
|
852
|
+
button.message !== button.label &&
|
|
853
|
+
button.message.trim().length > 1 &&
|
|
854
|
+
!isNumericOrEmpty(button.message)) {
|
|
855
|
+
const key = button.message.trim().toLowerCase();
|
|
856
|
+
const vocabLocation = {
|
|
857
|
+
table: 'buttons',
|
|
858
|
+
id: parseInt(button.id) || 0,
|
|
859
|
+
column: 'MESSAGE',
|
|
860
|
+
casing: detectCasing(button.message),
|
|
861
|
+
};
|
|
862
|
+
this.addToExtractedMap(extractedMap, key, button.message.trim(), vocabLocation);
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
});
|
|
866
|
+
const extractedStrings = Array.from(extractedMap.values());
|
|
867
|
+
return Promise.resolve({ errors: [], extractedStrings });
|
|
868
|
+
}
|
|
869
|
+
catch (error) {
|
|
870
|
+
return Promise.resolve({
|
|
871
|
+
errors: [
|
|
872
|
+
{
|
|
873
|
+
message: error instanceof Error ? error.message : 'Unknown extraction error',
|
|
874
|
+
step: 'EXTRACT',
|
|
875
|
+
},
|
|
876
|
+
],
|
|
877
|
+
extractedStrings: [],
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Alias method for generating translated TouchChat downloads compatible with aac-tools-platform
|
|
883
|
+
* @param filePath - Path to the original TouchChat .ce file
|
|
884
|
+
* @param translatedStrings - Array of translated string data
|
|
885
|
+
* @param sourceStrings - Array of source string data with metadata
|
|
886
|
+
* @returns Promise with path to the generated translated file
|
|
887
|
+
*/
|
|
888
|
+
async generateTranslatedDownload(filePath, translatedStrings, sourceStrings) {
|
|
889
|
+
try {
|
|
890
|
+
// Build translation map from the provided data
|
|
891
|
+
const translations = new Map();
|
|
892
|
+
sourceStrings.forEach((sourceString) => {
|
|
893
|
+
const translated = translatedStrings.find((ts) => ts.sourcestringid.toString() === sourceString.id.toString());
|
|
894
|
+
if (translated) {
|
|
895
|
+
const translatedText = translated.overridestring.length > 0
|
|
896
|
+
? translated.overridestring
|
|
897
|
+
: translated.translatedstring;
|
|
898
|
+
translations.set(sourceString.sourcestring, translatedText);
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
// Generate output path for TouchChat files
|
|
902
|
+
const outputPath = filePath.replace(/\.ce$/, '_translated.ce');
|
|
903
|
+
// Use existing processTexts method
|
|
904
|
+
await this.processTexts(filePath, translations, outputPath);
|
|
905
|
+
return Promise.resolve(outputPath);
|
|
906
|
+
}
|
|
907
|
+
catch (error) {
|
|
908
|
+
return Promise.reject(new Error(`Failed to generate translated download: ${error instanceof Error ? error.message : 'Unknown error'}`));
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Validate TouchChat file format
|
|
913
|
+
* @param filePath - Path to the file to validate
|
|
914
|
+
* @returns Promise with validation result
|
|
915
|
+
*/
|
|
916
|
+
async validate(filePath) {
|
|
917
|
+
return TouchChatValidator.validateFile(filePath);
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Extract symbol information from a TouchChat file for LLM-based translation.
|
|
921
|
+
* Returns a structured format showing which buttons have symbols and their context.
|
|
922
|
+
*
|
|
923
|
+
* This method uses shared translation utilities that work across all AAC formats.
|
|
924
|
+
*
|
|
925
|
+
* @param filePathOrBuffer - Path to TouchChat .ce file or buffer
|
|
926
|
+
* @returns Array of symbol information for LLM processing
|
|
927
|
+
*/
|
|
928
|
+
async extractSymbolsForLLM(filePathOrBuffer) {
|
|
929
|
+
const tree = await this.loadIntoTree(filePathOrBuffer);
|
|
930
|
+
// Collect all buttons from all pages
|
|
931
|
+
const allButtons = [];
|
|
932
|
+
Object.values(tree.pages).forEach((page) => {
|
|
933
|
+
page.buttons.forEach((button) => {
|
|
934
|
+
// Add page context to each button
|
|
935
|
+
button.pageId = page.id;
|
|
936
|
+
button.pageName = page.name || page.id;
|
|
937
|
+
allButtons.push(button);
|
|
938
|
+
});
|
|
939
|
+
});
|
|
940
|
+
// Use shared utility to extract buttons with translation context
|
|
941
|
+
return extractAllButtonsForTranslation(allButtons, (button) => ({
|
|
942
|
+
pageId: button.pageId,
|
|
943
|
+
pageName: button.pageName,
|
|
944
|
+
}));
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Apply LLM translations with symbol information.
|
|
948
|
+
* The LLM should provide translations with symbol attachments in the correct positions.
|
|
949
|
+
*
|
|
950
|
+
* This method uses shared translation utilities that work across all AAC formats.
|
|
951
|
+
*
|
|
952
|
+
* @param filePathOrBuffer - Path to TouchChat .ce file or buffer
|
|
953
|
+
* @param llmTranslations - Array of LLM translations with symbol info
|
|
954
|
+
* @param outputPath - Where to save the translated TouchChat file
|
|
955
|
+
* @param options - Translation options (e.g., allowPartial for testing)
|
|
956
|
+
* @returns Buffer of the translated TouchChat file
|
|
957
|
+
*/
|
|
958
|
+
async processLLMTranslations(filePathOrBuffer, llmTranslations, outputPath, options) {
|
|
959
|
+
if (!isNodeRuntime()) {
|
|
960
|
+
throw new Error('processLLMTranslations is only supported in Node.js environments for TouchChat files.');
|
|
961
|
+
}
|
|
962
|
+
const tree = await this.loadIntoTree(filePathOrBuffer);
|
|
963
|
+
// Validate translations using shared utility
|
|
964
|
+
const buttonIds = Object.values(tree.pages).flatMap((page) => page.buttons.map((b) => b.id));
|
|
965
|
+
validateTranslationResults(llmTranslations, buttonIds, options);
|
|
966
|
+
// Create a map for quick lookup
|
|
967
|
+
const translationMap = new Map(llmTranslations.map((t) => [t.buttonId, t]));
|
|
968
|
+
// Apply translations
|
|
969
|
+
Object.values(tree.pages).forEach((page) => {
|
|
970
|
+
page.buttons.forEach((button) => {
|
|
971
|
+
const translation = translationMap.get(button.id);
|
|
972
|
+
if (!translation)
|
|
973
|
+
return;
|
|
974
|
+
// Apply label translation
|
|
975
|
+
if (translation.translatedLabel) {
|
|
976
|
+
button.label = translation.translatedLabel;
|
|
977
|
+
}
|
|
978
|
+
// Apply message translation
|
|
979
|
+
if (translation.translatedMessage) {
|
|
980
|
+
button.message = translation.translatedMessage;
|
|
981
|
+
// Update semantic action if symbols provided
|
|
982
|
+
if (translation.symbols && translation.symbols.length > 0) {
|
|
983
|
+
if (!button.semanticAction) {
|
|
984
|
+
button.semanticAction = {
|
|
985
|
+
category: AACSemanticCategory.COMMUNICATION,
|
|
986
|
+
intent: AACSemanticIntent.SPEAK_TEXT,
|
|
987
|
+
text: translation.translatedMessage,
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
button.semanticAction.richText = {
|
|
991
|
+
text: translation.translatedMessage,
|
|
992
|
+
symbols: translation.symbols,
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
});
|
|
997
|
+
});
|
|
998
|
+
// Save and return
|
|
999
|
+
await this.saveFromTree(tree, outputPath);
|
|
1000
|
+
const fs = getFs();
|
|
1001
|
+
return fs.readFileSync(outputPath);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
export { TouchChatProcessor };
|