forked from AACTools/AACProcessors-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtouchchatProcessor.ts
More file actions
1443 lines (1303 loc) · 51.5 KB
/
Copy pathtouchchatProcessor.ts
File metadata and controls
1443 lines (1303 loc) · 51.5 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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
BaseProcessor,
ProcessorOptions,
ExtractStringsResult,
TranslatedString,
SourceString,
VocabLocation,
ExtractedString,
} from '../core/baseProcessor';
import {
AACTree,
AACPage,
AACButton,
AACSemanticAction,
AACSemanticCategory,
AACSemanticIntent,
} from '../core/treeStructure';
import { generateCloneId } from '../utilities/analytics/utils/idGenerator';
import { detectCasing, isNumericOrEmpty } from '../core/stringCasing';
import { TouchChatValidator } from '../validation/touchChatValidator';
import { ValidationResult } from '../validation/validationTypes';
import {
ProcessorInput,
getFs,
getNodeRequire,
getOs,
getPath,
isNodeRuntime,
readBinaryFromInput,
} from '../utils/io';
import {
extractAllButtonsForTranslation,
validateTranslationResults,
type ButtonForTranslation,
type LLMLTranslationResult,
} from '../utilities/translation/translationProcessor';
import {
openSqliteDatabase,
requireBetterSqlite3,
type SqliteDatabaseAdapter,
} from '../utils/sqlite';
import { openZipFromInput } from '../utils/zip';
interface TouchChatButton {
id: number;
resource_id: number;
label: string | null;
message: string | null;
symbol_link_id: number | null;
visible: number;
button_style_id: number;
pronunciation: string | null;
skin_tone_override: number | null;
}
interface TouchChatPage {
id: number;
resource_id: number;
name: string;
symbol_link_id: number | null;
page_style_id: number;
button_style_id: number;
feature: number | null;
}
const toNumberOrUndefined = (value: number | null | undefined): number | undefined =>
typeof value === 'number' ? value : undefined;
const toStringOrUndefined = (value: string | null | undefined): string | undefined =>
typeof value === 'string' && value.length > 0 ? value : undefined;
const toBooleanOrUndefined = (value: number | null | undefined): boolean | undefined =>
typeof value === 'number' ? value !== 0 : undefined;
interface TouchChatButtonStyle {
id: number;
body_color?: number | null;
border_color?: number | null;
border_width?: number | null;
font_color?: number | null;
font_height?: number | null;
font_name?: string | null;
font_bold?: number | null;
font_italic?: number | null;
font_underline?: number | null;
transparent?: number | null;
label_on_top?: number | null;
}
interface TouchChatPageStyle {
id: number;
bg_color?: number | null;
}
function intToHex(colorInt: number | null | undefined): string | undefined {
if (colorInt === null || typeof colorInt === 'undefined') {
return undefined;
}
// Assuming the color is in ARGB format, we mask out the alpha channel
return `#${(colorInt & 0x00ffffff).toString(16).padStart(6, '0')}`;
}
/**
* Map TouchChat visible value to AAC standard visibility
* TouchChat: 0 = Hidden, 1 = Visible
* Maps to: 'Hidden' | 'Visible' | undefined
*/
function mapTouchChatVisibility(
visible: number | null | undefined
): 'Visible' | 'Hidden' | undefined {
if (visible === null || visible === undefined) {
return undefined; // Default to visible
}
return visible === 0 ? 'Hidden' : 'Visible';
}
class TouchChatProcessor extends BaseProcessor {
private tree: AACTree | null = null;
private sourceFile: ProcessorInput | null = null;
constructor(options?: ProcessorOptions) {
super(options);
}
async extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]> {
// Extracts all button labels/texts from TouchChat .ce file
if (!this.tree && filePathOrBuffer) {
this.tree = await this.loadIntoTree(filePathOrBuffer);
}
if (!this.tree) {
throw new Error('No tree available - call loadIntoTree first');
}
const texts: string[] = [];
for (const pageId in this.tree.pages) {
const page = this.tree.pages[pageId];
page.buttons.forEach((btn) => {
if (btn.label) texts.push(btn.label);
if (btn.message && btn.message !== btn.label) texts.push(btn.message);
});
}
return texts;
}
async loadIntoTree(filePathOrBuffer: ProcessorInput): Promise<AACTree> {
await Promise.resolve();
// Unzip .ce file, extract the .c4v SQLite DB, and parse pages/buttons
let db: SqliteDatabaseAdapter | null = null;
let cleanup: (() => void) | undefined;
try {
// Store source file path or buffer
this.sourceFile = filePathOrBuffer;
// Step 1: Unzip
const zipInput = readBinaryFromInput(filePathOrBuffer);
const { zip } = this.options.zipAdapter
? await this.options.zipAdapter(zipInput)
: await openZipFromInput(zipInput);
const vocabEntry = zip.listFiles().find((name) => name.endsWith('.c4v'));
if (!vocabEntry) {
throw new Error('No .c4v vocab DB found in TouchChat export');
}
const dbBuffer = await zip.readFile(vocabEntry);
const dbResult = await openSqliteDatabase(dbBuffer, { readonly: true });
db = dbResult.db;
cleanup = dbResult.cleanup;
// Step 3: Create tree and load pages
const tree = new AACTree();
// Set root ID to the first page ID (will be updated if we find a better root)
let rootPageId: string | null = null;
const getTableColumns = (tableName: string): Set<string> => {
if (!db) return new Set();
try {
const rows = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{
name: string;
}>;
return new Set(rows.map((row) => row.name));
} catch {
return new Set();
}
};
// Load ID mappings first
const idMappings = new Map<number, string>();
const numericToRid = new Map<number, string>();
try {
const mappingQuery = 'SELECT numeric_id, string_id FROM page_id_mapping';
const mappings = db.prepare(mappingQuery).all() as {
numeric_id: number;
string_id: string;
}[];
mappings.forEach((mapping) => {
idMappings.set(mapping.numeric_id, mapping.string_id);
});
} catch (e) {
// No mapping table, use numeric IDs as strings
}
// Load styles
const buttonStyles = new Map<number, TouchChatButtonStyle>();
const pageStyles = new Map<number, TouchChatPageStyle>();
try {
const buttonStyleRows = db
.prepare('SELECT * FROM button_styles')
.all() as TouchChatButtonStyle[];
buttonStyleRows.forEach((style) => {
buttonStyles.set(style.id, style);
});
const pageStyleRows = db.prepare('SELECT * FROM page_styles').all() as TouchChatPageStyle[];
pageStyleRows.forEach((style) => {
pageStyles.set(style.id, style);
});
} catch (e) {
// console.log('No styles found:', e);
}
// First, load all pages and get their names from resources
const resourceColumns = getTableColumns('resources');
const hasRid = resourceColumns.has('rid');
const pageQuery = `
SELECT p.*, r.name${hasRid ? ', r.rid' : ''}
FROM pages p
JOIN resources r ON r.id = p.resource_id
`;
const pages = db.prepare(pageQuery).all() as (TouchChatPage & {
name: string;
rid?: string;
})[];
pages.forEach((pageRow) => {
// Use resource RID (UUID) if available, otherwise mapped string ID, then numeric ID
const pageId =
(hasRid ? pageRow.rid : null) || idMappings.get(pageRow.id) || String(pageRow.id);
numericToRid.set(pageRow.id, pageId);
const style = pageStyles.get(pageRow.page_style_id);
const page = new AACPage({
id: pageId,
name: pageRow.name || '',
grid: [],
buttons: [],
parentId: null,
style: {
backgroundColor: intToHex(style?.bg_color),
},
});
tree.addPage(page);
// Set the first page as root if no root is set
if (!rootPageId) {
rootPageId = pageId;
}
});
// Load button boxes and their cells
const buttonBoxQuery = `
SELECT bbc.*, b.*, bb.id as box_id, bb.layout_x, bb.layout_y
FROM button_box_cells bbc
JOIN buttons b ON b.resource_id = bbc.resource_id
JOIN button_boxes bb ON bb.id = bbc.button_box_id
`;
try {
const buttonBoxCells = db.prepare(buttonBoxQuery).all() as (TouchChatButton & {
box_id: number;
layout_x: number;
layout_y: number;
})[];
const buttonBoxes = new Map<
number,
{
layoutX: number;
layoutY: number;
buttons: Array<{
button: AACButton;
location: number;
spanX: number;
spanY: number;
}>;
}
>();
buttonBoxCells.forEach((cell) => {
let boxData = buttonBoxes.get(cell.box_id);
if (!boxData) {
boxData = {
layoutX: cell.layout_x || 10,
layoutY: cell.layout_y || 6,
buttons: [],
};
buttonBoxes.set(cell.box_id, boxData);
}
const style = buttonStyles.get(cell.button_style_id);
// Create semantic action for TouchChat button
const semanticAction: AACSemanticAction = {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.SPEAK_TEXT,
text: cell.message || cell.label || '',
platformData: {
touchChat: {
actionCode: 0, // Default speak action
actionData: cell.message || cell.label || '',
resourceId: cell.resource_id,
},
},
fallback: {
type: 'SPEAK',
message: cell.message || cell.label || '',
},
};
const button = new AACButton({
id: String(cell.id),
label: cell.label || '',
message: cell.message || '',
semanticAction: semanticAction,
semantic_id:
(((cell as any).symbol_link_id || (cell as any).symbolLinkId) as
| string
| undefined) || undefined, // Extract semantic_id from symbol_link_id
visibility: mapTouchChatVisibility(
((cell as any).visible as number | null | undefined) || undefined
),
// Note: TouchChat does not use scan blocks in the file
// Scanning is a runtime feature (linear/row-column patterns)
// scanBlock defaults to 1 (no grouping)
style: {
backgroundColor: intToHex(style?.body_color),
borderColor: intToHex(style?.border_color),
borderWidth: toNumberOrUndefined(style?.border_width),
fontColor: intToHex(style?.font_color),
fontSize: toNumberOrUndefined(style?.font_height),
fontFamily: toStringOrUndefined(style?.font_name),
fontWeight: style?.font_bold ? 'bold' : undefined,
fontStyle: style?.font_italic ? 'italic' : undefined,
textUnderline: toBooleanOrUndefined(style?.font_underline),
transparent: toBooleanOrUndefined(style?.transparent),
labelOnTop: toBooleanOrUndefined(style?.label_on_top),
},
});
boxData.buttons.push({
button,
location: ((cell as any).location as number) || 0,
spanX: ((cell as any).span_x as number) || 1,
spanY: ((cell as any).span_y as number) || 1,
});
});
// Map button boxes to pages
const boxInstances = db.prepare('SELECT * FROM button_box_instances').all() as {
id: number;
page_id: number;
button_box_id: number;
position_x: number;
position_y: number;
size_x: number;
size_y: number;
}[];
// Create a map to track page grid layouts
const pageGrids = new Map<string, Array<Array<AACButton | null>>>();
boxInstances.forEach((instance) => {
// Use mapped string ID if available, otherwise use numeric ID as string
const pageId = numericToRid.get(instance.page_id) || String(instance.page_id);
const page = tree.getPage(pageId);
const boxData = buttonBoxes.get(instance.button_box_id);
if (page && boxData) {
// Initialize page grid if not exists (assume max 10x10 grid)
if (!pageGrids.has(pageId)) {
const grid: Array<Array<AACButton | null>> = [];
for (let r = 0; r < 10; r++) {
grid[r] = new Array(10).fill(null);
}
pageGrids.set(pageId, grid);
}
const pageGrid = pageGrids.get(pageId);
if (!pageGrid) return;
const boxX = Number(instance.position_x) || 0;
const boxY = Number(instance.position_y) || 0;
const boxWidth = boxData.layoutX; // Use layout_x from button_boxes, not size_x from instance
// boxHeight not currently used but kept for future span calculations
// const boxHeight = boxData.layoutY;
boxData.buttons.forEach(({ button, location, spanX, spanY }) => {
const safeLocation = Number(location) || 0;
const safeSpanX = Number(spanX) || 1;
const safeSpanY = Number(spanY) || 1;
// Calculate button position within the button box
// location is a linear index, convert to grid coordinates
const buttonX = safeLocation % boxWidth;
const buttonY = Math.floor(safeLocation / boxWidth);
// Calculate absolute position on page
const absoluteX = boxX + buttonX;
const absoluteY = boxY + buttonY;
// Set button's x and y coordinates
button.x = absoluteX;
button.y = absoluteY;
// Add button to page
page.addButton(button);
// Place button in grid (handle span)
for (let r = absoluteY; r < absoluteY + safeSpanY && r < 10; r++) {
for (let c = absoluteX; c < absoluteX + safeSpanX && c < 10; c++) {
if (pageGrid && pageGrid[r] && pageGrid[r][c] === null) {
pageGrid[r][c] = button;
}
}
}
});
}
});
// Set grid layouts for all pages
pageGrids.forEach((grid, pageId) => {
const page = tree.getPage(pageId);
if (page) {
page.grid = grid;
// Generate clone_id for each button in the grid
const semanticIds: string[] = [];
const cloneIds: string[] = [];
grid.forEach((row, rowIndex) => {
row.forEach((btn, colIndex) => {
if (btn) {
// Generate clone_id based on position and label
const rows = grid.length;
const cols = grid[0] ? grid[0].length : 10;
btn.clone_id = generateCloneId(rows, cols, rowIndex, colIndex, btn.label);
cloneIds.push(btn.clone_id);
// Track semantic_id if present
if (btn.semantic_id) {
semanticIds.push(btn.semantic_id);
}
}
});
});
// Track IDs on the page
if (semanticIds.length > 0) {
page.semantic_ids = semanticIds;
}
if (cloneIds.length > 0) {
page.clone_ids = cloneIds;
}
}
});
} catch (e) {
// console.log('No button box cells found:', e);
}
// Load buttons directly linked to pages via resources
const pageButtonsQuery = `
SELECT b.*, r.*
FROM buttons b
JOIN resources r ON r.id = b.resource_id
WHERE r.type = 7
`;
try {
const pageButtons = db.prepare(pageButtonsQuery).all() as (TouchChatButton & {
type: number;
})[];
pageButtons.forEach((btnRow) => {
const style = buttonStyles.get(btnRow.button_style_id);
// Create semantic action for TouchChat button
const semanticAction: AACSemanticAction = {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.SPEAK_TEXT,
text: btnRow.message || btnRow.label || '',
platformData: {
touchChat: {
actionCode: 0, // Default speak action
actionData: btnRow.message || btnRow.label || '',
},
},
fallback: {
type: 'SPEAK',
message: btnRow.message || btnRow.label || '',
},
};
const button = new AACButton({
id: String(btnRow.id),
label: btnRow.label || '',
message: btnRow.message || '',
semanticAction: semanticAction,
visibility: mapTouchChatVisibility(btnRow.visible),
// Note: TouchChat does not use scan blocks in the file
// Scanning is a runtime feature (linear/row-column patterns)
// scanBlock defaults to 1 (no grouping)
style: {
backgroundColor: intToHex(style?.body_color),
borderColor: intToHex(style?.border_color),
borderWidth: toNumberOrUndefined(style?.border_width),
fontColor: intToHex(style?.font_color),
fontSize: toNumberOrUndefined(style?.font_height),
fontFamily: toStringOrUndefined(style?.font_name),
fontWeight: style?.font_bold ? 'bold' : undefined,
fontStyle: style?.font_italic ? 'italic' : undefined,
textUnderline: toBooleanOrUndefined(style?.font_underline),
transparent: toBooleanOrUndefined(style?.transparent),
labelOnTop: toBooleanOrUndefined(style?.label_on_top),
},
});
// Find the page that references this resource
const page = Object.values(tree.pages).find(
(p) => p.id === (numericToRid.get(btnRow.id) || String(btnRow.id))
);
if (page) page.addButton(button);
});
} catch (e) {
// console.log('No direct page buttons found:', e);
}
// Load navigation actions
const navActionsQuery = `
SELECT a.resource_id, COALESCE(${hasRid ? 'r_rid.rid, r_id.rid, ' : ''}r_id.id, ad.value) as target_page_id
FROM actions a
JOIN action_data ad ON ad.action_id = a.id
${hasRid ? 'LEFT JOIN resources r_rid ON r_rid.rid = ad.value AND r_rid.type = 7' : ''}
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
WHERE a.code IN (1, 8, 9)
`;
try {
const navActions = db.prepare(navActionsQuery).all() as {
resource_id: number;
target_page_id: string;
}[];
navActions.forEach((nav) => {
// Find button in any page by its resourceId
for (const pageId in tree.pages) {
const page = tree.pages[pageId];
const button = page.buttons.find(
(b) => b.semanticAction?.platformData?.touchChat?.resourceId === nav.resource_id
);
if (button) {
// Use mapped string ID for target page if available
const numericTargetId = parseInt(String(nav.target_page_id));
const targetPageId = !isNaN(numericTargetId)
? numericToRid.get(numericTargetId) || String(numericTargetId)
: String(nav.target_page_id);
button.targetPageId = targetPageId;
// Create semantic action for navigation
button.semanticAction = {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.NAVIGATE_TO,
targetId: String(targetPageId),
platformData: {
touchChat: {
actionCode: 1, // TouchChat navigation code
actionData: String(targetPageId),
},
},
fallback: {
type: 'NAVIGATE',
targetPageId: String(targetPageId),
},
};
break;
}
}
});
} catch (e) {
// console.log('No navigation actions found:', e);
}
// Try to load root ID from multiple sources in order of priority
try {
// First, try to get HOME page from special_pages table (TouchChat specific)
const specialPagesQuery = "SELECT page_id FROM special_pages WHERE name = 'HOME'";
const homePageRow = db.prepare(specialPagesQuery).get() as { page_id: number } | undefined;
if (homePageRow) {
// The page_id is the page's id (not resource_id), need to get the RID
const homePageIdQuery = `
SELECT p.id, r.rid
FROM pages p
JOIN resources r ON r.id = p.resource_id
WHERE p.id = ?
LIMIT 1
`;
const homePage = db.prepare(homePageIdQuery).get(homePageRow.page_id) as
| {
id: number;
rid?: string;
}
| undefined;
if (homePage) {
const homePageUUID = homePage.rid || String(homePage.id);
if (tree.getPage(homePageUUID)) {
tree.rootId = homePageUUID;
tree.metadata.defaultHomePageId = homePageUUID;
}
}
}
// If no HOME page found, try tree_metadata table (general fallback)
if (!tree.rootId) {
const metadataQuery = "SELECT value FROM tree_metadata WHERE key = 'rootId'";
const rootIdRow = db.prepare(metadataQuery).get() as { value: string } | undefined;
if (rootIdRow && tree.getPage(rootIdRow.value)) {
tree.rootId = rootIdRow.value;
tree.metadata.defaultHomePageId = rootIdRow.value;
}
}
// Final fallback: first page
if (!tree.rootId && rootPageId) {
tree.rootId = rootPageId;
tree.metadata.defaultHomePageId = rootPageId;
}
} catch (e) {
// No metadata table or other error, use first page as root
if (rootPageId) {
tree.rootId = rootPageId;
tree.metadata.defaultHomePageId = rootPageId;
}
}
// Set metadata for TouchChat files
tree.metadata.format = 'touchchat';
return tree;
} finally {
// Clean up
if (cleanup) {
cleanup();
} else if (db) {
db.close();
}
}
}
async processTexts(
filePathOrBuffer: ProcessorInput,
translations: Map<string, string>,
outputPath: string
): Promise<Uint8Array> {
if (!isNodeRuntime()) {
throw new Error(
'processTexts is only supported in Node.js environments for TouchChat files.'
);
}
/**
* TouchChat .ce files are ZIP archives containing a SQLite .c4v database.
* Rebuilding the database can drop tables/metadata/resources that we don't
* currently model in the tree, which can corrupt the file.
*
* For file paths, we preserve the original archive and update text in-place
* within the embedded SQLite database, ensuring assets and metadata remain intact.
*/
if (typeof filePathOrBuffer === 'string') {
const fs = getFs();
const path = getPath();
const os = getOs();
const AdmZip = getNodeRequire()('adm-zip') as typeof import('adm-zip');
const inputPath = filePathOrBuffer;
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
if (fs.existsSync(outputPath)) {
fs.unlinkSync(outputPath);
}
const zip = new AdmZip(inputPath);
const entries = zip.getEntries();
const vocabEntry = entries.find((entry) => entry.entryName.endsWith('.c4v'));
if (!vocabEntry) {
throw new Error('No .c4v vocab DB found in TouchChat export');
}
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'touchchat-translate-'));
const dbPath = path.join(tempDir, 'vocab.c4v');
try {
fs.writeFileSync(dbPath, vocabEntry.getData());
const Database = requireBetterSqlite3();
const db = new Database(dbPath, { readonly: false });
try {
const getColumns = (tableName: string): Set<string> => {
try {
const rows = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{
name: string;
}>;
return new Set(rows.map((row) => row.name));
} catch {
return new Set();
}
};
const resourceColumns = getColumns('resources');
const pageColumns = getColumns('pages');
const buttonColumns = getColumns('buttons');
const updatePageResourceName = resourceColumns.has('name')
? db.prepare(
'UPDATE resources SET name = ? WHERE name = ? AND id IN (SELECT resource_id FROM pages)'
)
: null;
const updatePageName = pageColumns.has('name')
? db.prepare('UPDATE pages SET name = ? WHERE name = ?')
: null;
const updateButtonLabel = buttonColumns.has('label')
? db.prepare('UPDATE buttons SET label = ? WHERE label = ?')
: null;
const updateButtonMessage = buttonColumns.has('message')
? db.prepare('UPDATE buttons SET message = ? WHERE message = ?')
: null;
const entriesToUpdate = Array.from(translations.entries());
const applyUpdates = db.transaction(() => {
entriesToUpdate.forEach(([original, translated]) => {
if (!translated || translated === original) {
return;
}
if (updatePageResourceName) {
updatePageResourceName.run(translated, original);
}
if (updatePageName) {
updatePageName.run(translated, original);
}
if (updateButtonLabel) {
updateButtonLabel.run(translated, original);
}
if (updateButtonMessage) {
updateButtonMessage.run(translated, original);
}
});
});
applyUpdates();
} finally {
db.close();
}
const outputZip = new AdmZip();
entries.forEach((entry) => {
if (entry.entryName === vocabEntry.entryName) {
return;
}
const data = entry.isDirectory ? Buffer.alloc(0) : entry.getData();
outputZip.addFile(entry.entryName, data, entry.comment || '');
});
outputZip.addFile(vocabEntry.entryName, fs.readFileSync(dbPath));
outputZip.writeZip(outputPath);
} finally {
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch {
// Best-effort cleanup
}
}
return fs.readFileSync(outputPath);
}
// Fallback for buffer inputs: rebuild from tree (may drop TouchChat metadata)
const tree = await this.loadIntoTree(filePathOrBuffer);
Object.values(tree.pages).forEach((page) => {
if (page.name && translations.has(page.name)) {
const translatedName = translations.get(page.name);
if (translatedName !== undefined) {
page.name = translatedName;
}
}
page.buttons.forEach((button) => {
if (button.label && translations.has(button.label)) {
const translatedLabel = translations.get(button.label);
if (translatedLabel !== undefined) {
button.label = translatedLabel;
}
}
if (button.message && translations.has(button.message)) {
const translatedMessage = translations.get(button.message);
if (translatedMessage !== undefined) {
button.message = translatedMessage;
}
}
});
});
await this.saveFromTree(tree, outputPath);
const fs = getFs();
return fs.readFileSync(outputPath);
}
async saveFromTree(tree: AACTree, outputPath: string): Promise<void> {
await Promise.resolve();
if (!isNodeRuntime()) {
throw new Error(
'saveFromTree is only supported in Node.js environments for TouchChat files.'
);
}
const fs = getFs();
const path = getPath();
const os = getOs();
// Create a TouchChat database that matches the expected schema for loading
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'touchchat-export-'));
const dbPath = path.join(tmpDir, 'vocab.c4v');
try {
const Database = requireBetterSqlite3();
const db = new Database(dbPath);
// Create schema that matches what loadIntoTree expects
db.exec(`
CREATE TABLE IF NOT EXISTS resources (
id INTEGER PRIMARY KEY,
name TEXT,
type INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS pages (
id INTEGER PRIMARY KEY,
resource_id INTEGER,
name TEXT,
symbol_link_id INTEGER,
page_style_id INTEGER DEFAULT 1,
button_style_id INTEGER DEFAULT 1,
feature INTEGER,
FOREIGN KEY (resource_id) REFERENCES resources (id)
);
CREATE TABLE IF NOT EXISTS buttons (
id INTEGER PRIMARY KEY,
resource_id INTEGER,
label TEXT,
message TEXT,
symbol_link_id INTEGER,
visible INTEGER DEFAULT 1,
button_style_id INTEGER DEFAULT 1,
pronunciation TEXT,
skin_tone_override INTEGER,
FOREIGN KEY (resource_id) REFERENCES resources (id)
);
CREATE TABLE IF NOT EXISTS button_boxes (
id INTEGER PRIMARY KEY,
resource_id INTEGER,
layout_x INTEGER DEFAULT 10,
layout_y INTEGER DEFAULT 6,
init_size_x INTEGER DEFAULT 10000,
init_size_y INTEGER DEFAULT 10000,
scan_pattern_id INTEGER DEFAULT 0,
FOREIGN KEY (resource_id) REFERENCES resources (id)
);
CREATE TABLE IF NOT EXISTS button_box_cells (
id INTEGER PRIMARY KEY,
button_box_id INTEGER,
resource_id INTEGER,
location INTEGER,
span_x INTEGER DEFAULT 1,
span_y INTEGER DEFAULT 1,
button_style_id INTEGER DEFAULT 1,
label TEXT,
message TEXT,
box_id INTEGER,
FOREIGN KEY (button_box_id) REFERENCES button_boxes (id),
FOREIGN KEY (resource_id) REFERENCES resources (id),
FOREIGN KEY (button_style_id) REFERENCES button_styles (id)
);
CREATE TABLE IF NOT EXISTS button_box_instances (
id INTEGER PRIMARY KEY,
page_id INTEGER,
button_box_id INTEGER,
position_x INTEGER DEFAULT 0,
position_y INTEGER DEFAULT 0,
size_x INTEGER DEFAULT 1,
size_y INTEGER DEFAULT 1,
FOREIGN KEY (page_id) REFERENCES pages (id),
FOREIGN KEY (button_box_id) REFERENCES button_boxes (id)
);
CREATE TABLE IF NOT EXISTS actions (
id INTEGER PRIMARY KEY,
resource_id INTEGER,
code INTEGER,
FOREIGN KEY (resource_id) REFERENCES resources (id)
);
CREATE TABLE IF NOT EXISTS action_data (
id INTEGER PRIMARY KEY,
action_id INTEGER,
value TEXT,
FOREIGN KEY (action_id) REFERENCES actions (id)
);
CREATE TABLE IF NOT EXISTS tree_metadata (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS page_id_mapping (
numeric_id INTEGER PRIMARY KEY,
string_id TEXT UNIQUE
);
CREATE TABLE IF NOT EXISTS button_styles (
id INTEGER PRIMARY KEY,
label_on_top INTEGER DEFAULT 0,
force_label_on_top INTEGER DEFAULT 0,
transparent INTEGER DEFAULT 0,
force_transparent INTEGER DEFAULT 0,
font_color INTEGER,
force_font_color INTEGER DEFAULT 0,
body_color INTEGER,
force_body_color INTEGER DEFAULT 0,
border_color INTEGER,
force_border_color INTEGER DEFAULT 0,
border_width REAL,
force_border_width INTEGER DEFAULT 0,
font_name TEXT,
font_bold INTEGER DEFAULT 0,
font_underline INTEGER DEFAULT 0,
font_italic INTEGER DEFAULT 0,
font_height REAL,
force_font INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS page_styles (
id INTEGER PRIMARY KEY,
bg_color INTEGER,
force_bg_color INTEGER DEFAULT 0,
bg_alignment INTEGER DEFAULT 0,
force_bg_alignment INTEGER DEFAULT 0
);
`);
// Insert default styles
db.prepare('INSERT INTO button_styles (id) VALUES (1)').run();
db.prepare('INSERT INTO page_styles (id) VALUES (1)').run();
// Helper function to convert hex color to integer
const hexToInt = (hexColor?: string): number | null => {
if (!hexColor) return null;
const hex = hexColor.replace('#', '');
return parseInt(hex, 16);
};
// Insert pages and buttons using the proper schema
let resourceIdCounter = 1;
let pageIdCounter = 1;
let buttonIdCounter = 1;
let buttonBoxIdCounter = 1;
let buttonBoxInstanceIdCounter = 1;
let actionIdCounter = 1;
let buttonStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
let pageStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
// Create mapping from string IDs to numeric IDs
const pageIdMap = new Map<string, number>();
const insertedButtonIds = new Set<number>();
const buttonStyleMap = new Map<string, number>();
const pageStyleMap = new Map<string, number>();
// First pass: create pages and map IDs
Object.values(tree.pages).forEach((page) => {
// Try to use numeric ID if possible, otherwise assign sequential ID
const numericPageId = /^\d+$/.test(page.id) ? parseInt(page.id) : pageIdCounter++;
pageIdMap.set(page.id, numericPageId);
// Create page style if needed
let pageStyleId = 1; // default style
if (page.style && page.style.backgroundColor) {
const styleKey = JSON.stringify(page.style);
if (!pageStyleMap.has(styleKey)) {
pageStyleId = pageStyleIdCounter++;
pageStyleMap.set(styleKey, pageStyleId);
const insertPageStyle = db.prepare(
'INSERT INTO page_styles (id, bg_color, force_bg_color) VALUES (?, ?, ?)'
);
insertPageStyle.run(
pageStyleId,
hexToInt(page.style.backgroundColor),
page.style.backgroundColor ? 1 : 0
);
} else {
const existingPageStyleId = pageStyleMap.get(styleKey);
if (typeof existingPageStyleId === 'number') {
pageStyleId = existingPageStyleId;