-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsnapProcessor.ts
More file actions
1542 lines (1398 loc) · 57 KB
/
Copy pathsnapProcessor.ts
File metadata and controls
1542 lines (1398 loc) · 57 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,
} from '../core/baseProcessor';
import {
AACTree,
AACPage,
AACButton,
AACSemanticAction,
AACSemanticCategory,
AACSemanticIntent,
SnapMetadata,
} from '../core/treeStructure';
import { generateCloneId } from '../utilities/analytics/utils/idGenerator';
import { SnapValidator } from '../validation/snapValidator';
import { ValidationResult } from '../validation/validationTypes';
import { ProcessorInput, getNodeRequire, isNodeRuntime } from '../utils/io';
import { openSqliteDatabase, requireBetterSqlite3 } from '../utils/sqlite';
/**
* Convert a Buffer or Uint8Array to base64 string (browser and Node compatible)
* Node.js Buffers support toString('base64'), but Uint8Arrays in browser do not.
* This function works in both environments.
*/
function arrayBufferToBase64(data: Buffer | Uint8Array): string {
// Node.js environment - Buffer has built-in base64 encoding
if (typeof Buffer !== 'undefined' && data instanceof Buffer) {
return data.toString('base64');
}
// Browser environment - use btoa with binary string conversion
const bytes = new Uint8Array(data);
let binary = '';
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
interface SnapButton {
Id: number;
Label: string;
Message: string | null;
LibrarySymbolId?: number | null;
PageSetImageId?: number | null;
NavigatePageId: number | null;
MessageRecordingId?: number | null;
UseMessageRecording?: number | null;
SerializedMessageSoundMetadata?: string | null;
LabelColor?: number;
BackgroundColor?: number;
BorderColor?: number;
BorderThickness?: number;
FontSize?: number;
FontFamily?: string;
FontStyle?: number;
Visible?: number; // 0 = hidden, 1 (or non-zero) = visible
}
/**
* Map Snap Visible value to AAC standard visibility
* Snap: 0 = hidden, 1 (or non-zero) = visible
* Maps to: 'Hidden' | 'Visible' | undefined
*/
function mapSnapVisibility(visible: number | null | undefined): 'Hidden' | 'Visible' | undefined {
if (visible === null || visible === undefined) {
return undefined; // Default to visible
}
return visible === 0 ? 'Hidden' : 'Visible';
}
interface SnapPage {
Id: number;
Name: string;
Buttons: SnapButton[];
ParentId: number | null;
BackgroundColor?: number;
}
class SnapProcessor extends BaseProcessor {
readonly capabilities = {
wordList: 'none' as const,
preservesAssetsOnSave: false,
newCellCreation: 'allowed' as const,
};
private symbolResolver: unknown | null = null;
private loadAudio: boolean = false;
private pageLayoutPreference: 'largest' | 'smallest' | 'scanning' | number = 'scanning'; // Default to scanning for metrics
constructor(
symbolResolver: unknown | null = null,
options?: ProcessorOptions & {
loadAudio?: boolean;
pageLayoutPreference?: 'largest' | 'smallest' | 'scanning' | number;
}
) {
super(options);
this.symbolResolver = symbolResolver;
this.loadAudio = options?.loadAudio !== undefined ? options.loadAudio : true;
this.pageLayoutPreference =
options?.pageLayoutPreference !== undefined ? options.pageLayoutPreference : 'scanning'; // Default to scanning
}
async extractTexts(filePathOrBuffer: ProcessorInput): Promise<string[]> {
const tree = await this.loadIntoTree(filePathOrBuffer);
const texts: string[] = [];
for (const pageId in tree.pages) {
const page = tree.pages[pageId];
// Include page names
if (page.name) texts.push(page.name);
// Include button texts
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> {
const { writeBinaryToPath, removePath, mkTempDir, basename, join } = this.options.fileAdapter;
const tree = new AACTree();
let dbResult: Awaited<ReturnType<typeof openSqliteDatabase>> | null = null;
let cleanupTempZip: (() => Promise<void>) | null = null;
try {
// Handle .sub.zip files (Snap pageset backups containing .sps files)
let inputFile = filePathOrBuffer;
if (typeof filePathOrBuffer === 'string') {
const fileName = basename(filePathOrBuffer).toLowerCase();
if (fileName.endsWith('.sub.zip') || filePathOrBuffer.endsWith('.sub')) {
// Extract .sub.zip to find the embedded .sps file
const tempDir = await mkTempDir('snap-sub-');
const zip = await this.options.zipAdapter(filePathOrBuffer);
// Find the .sps file in the archive
const files = zip.listFiles();
const spsFile = files.find((f) => f.endsWith('.sps'));
if (!spsFile) {
await removePath(tempDir, { recursive: true, force: true });
throw new Error('No .sps file found in .sub.zip archive');
}
// Extract the .sps file
const spsData = await zip.readFile(spsFile);
const extractedSpsPath = join(tempDir, basename(spsFile));
await writeBinaryToPath(extractedSpsPath, Buffer.from(spsData));
inputFile = extractedSpsPath;
cleanupTempZip = async () => {
await removePath(tempDir, { recursive: true, force: true });
};
}
}
dbResult = await openSqliteDatabase(inputFile, {
readonly: true,
fileAdapter: this.options.fileAdapter,
});
const db = dbResult.db;
const getTableColumns = (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();
}
};
// Load pages first, using UniqueId as canonical id
const pages = db.prepare('SELECT * FROM Page').all();
// Load PageSetProperties to find default Keyboard and Home pages
let defaultKeyboardPageId: string | undefined;
let defaultHomePageId: string | undefined;
let dashboardPageId: string | undefined;
let toolbarId: string | undefined;
try {
const properties = db.prepare('SELECT * FROM PageSetProperties').get();
if (properties) {
defaultKeyboardPageId = properties.DefaultKeyboardPageUniqueId;
defaultHomePageId = properties.DefaultHomePageUniqueId;
dashboardPageId = properties.DashboardUniqueId;
toolbarId = properties.ToolBarUniqueId;
const hasGlobalToolbar =
toolbarId && toolbarId !== '00000000-0000-0000-0000-000000000000';
// Store metadata in tree
const metadata: SnapMetadata = {
format: 'snap',
name: properties.Name || properties.PageSetName || undefined,
description: properties.Description || undefined,
author: properties.Author || undefined,
locale: properties.Locale || undefined,
languages: properties.Locale ? [properties.Locale] : undefined,
defaultKeyboardPageId: defaultKeyboardPageId || undefined,
defaultHomePageId: defaultHomePageId || undefined,
dashboardId: dashboardPageId || undefined,
hasGlobalToolbar: !!hasGlobalToolbar,
};
tree.metadata = metadata;
// Set toolbarId if there's a global toolbar
if (hasGlobalToolbar) {
tree.toolbarId = toolbarId || null;
// Use defaultHomePageId as root (the content pageset), not the toolbar
tree.rootId = defaultHomePageId || null;
} else if (defaultHomePageId) {
tree.rootId = defaultHomePageId;
}
}
} catch (e) {
console.warn('[SnapProcessor] Failed to load PageSetProperties:', e);
}
// If still no root, fallback to first page (but don't override a valid defaultHomePageId)
if (!tree.rootId && pages.length > 0) {
tree.rootId = String(pages[0].UniqueId || pages[0].Id);
}
// Map from numeric Id -> UniqueId for later lookup
const idToUniqueId: Record<string, string> = {};
pages.forEach((pageRow: SnapPage) => {
const uniqueId = String((pageRow as any).UniqueId || pageRow.Id);
idToUniqueId[String(pageRow.Id)] = uniqueId;
const page = new AACPage({
id: uniqueId,
name: (pageRow as any).Title || pageRow.Name,
grid: [],
buttons: [],
parentId: null, // ParentId will be set via navigation buttons below
style: {
backgroundColor: pageRow.BackgroundColor
? `#${pageRow.BackgroundColor.toString(16)}`
: undefined,
},
});
tree.addPage(page);
});
// Try to find toolbar page even if not set in PageSetProperties
// Some SNAP files have a toolbar page but don't set ToolBarUniqueId
// This must be done AFTER pages are added to the tree
if (!tree.toolbarId || tree.toolbarId === '00000000-0000-0000-0000-000000000000') {
const toolbarPage = Object.values(tree.pages).find((p) => {
const name = (p.name || '').toLowerCase();
return name === 'tool bar' || name === 'toolbar';
});
if (toolbarPage) {
tree.toolbarId = toolbarPage.id;
// Update metadata to reflect toolbar detection
if (tree.metadata) {
(tree.metadata as any).hasGlobalToolbar = true;
}
}
}
// Load ScanGroups for TD Snap "Group Scan" feature
// Maps PageLayoutId -> Array of ScanGroups with their scan block numbers
interface SnapScanGroup {
id: number;
scanBlock: number; // 1-based, determined by ScanGroup index within PageLayout
positions: Array<{ Column: number; Row: number }>;
}
const scanGroupsByPageLayout = new Map<number, SnapScanGroup[]>();
try {
const scanGroupRows = db
.prepare('SELECT Id, SerializedGridPositions, PageLayoutId FROM ScanGroup ORDER BY Id')
.all() as {
Id: number;
SerializedGridPositions: string;
PageLayoutId: number;
}[];
if (scanGroupRows && scanGroupRows.length > 0) {
// Group by PageLayoutId first
const groupsByLayout = new Map<number, any[]>();
scanGroupRows.forEach((sg) => {
if (!groupsByLayout.has(sg.PageLayoutId)) {
groupsByLayout.set(sg.PageLayoutId, []);
}
const layoutGroups = groupsByLayout.get(sg.PageLayoutId);
if (layoutGroups) {
layoutGroups.push(sg);
}
});
// For each PageLayout, assign scan block numbers based on order (1-based index)
groupsByLayout.forEach((groups, layoutId) => {
groups.forEach((sg, index) => {
// Parse SerializedGridPositions JSON
let positions: Array<{ Column: number; Row: number }> = [];
try {
positions = JSON.parse(sg.SerializedGridPositions as string);
} catch (_e) {
// Invalid JSON, skip this group
return;
}
const scanGroup: SnapScanGroup = {
id: sg.Id,
scanBlock: index + 1, // Scan block is 1-based index
positions: positions,
};
if (!scanGroupsByPageLayout.has(layoutId)) {
scanGroupsByPageLayout.set(layoutId, []);
}
const layoutGroups = scanGroupsByPageLayout.get(layoutId);
if (layoutGroups) {
layoutGroups.push(scanGroup);
}
});
});
}
} catch (e) {
// No ScanGroups table or error loading, continue without scan blocks
console.warn('[SnapProcessor] Failed to load ScanGroups:', e);
}
// Load buttons per page, using UniqueId for page id
for (const pageRow of pages) {
// Create a map to track page grid layouts
const pageGrids = new Map<string, Array<Array<AACButton | null>>>();
// Select PageLayout for this page based on preference
let selectedPageLayoutId: number | null = null;
try {
const pageLayouts = db
.prepare('SELECT Id, PageLayoutSetting FROM PageLayout WHERE PageId = ?')
.all(pageRow.Id) as { Id: number; PageLayoutSetting: string }[];
if (pageLayouts && pageLayouts.length > 0) {
// Parse PageLayoutSetting: "columns,rows,hasScanGroups,?"
const layoutsWithInfo = pageLayouts.map((pl) => {
const parts = pl.PageLayoutSetting.split(',');
const cols = parseInt(parts[0], 10) || 0;
const rows = parseInt(parts[1], 10) || 0;
const hasScanning = parts[2] === 'True';
const size = cols * rows;
return { id: pl.Id, cols, rows, size, hasScanning };
});
// Select based on preference
if (typeof this.pageLayoutPreference === 'number') {
// Specific PageLayoutId
selectedPageLayoutId = this.pageLayoutPreference;
} else if (this.pageLayoutPreference === 'largest') {
// Select layout with largest grid size, prefer layouts with ScanGroups
layoutsWithInfo.sort((a, b) => {
const sizeDiff = b.size - a.size;
if (sizeDiff !== 0) return sizeDiff;
// Same size, prefer one with ScanGroups
const aHasScanning = scanGroupsByPageLayout.has(a.id);
const bHasScanning = scanGroupsByPageLayout.has(b.id);
return (bHasScanning ? 1 : 0) - (aHasScanning ? 1 : 0);
});
selectedPageLayoutId = layoutsWithInfo[0].id;
} else if (this.pageLayoutPreference === 'smallest') {
// Select layout with smallest grid size, prefer layouts with ScanGroups
layoutsWithInfo.sort((a, b) => {
const sizeDiff = a.size - b.size;
if (sizeDiff !== 0) return sizeDiff;
// Same size, prefer one with ScanGroups
const aHasScanning = scanGroupsByPageLayout.has(a.id);
const bHasScanning = scanGroupsByPageLayout.has(b.id);
return (bHasScanning ? 1 : 0) - (aHasScanning ? 1 : 0);
});
selectedPageLayoutId = layoutsWithInfo[0].id;
} else if (this.pageLayoutPreference === 'scanning') {
// Select layout with scanning enabled (check against actual ScanGroups)
const scanningLayouts = layoutsWithInfo.filter((l) =>
scanGroupsByPageLayout.has(l.id)
);
if (scanningLayouts.length > 0) {
scanningLayouts.sort((a, b) => b.size - a.size);
selectedPageLayoutId = scanningLayouts[0].id;
} else {
// Fallback to largest
layoutsWithInfo.sort((a, b) => b.size - a.size);
selectedPageLayoutId = layoutsWithInfo[0].id;
}
}
}
} catch (e) {
// Error selecting PageLayout, will load all buttons
console.warn(`[SnapProcessor] Failed to select PageLayout for page ${pageRow.Id}:`, e);
}
// Load buttons
let buttons: any[] = [];
try {
const buttonColumns = getTableColumns('Button');
const selectFields = [
'b.Id',
'b.Label',
'b.Message',
buttonColumns.has('LibrarySymbolId') ? 'b.LibrarySymbolId' : 'NULL AS LibrarySymbolId',
buttonColumns.has('PageSetImageId') ? 'b.PageSetImageId' : 'NULL AS PageSetImageId',
buttonColumns.has('BorderColor') ? 'b.BorderColor' : 'NULL AS BorderColor',
buttonColumns.has('BorderThickness') ? 'b.BorderThickness' : 'NULL AS BorderThickness',
buttonColumns.has('FontSize') ? 'b.FontSize' : 'NULL AS FontSize',
buttonColumns.has('FontFamily') ? 'b.FontFamily' : 'NULL AS FontFamily',
buttonColumns.has('FontStyle') ? 'b.FontStyle' : 'NULL AS FontStyle',
buttonColumns.has('LabelColor') ? 'b.LabelColor' : 'NULL AS LabelColor',
buttonColumns.has('BackgroundColor') ? 'b.BackgroundColor' : 'NULL AS BackgroundColor',
buttonColumns.has('NavigatePageId') ? 'b.NavigatePageId' : 'NULL AS NavigatePageId',
buttonColumns.has('ContentType') ? 'b.ContentType' : 'NULL AS ContentType',
];
if (this.loadAudio) {
selectFields.push(
buttonColumns.has('MessageRecordingId')
? 'b.MessageRecordingId'
: 'NULL AS MessageRecordingId'
);
selectFields.push(
buttonColumns.has('UseMessageRecording')
? 'b.UseMessageRecording'
: 'NULL AS UseMessageRecording'
);
selectFields.push(
buttonColumns.has('SerializedMessageSoundMetadata')
? 'b.SerializedMessageSoundMetadata'
: 'NULL AS SerializedMessageSoundMetadata'
);
}
const placementColumns = getTableColumns('ElementPlacement');
const hasButtonPageLink = getTableColumns('ButtonPageLink').size > 0;
selectFields.push(
placementColumns.has('GridPosition') ? 'ep.GridPosition' : 'NULL AS GridPosition',
placementColumns.has('PageLayoutId') ? 'ep.PageLayoutId' : 'NULL AS PageLayoutId',
placementColumns.has('Visible') ? 'ep.Visible' : 'NULL AS Visible',
'er.PageId as ButtonPageId'
);
if (hasButtonPageLink) {
selectFields.push('bpl.PageUniqueId AS LinkedPageUniqueId');
} else {
selectFields.push('NULL AS LinkedPageUniqueId');
}
const hasCommandSequence = getTableColumns('CommandSequence').size > 0;
if (hasCommandSequence) {
selectFields.push('cs.SerializedCommands');
} else {
selectFields.push('NULL AS SerializedCommands');
}
const buttonQuery = `
SELECT ${selectFields.join(', ')}
FROM Button b
INNER JOIN ElementReference er ON b.ElementReferenceId = er.Id
LEFT JOIN ElementPlacement ep ON ep.ElementReferenceId = er.Id
${hasButtonPageLink ? 'LEFT JOIN ButtonPageLink bpl ON b.Id = bpl.ButtonId' : ''}
${hasCommandSequence ? 'LEFT JOIN CommandSequence cs ON b.Id = cs.ButtonId' : ''}
WHERE er.PageId = ? ${selectedPageLayoutId ? 'AND ep.PageLayoutId = ?' : ''}
`;
if (selectedPageLayoutId) {
buttons = db.prepare(buttonQuery).all(pageRow.Id, selectedPageLayoutId);
} else {
buttons = db.prepare(buttonQuery).all(pageRow.Id);
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err);
const errorCode =
err && typeof err === 'object' && 'code' in err ? (err as any).code : undefined;
if (
errorCode === 'SQLITE_CORRUPT' ||
errorCode === 'SQLITE_NOTADB' ||
/malformed/i.test(errorMessage)
) {
throw new Error(`Snap database is corrupted or incomplete: ${errorMessage}`);
}
console.warn(`Failed to load buttons for page ${pageRow.Id}: ${errorMessage}`);
// Skip this page instead of loading all buttons
buttons = [];
}
const uniqueId = String(pageRow.UniqueId || pageRow.Id);
const page = tree.getPage(uniqueId);
if (!page) {
continue;
}
// Initialize page grid if not exists (assume max 10x10 grid)
if (!pageGrids.has(uniqueId)) {
const grid: Array<Array<AACButton | null>> = [];
for (let r = 0; r < 10; r++) {
grid[r] = new Array(10).fill(null);
}
pageGrids.set(uniqueId, grid);
}
const pageGrid = pageGrids.get(uniqueId);
if (!pageGrid) continue;
buttons.forEach((btnRow) => {
// Determine navigation target UniqueId, if possible
let targetPageUniqueId: string | undefined = undefined;
if (btnRow.NavigatePageId && idToUniqueId[String(btnRow.NavigatePageId)]) {
targetPageUniqueId = idToUniqueId[String(btnRow.NavigatePageId)];
} else if (btnRow.LinkedPageUniqueId) {
targetPageUniqueId = String(btnRow.LinkedPageUniqueId);
} else if (btnRow.PageUniqueId) {
targetPageUniqueId = String(btnRow.PageUniqueId);
}
// Parse CommandSequence for navigation targets if not found yet
if (btnRow.SerializedCommands) {
try {
const commands = JSON.parse(btnRow.SerializedCommands as string);
const values = commands.$values || [];
for (const cmd of values) {
if (cmd.$type === '2' && cmd.LinkedPageId) {
// Normal Navigation
targetPageUniqueId = String(cmd.LinkedPageId);
} else if (cmd.$type === '16') {
// Go to Home
targetPageUniqueId = defaultHomePageId;
} else if (cmd.$type === '17') {
// Go to Keyboard
targetPageUniqueId = defaultKeyboardPageId;
} else if (cmd.$type === '18') {
// Go to Dashboard
targetPageUniqueId = dashboardPageId;
}
}
} catch (_e) {
// Ignore JSON parse errors in commands
}
}
// Determine parent page association for this button
const parentPageId = btnRow.ButtonPageId ? String(btnRow.ButtonPageId) : undefined;
const parentUniqueId =
parentPageId && idToUniqueId[parentPageId] ? idToUniqueId[parentPageId] : uniqueId;
// Load audio recording if requested and available
let audioRecording;
if (this.loadAudio && btnRow.MessageRecordingId && btnRow.MessageRecordingId > 0) {
try {
const recordingData = db
.prepare(
`
SELECT Id, Identifier, Data FROM PageSetData WHERE Id = ?
`
)
.get(btnRow.MessageRecordingId) as
| { Id: number; Identifier: string; Data: Buffer }
| undefined;
if (recordingData) {
audioRecording = {
id: recordingData.Id,
data: recordingData.Data,
identifier: recordingData.Identifier,
metadata: btnRow.SerializedMessageSoundMetadata || undefined,
};
}
} catch (e) {
console.warn(`[SnapProcessor] Failed to load audio for button ${btnRow.Id}:`, e);
}
}
// Load symbol image if available
// Note: PageSetImageId references embedded images in PageSetData table
// LibrarySymbolId references external symbol libraries (SymbolStix, etc.)
let buttonImage: string | undefined;
const buttonParameters: { image_id?: string } = {};
if (btnRow.PageSetImageId && btnRow.PageSetImageId > 0) {
try {
const imageData = db
.prepare(
`
SELECT Id, Identifier, Data FROM PageSetData WHERE Id = ?
`
)
.get(btnRow.PageSetImageId) as
| { Id: number; Identifier: string; Data: Buffer }
| undefined;
if (imageData && imageData.Data && imageData.Data.length > 0) {
// Snap files can store different types of image data:
// 1. PNG/JPEG binaries (actual images) - extract and display
// 2. Vector graphics (custom format d7 cd c6 9a) - skip (requires renderer)
const data = imageData.Data;
// Check for PNG: 89 50 4E 47
const isPng =
data.length > 4 &&
data[0] === 0x89 &&
data[1] === 0x50 &&
data[2] === 0x4e &&
data[3] === 0x47;
// Check for JPEG: FF D8 FF
const isJpeg =
data.length > 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff;
if (isPng || isJpeg) {
// Actual PNG/JPEG image - can be displayed
const mimeType = isPng ? 'image/png' : 'image/jpeg';
const base64 = arrayBufferToBase64(data);
buttonImage = `data:${mimeType};base64,${base64}`;
buttonParameters.image_id = imageData.Identifier;
} else {
// Vector graphics or other format - skip rendering
// Store identifier but don't create image URL
buttonParameters.image_id = imageData.Identifier;
}
}
} catch (e) {
console.warn(
`[SnapProcessor] Failed to load image for button ${btnRow.Id} (PageSetImageId: ${btnRow.PageSetImageId}):`,
e
);
}
}
// Create semantic action for Snap button
let semanticAction: AACSemanticAction | undefined;
if (targetPageUniqueId) {
semanticAction = {
category: AACSemanticCategory.NAVIGATION,
intent: AACSemanticIntent.NAVIGATE_TO,
targetId: targetPageUniqueId,
platformData: {
snap: {
navigatePageId: btnRow.NavigatePageId,
elementReferenceId: btnRow.Id,
},
},
fallback: {
type: 'NAVIGATE',
targetPageId: targetPageUniqueId,
},
};
} else {
semanticAction = {
category: AACSemanticCategory.COMMUNICATION,
intent: AACSemanticIntent.SPEAK_TEXT,
text: btnRow.Message || btnRow.Label || '',
platformData: {
snap: {
elementReferenceId: btnRow.Id,
},
},
fallback: {
type: 'SPEAK',
message: btnRow.Message || btnRow.Label || '',
},
};
}
const button = new AACButton({
id: String(btnRow.Id),
label: btnRow.Label || (btnRow.ContentType === 1 ? '[Prediction]' : ''),
message:
btnRow.Message || (btnRow.ContentType === 1 ? '[Prediction]' : btnRow.Label || ''),
targetPageId: targetPageUniqueId,
semanticAction: semanticAction,
contentType: btnRow.ContentType === 1 ? 'AutoContent' : undefined,
contentSubType: btnRow.ContentType === 1 ? 'Prediction' : undefined,
audioRecording: audioRecording,
visibility: mapSnapVisibility(btnRow.Visible as number),
semantic_id: btnRow.LibrarySymbolId
? `snap_symbol_${btnRow.LibrarySymbolId}`
: undefined, // Extract semantic_id from LibrarySymbolId
image: buttonImage,
resolvedImageEntry: buttonImage,
parameters: Object.keys(buttonParameters).length > 0 ? buttonParameters : undefined,
style: {
backgroundColor: btnRow.BackgroundColor
? `#${btnRow.BackgroundColor.toString(16)}`
: undefined,
borderColor: btnRow.BorderColor ? `#${btnRow.BorderColor.toString(16)}` : undefined,
borderWidth: btnRow.BorderThickness,
fontColor: btnRow.LabelColor ? `#${btnRow.LabelColor.toString(16)}` : undefined,
fontSize: btnRow.FontSize,
fontFamily: btnRow.FontFamily,
fontStyle: btnRow.FontStyle?.toString(),
},
});
// Add to the intended parent page
const parentPage = tree.getPage(parentUniqueId);
if (parentPage) {
// Load path: do not record as a user mutation
parentPage._loadButton(button);
// Add button to grid layout if position data is available
const gridPositionStr = String(btnRow.GridPosition || '');
if (gridPositionStr && gridPositionStr.includes(',')) {
// Parse comma-separated coordinates "x,y"
const [xStr, yStr] = gridPositionStr.split(',');
const gridX = parseInt(xStr, 10);
const gridY = parseInt(yStr, 10);
// Set button x,y properties (critical for metrics!)
if (!isNaN(gridX) && !isNaN(gridY)) {
button.x = gridX;
button.y = gridY;
// Determine scan block from ScanGroups (TD Snap "Group Scan")
// IMPORTANT: Only match against ScanGroups from the SAME PageLayout
// A button can exist in multiple layouts with different positions
const buttonPageLayoutId = btnRow.PageLayoutId as number;
if (buttonPageLayoutId && scanGroupsByPageLayout.has(buttonPageLayoutId)) {
const scanGroups = scanGroupsByPageLayout.get(buttonPageLayoutId);
if (scanGroups && scanGroups.length > 0) {
// Find which ScanGroup contains this button's position
for (const scanGroup of scanGroups) {
// Skip if positions array is null or undefined
if (!scanGroup.positions || !Array.isArray(scanGroup.positions)) {
continue;
}
const foundInGroup = scanGroup.positions.some(
(pos) => pos.Column === gridX && pos.Row === gridY
);
if (foundInGroup) {
// Use the scan block number from the ScanGroup
// ScanGroup scanBlock is already 1-based (index + 1)
button.scanBlock = scanGroup.scanBlock;
break; // Found the scan block, stop looking
}
}
}
}
}
// Place button in grid if within bounds and coordinates are valid
if (
!isNaN(gridX) &&
!isNaN(gridY) &&
gridX >= 0 &&
gridY >= 0 &&
gridY < 10 &&
gridX < 10 &&
pageGrid[gridY] &&
pageGrid[gridY][gridX] === null
) {
// Generate clone_id for button at this position
const rows = pageGrid.length;
const cols = pageGrid[0] ? pageGrid[0].length : 10;
button.clone_id = generateCloneId(rows, cols, gridY, gridX, button.label);
pageGrid[gridY][gridX] = button;
}
}
}
// If this is a navigation button, update the target page's parentId
if (targetPageUniqueId) {
const targetPage = tree.getPage(targetPageUniqueId);
if (targetPage) {
targetPage.parentId = parentUniqueId;
}
}
});
// Set grid layout for the current page
const currentPage = tree.getPage(uniqueId);
if (currentPage && pageGrid) {
currentPage.grid = pageGrid;
// Track semantic_ids and clone_ids on the page
const semanticIds: string[] = [];
const cloneIds: string[] = [];
pageGrid.forEach((row) => {
row.forEach((btn) => {
if (btn) {
if (btn.semantic_id) {
semanticIds.push(btn.semantic_id);
}
if (btn.clone_id) {
cloneIds.push(btn.clone_id);
}
}
});
});
if (semanticIds.length > 0) {
currentPage.semantic_ids = semanticIds;
}
if (cloneIds.length > 0) {
currentPage.clone_ids = cloneIds;
}
}
}
return tree;
} catch (error: any) {
const fileIdentifier =
typeof filePathOrBuffer === 'string' ? filePathOrBuffer : '[buffer input]';
// Provide more specific error messages
if (error.code === 'SQLITE_NOTADB') {
throw new Error(
`Invalid SQLite database file: ${typeof filePathOrBuffer === 'string' ? filePathOrBuffer : 'buffer'}`
);
} else if (error.code === 'ENOENT') {
throw new Error(`File not found: ${fileIdentifier}`);
} else if (error.code === 'EACCES') {
throw new Error(`Permission denied accessing file: ${fileIdentifier}`);
} else {
throw new Error(`Failed to load Snap file: ${error.message}`);
}
} finally {
if (dbResult?.cleanup) {
await dbResult.cleanup();
} else if (dbResult?.db) {
dbResult.db.close();
}
// Clean up temporary extracted .sps file from .sub.zip
if (cleanupTempZip) {
try {
await cleanupTempZip();
} catch (e) {
console.warn('[SnapProcessor] Failed to clean up temporary .sps file:', e);
}
}
}
}
async processTexts(
filePathOrBuffer: ProcessorInput,
translations: Map<string, string>,
outputPath: string
): Promise<Uint8Array> {
const { pathExists, mkDir, writeBinaryToPath, readBinaryFromInput, removePath, dirname } =
this.options.fileAdapter;
if (!isNodeRuntime()) {
throw new Error('processTexts is only supported in Node.js environments for Snap files.');
}
if (typeof filePathOrBuffer === 'string') {
const inputPath = filePathOrBuffer;
const outputDir = dirname(outputPath);
const dirExists = await pathExists(outputDir);
if (!dirExists) {
await mkDir(outputDir, { recursive: true });
}
if (await pathExists(outputPath)) {
await removePath(outputPath);
}
await writeBinaryToPath(outputPath, await readBinaryFromInput(inputPath));
const Database = requireBetterSqlite3();
const db = new Database(outputPath, { 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 pageColumns = getColumns('Page');
const buttonColumns = getColumns('Button');
const pageUpdates: string[] = [];
const pageWhere: string[] = [];
const pageColumnsToUse: Array<'Name' | 'Title'> = [];
if (pageColumns.has('Name')) {
pageUpdates.push('Name = ?');
pageWhere.push('Name = ?');
pageColumnsToUse.push('Name');
}
if (pageColumns.has('Title')) {
pageUpdates.push('Title = ?');
pageWhere.push('Title = ?');
pageColumnsToUse.push('Title');
}
const updatePage =
pageUpdates.length > 0
? db.prepare(
`UPDATE Page SET ${pageUpdates.join(', ')} WHERE ${pageWhere.join(' OR ')}`
)
: null;
const updateLabel = buttonColumns.has('Label')
? db.prepare('UPDATE Button SET Label = ? WHERE Label = ?')
: null;
const updateMessage = buttonColumns.has('Message')
? db.prepare('UPDATE Button SET Message = ? WHERE Message = ?')
: null;
const entries = Array.from(translations.entries());
const applyUpdates = db.transaction(() => {
entries.forEach(([original, translated]) => {
if (!translated || translated === original) {
return;
}
if (updatePage) {
const updateValues: string[] = [];
pageColumnsToUse.forEach(() => updateValues.push(translated));
pageColumnsToUse.forEach(() => updateValues.push(original));
updatePage.run(...updateValues);
}
if (updateLabel) {
updateLabel.run(translated, original);
}
if (updateMessage) {
updateMessage.run(translated, original);
}
});
});
applyUpdates();
} finally {
db.close();
}
return await readBinaryFromInput(outputPath);
}
// Fallback for buffer inputs: rebuild from tree (may drop Snap assets)
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);
return await readBinaryFromInput(outputPath);
}
async saveFromTree(tree: AACTree, outputPath: string): Promise<void> {
const { pathExists, mkDir, removePath, dirname } = this.options.fileAdapter;
if (!isNodeRuntime()) {
throw new Error('saveFromTree is only supported in Node.js environments for Snap files.');
}
const outputDir = dirname(outputPath);
const dirExists = await pathExists(outputDir);
if (!dirExists) {
await mkDir(outputDir, { recursive: true });
}
if (await pathExists(outputPath)) {
await removePath(outputPath);
}
// Create a new SQLite database for Snap format
const Database = requireBetterSqlite3();
const db = new Database(outputPath, { readonly: false });
try {
// Create basic Snap database schema (simplified)
db.exec(`
CREATE TABLE IF NOT EXISTS Page (
Id INTEGER PRIMARY KEY,
UniqueId TEXT UNIQUE,
Title TEXT,
Name TEXT,
BackgroundColor INTEGER
);