Repository navigation
Expand file tree
/
Copy pathshapeSnap.ts
More file actions
807 lines (673 loc) · 20.2 KB
/
Copy pathshapeSnap.ts
File metadata and controls
807 lines (673 loc) · 20.2 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
import {
Element,
Geometry,
NativeUIUtils,
PluginCommAPI,
PluginFileAPI,
PluginNoteAPI,
PointUtils,
type Point,
} from 'sn-plugin-lib';
import {
ensurePermissions,
FILE_READ_PERMISSION,
FILE_WRITE_PERMISSION,
} from '../permissions';
import {
detectBestShape,
type GeometryDescriptor,
type PointLike,
} from './shapeMatching';
export const SNAP_SHAPE_BUTTON_ID = 4200;
type APIErrorShape = {
code?: number;
message?: string;
};
type APIResponse<T> = {
success: boolean;
result?: T;
error?: APIErrorShape;
};
type Size = {
width: number;
height: number;
};
type LayerInfo = {
layerId: number;
isCurrentLayer: boolean;
};
type Bounds = {
left: number;
top: number;
right: number;
bottom: number;
width: number;
height: number;
diagonal: number;
center: PointLike;
};
type StrokeInfo = {
element: Element;
pageIndex: number;
layerNum: number;
bounds: Bounds;
strokePath: PointLike[];
samplePoints: PointLike[];
recognitionName: string | null;
penColor: number;
penType: number;
thickness: number;
};
type StrokeCluster = {
strokes: StrokeInfo[];
insertionIndex: number;
layerNum: number;
};
type GeometryStyle = {
penColor: number;
penType: number;
penWidth: number;
};
type ClusterReplacement = {
insertionIndex: number;
replacedUuids: Set<string>;
geometryElement: Element;
};
type ClusterMatch = {
cluster: StrokeCluster;
geometryDescriptor: GeometryDescriptor;
};
type FastPathPlan = {
geometries: Geometry[];
};
type FastPathOutcome =
| {
kind: 'plan';
plan: FastPathPlan;
}
| {
kind: 'no_match';
}
| {
kind: 'fallback';
};
let isSnapping = false;
function asResponse<T>(value: unknown): APIResponse<T> {
return value as APIResponse<T>;
}
function describeError(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === 'string') {
return error;
}
return 'Unknown error';
}
async function showStatus(message: string, isSuccess: boolean): Promise<void> {
try {
await NativeUIUtils.showRattaDialog(message, 'OK', '', isSuccess);
} catch (error) {
console.warn('Failed to show Snap Shape dialog', describeError(error));
}
}
function throwIfFailed<T>(response: APIResponse<T>, context: string): T {
if (!response?.success) {
throw new Error(response?.error?.message ?? context);
}
return response.result as T;
}
function distance(a: PointLike, b: PointLike): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
function buildBounds(points: PointLike[]): Bounds {
let left = Number.POSITIVE_INFINITY;
let top = Number.POSITIVE_INFINITY;
let right = Number.NEGATIVE_INFINITY;
let bottom = Number.NEGATIVE_INFINITY;
for (const point of points) {
left = Math.min(left, point.x);
top = Math.min(top, point.y);
right = Math.max(right, point.x);
bottom = Math.max(bottom, point.y);
}
const width = Math.max(right - left, 1);
const height = Math.max(bottom - top, 1);
return {
left,
top,
right,
bottom,
width,
height,
diagonal: Math.hypot(width, height),
center: {
x: left + width / 2,
y: top + height / 2,
},
};
}
function boundsGap(left: Bounds, right: Bounds): number {
const horizontal =
Math.max(0, left.left - right.right) + Math.max(0, right.left - left.right);
const vertical =
Math.max(0, left.top - right.bottom) + Math.max(0, right.top - left.bottom);
return Math.hypot(horizontal, vertical);
}
function dominantValue(values: number[], fallback: number): number {
if (!values.length) {
return fallback;
}
const counts = new Map<number, number>();
for (const value of values) {
counts.set(value, (counts.get(value) ?? 0) + 1);
}
let bestValue = fallback;
let bestCount = -1;
for (const [value, count] of counts) {
if (count > bestCount) {
bestValue = value;
bestCount = count;
}
}
return bestValue;
}
function median(values: number[], fallback: number): number {
if (!values.length) {
return fallback;
}
const sorted = values.slice().sort((left, right) => left - right);
const middle = Math.floor(sorted.length / 2);
if (sorted.length % 2 === 1) {
return sorted[middle];
}
return (sorted[middle - 1] + sorted[middle]) / 2;
}
function normalizePoint(point: PointLike): PointLike {
return {
x: Math.round(point.x * 1000) / 1000,
y: Math.round(point.y * 1000) / 1000,
};
}
function samePoint(left: PointLike, right: PointLike): boolean {
return distance(left, right) <= 0.5;
}
export function closePolygonPoints(points: PointLike[]): PointLike[] {
if (points.length < 3) {
return points.slice();
}
const first = points[0];
const last = points[points.length - 1];
if (samePoint(first, last)) {
return points.slice();
}
return points.concat([{...first}]);
}
function isLayerUnsupportedError(error: unknown): boolean {
const message =
typeof error === 'string'
? error
: error instanceof Error
? error.message
: '';
return /cannot operate on layers/i.test(message);
}
async function readAllAccessorItems<T>(
accessor: {
size(): Promise<number>;
getRange(startIndex: number, count: number): Promise<T[]>;
} | null | undefined,
): Promise<T[]> {
if (!accessor) {
return [];
}
const size = await accessor.size();
if (!size) {
return [];
}
return accessor.getRange(0, size);
}
async function readStrokePath(
element: Element,
pageSize: Size,
): Promise<PointLike[]> {
const strokePoints = await readAllAccessorItems<Point>(element.stroke?.points);
return strokePoints.map(point =>
normalizePoint(PointUtils.emrPoint2Android(point, pageSize)),
);
}
async function readSamplePoints(
element: Element,
pageSize: Size,
): Promise<PointLike[]> {
const contours = await readAllAccessorItems<Point[]>(element.contoursSrc);
const contourPoints = contours.flat().map(normalizePoint);
if (contourPoints.length >= 8) {
return contourPoints;
}
return readStrokePath(element, pageSize);
}
function minEndpointDistance(left: StrokeInfo, right: StrokeInfo): number {
const leftEndpoints = [
left.strokePath[0],
left.strokePath[left.strokePath.length - 1],
].filter(Boolean) as PointLike[];
const rightEndpoints = [
right.strokePath[0],
right.strokePath[right.strokePath.length - 1],
].filter(Boolean) as PointLike[];
let best = Number.POSITIVE_INFINITY;
for (const start of leftEndpoints) {
for (const end of rightEndpoints) {
best = Math.min(best, distance(start, end));
}
}
return best;
}
function shouldClusterTogether(left: StrokeInfo, right: StrokeInfo): boolean {
if (left.layerNum !== right.layerNum) {
return false;
}
const gap = boundsGap(left.bounds, right.bounds);
const endpointGap = minEndpointDistance(left, right);
const diagonal = Math.min(left.bounds.diagonal, right.bounds.diagonal);
const closeByBounds = gap <= Math.max(18, diagonal * 0.08);
const closeByEndpoints = endpointGap <= Math.max(28, diagonal * 0.22);
const overlappingWithPadding =
gap <= Math.max(24, diagonal * 0.14) &&
endpointGap <= Math.max(42, diagonal * 0.3);
return (closeByBounds && closeByEndpoints) || overlappingWithPadding;
}
function clusterStrokes(strokes: StrokeInfo[]): StrokeCluster[] {
const remaining = new Set(strokes.map((_, index) => index));
const clusters: StrokeCluster[] = [];
while (remaining.size) {
const seed = remaining.values().next().value as number;
remaining.delete(seed);
const queue = [seed];
const clusterIndices = [seed];
while (queue.length) {
const current = queue.shift() as number;
const currentStroke = strokes[current];
for (const candidate of Array.from(remaining)) {
if (!shouldClusterTogether(currentStroke, strokes[candidate])) {
continue;
}
remaining.delete(candidate);
queue.push(candidate);
clusterIndices.push(candidate);
}
}
const clusterStrokesList = clusterIndices
.map(index => strokes[index])
.sort((left, right) => left.pageIndex - right.pageIndex);
clusters.push({
strokes: clusterStrokesList,
insertionIndex: clusterStrokesList[0]?.pageIndex ?? 0,
layerNum: clusterStrokesList[0]?.layerNum ?? 0,
});
}
return clusters.sort((left, right) => left.insertionIndex - right.insertionIndex);
}
function deriveClusterStyle(cluster: StrokeCluster): GeometryStyle {
const colors = cluster.strokes.map(stroke => stroke.penColor);
const penTypes = cluster.strokes.map(stroke => stroke.penType);
const widths = cluster.strokes.map(stroke => stroke.thickness);
return {
penColor: dominantValue(colors, 0x9d),
penType: dominantValue(penTypes, 10),
penWidth: Math.max(1, Math.round(median(widths, 2))),
};
}
function buildGeometry(
geometryDescriptor: GeometryDescriptor,
style: GeometryStyle,
): Geometry {
const geometry = new Geometry();
geometry.penColor = style.penColor;
geometry.penType = style.penType;
geometry.penWidth = style.penWidth;
if (geometryDescriptor.type === 'line') {
geometry.type = Geometry.TYPE_STRAIGHT_LINE;
geometry.points = geometryDescriptor.points;
geometry.ellipseCenterPoint = null;
geometry.ellipseMajorAxisRadius = 0;
geometry.ellipseMinorAxisRadius = 0;
geometry.ellipseAngle = 0;
return geometry;
}
if (geometryDescriptor.type === 'ellipse') {
const isCircle =
Math.abs(geometryDescriptor.majorRadius - geometryDescriptor.minorRadius) <= 1;
geometry.type = isCircle ? Geometry.TYPE_CIRCLE : Geometry.TYPE_ELLIPSE;
geometry.points = [];
geometry.ellipseCenterPoint = geometryDescriptor.center;
geometry.ellipseMajorAxisRadius = geometryDescriptor.majorRadius;
geometry.ellipseMinorAxisRadius = geometryDescriptor.minorRadius;
geometry.ellipseAngle = geometryDescriptor.angle;
return geometry;
}
geometry.type = Geometry.TYPE_POLYGON;
geometry.points = closePolygonPoints(geometryDescriptor.points);
geometry.ellipseCenterPoint = null;
geometry.ellipseMajorAxisRadius = 0;
geometry.ellipseMinorAxisRadius = 0;
geometry.ellipseAngle = 0;
return geometry;
}
function matchClusters(clusters: StrokeCluster[]): ClusterMatch[] {
const matches: ClusterMatch[] = [];
for (const cluster of clusters) {
const match = detectBestShape({
samplePoints: cluster.strokes.flatMap(stroke => stroke.samplePoints),
strokePaths: cluster.strokes.map(stroke => stroke.strokePath),
recognitionNames: cluster.strokes
.map(stroke => stroke.recognitionName)
.filter(Boolean) as string[],
});
if (!match) {
continue;
}
matches.push({
cluster,
geometryDescriptor: match.geometry,
});
}
return matches;
}
async function createGeometryElement(
geometryDescriptor: GeometryDescriptor,
style: GeometryStyle,
page: number,
layer: number,
): Promise<Element> {
const createResponse = asResponse<Element>(
await PluginCommAPI.createElement(Element.TYPE_GEO),
);
const element = throwIfFailed(createResponse, 'Failed to create geometry element');
const geometry = buildGeometry(geometryDescriptor, style);
element.pageNum = page;
element.layerNum = layer;
element.thickness = style.penWidth;
element.geometry = geometry;
return element;
}
function buildFinalPageElements(
pageElements: Element[],
replacements: ClusterReplacement[],
): Element[] {
const insertions = new Map<number, Element[]>();
const removedUuids = new Set<string>();
for (const replacement of replacements) {
for (const uuid of replacement.replacedUuids) {
removedUuids.add(uuid);
}
const existing = insertions.get(replacement.insertionIndex) ?? [];
existing.push(replacement.geometryElement);
insertions.set(replacement.insertionIndex, existing);
}
const finalElements: Element[] = [];
for (let index = 0; index < pageElements.length; index += 1) {
const pending = insertions.get(index);
if (pending?.length) {
finalElements.push(...pending);
insertions.delete(index);
}
const element = pageElements[index];
if (removedUuids.has(element.uuid)) {
continue;
}
finalElements.push(element);
}
const trailing = insertions.get(pageElements.length);
if (trailing?.length) {
finalElements.push(...trailing);
}
return finalElements;
}
async function buildStrokeInfo(
element: Element,
pageIndex: number,
pageSize: Size,
): Promise<StrokeInfo | null> {
if (element.type !== Element.TYPE_STROKE || !element.stroke) {
return null;
}
const strokePath = await readStrokePath(element, pageSize);
const samplePoints = await readSamplePoints(element, pageSize);
if (strokePath.length < 2 || samplePoints.length < 6) {
return null;
}
return {
element,
pageIndex,
layerNum: element.layerNum ?? 0,
bounds: buildBounds(samplePoints),
strokePath,
samplePoints,
recognitionName: element.recognizeResult?.predict_name?.trim() || null,
penColor: element.stroke.penColor ?? 0x9d,
penType: element.stroke.penType ?? 10,
thickness: Math.max(1, Math.round(element.thickness || 2)),
};
}
function isNotePath(filePath: string): boolean {
return /\.note$/i.test(filePath);
}
async function getCurrentLayerId(
filePath: string,
page: number,
): Promise<number | null> {
if (!isNotePath(filePath)) {
return null;
}
const layersResponse = asResponse<LayerInfo[]>(
await PluginFileAPI.getLayers(filePath, page),
);
if (!layersResponse?.success) {
const message = layersResponse?.error?.message ?? 'Failed to get note layers';
if (isLayerUnsupportedError(message)) {
return null;
}
throw new Error(message);
}
const layers = layersResponse.result ?? [];
const currentLayer = layers.find(layer => layer.isCurrentLayer);
return currentLayer?.layerId ?? 0;
}
async function buildFastPathPlan(
filePath: string,
page: number,
lassoElements: Element[],
pageSize: Size,
): Promise<FastPathOutcome> {
const selectedStrokes = lassoElements.filter(
element => element.type === Element.TYPE_STROKE,
);
if (!selectedStrokes.length || selectedStrokes.length !== lassoElements.length) {
return {kind: 'fallback'};
}
const strokeInfos = (
await Promise.all(
selectedStrokes.map((element, index) => buildStrokeInfo(element, index, pageSize)),
)
).filter(Boolean) as StrokeInfo[];
if (strokeInfos.length !== selectedStrokes.length) {
return {kind: 'fallback'};
}
const clusters = clusterStrokes(strokeInfos);
const matches = matchClusters(clusters);
if (!matches.length) {
return {kind: 'no_match'};
}
if (matches.length !== clusters.length) {
return {kind: 'fallback'};
}
const currentLayerId = await getCurrentLayerId(filePath, page);
if (
currentLayerId !== null &&
matches.some(match => match.cluster.layerNum !== currentLayerId)
) {
return {kind: 'fallback'};
}
return {
kind: 'plan',
plan: {
geometries: matches.map(({cluster, geometryDescriptor}) =>
buildGeometry(geometryDescriptor, deriveClusterStyle(cluster)),
),
},
};
}
async function executeFastPath(plan: FastPathPlan): Promise<void> {
const deleteResponse = asResponse<boolean>(await PluginCommAPI.deleteLassoElements());
throwIfFailed(deleteResponse, 'Failed to delete selected strokes');
for (const geometry of plan.geometries) {
const insertResponse = asResponse<boolean>(
await PluginCommAPI.insertGeometry(geometry),
);
throwIfFailed(insertResponse, 'Failed to insert snapped geometry');
}
const clearLassoResponse = asResponse<boolean>(
await PluginCommAPI.setLassoBoxState(2),
);
if (!clearLassoResponse?.success) {
console.warn('Failed to clear lasso box after fast-path snapping');
}
}
async function executeFallbackPageReplace(
filePath: string,
page: number,
lassoElements: Element[],
pageSize: Size,
): Promise<boolean> {
if (isNotePath(filePath)) {
const saveResponse = asResponse<boolean>(await PluginNoteAPI.saveCurrentNote());
if (!saveResponse?.success) {
console.warn('saveCurrentNote failed; continuing with file-level read/write');
}
}
const pageElements = throwIfFailed(
asResponse<Element[]>(await PluginFileAPI.getElements(page, filePath)),
'Failed to get page elements',
);
const selectedStrokeUuids = new Set(
lassoElements
.filter(element => element.type === Element.TYPE_STROKE)
.map(element => element.uuid),
);
const selectedStrokeNums = new Set(
lassoElements
.filter(element => element.type === Element.TYPE_STROKE)
.map(element => element.numInPage),
);
const matchingPageStrokes = pageElements
.map((element, index) => ({element, index}))
.filter(
({element}) =>
element.type === Element.TYPE_STROKE &&
(selectedStrokeUuids.has(element.uuid) ||
selectedStrokeNums.has(element.numInPage)),
);
if (!matchingPageStrokes.length) {
await showStatus('Snap Shape: no matching stroke elements found on the page.', false);
return true;
}
const strokeInfos = (
await Promise.all(
matchingPageStrokes.map(({element, index}) =>
buildStrokeInfo(element, index, pageSize),
),
)
).filter(Boolean) as StrokeInfo[];
if (!strokeInfos.length) {
await showStatus('Snap Shape: no usable stroke data found in the selection.', false);
return true;
}
const clusters = clusterStrokes(strokeInfos);
const matches = matchClusters(clusters);
if (!matches.length) {
await showStatus(
'Snap Shape could not find a clear shape match for this selection.',
false,
);
return true;
}
const replacements: ClusterReplacement[] = [];
for (const {cluster, geometryDescriptor} of matches) {
const geometryElement = await createGeometryElement(
geometryDescriptor,
deriveClusterStyle(cluster),
page,
cluster.layerNum,
);
replacements.push({
insertionIndex: cluster.insertionIndex,
replacedUuids: new Set(cluster.strokes.map(stroke => stroke.element.uuid)),
geometryElement,
});
}
const finalElements = buildFinalPageElements(pageElements, replacements);
const replaceResponse = asResponse<boolean>(
await PluginFileAPI.replaceElements(filePath, page, finalElements),
);
throwIfFailed(replaceResponse, 'Failed to replace page elements');
const clearLassoResponse = asResponse<boolean>(await PluginCommAPI.setLassoBoxState(2));
if (!clearLassoResponse?.success) {
console.warn('Failed to clear lasso box after snapping');
}
const reloadResponse = asResponse<boolean>(await PluginCommAPI.reloadFile());
if (!reloadResponse?.success) {
console.warn('reloadFile failed after shape snap');
}
return true;
}
export async function snapCurrentSelection(): Promise<void> {
if (isSnapping) {
return;
}
isSnapping = true;
try {
await ensurePermissions([FILE_READ_PERMISSION, FILE_WRITE_PERMISSION]);
const filePath = throwIfFailed(
asResponse<string>(await PluginCommAPI.getCurrentFilePath()),
'Failed to get current file path',
);
const page = throwIfFailed(
asResponse<number>(await PluginCommAPI.getCurrentPageNum()),
'Failed to get current page number',
);
const lassoElements = throwIfFailed(
asResponse<Element[]>(await PluginCommAPI.getLassoElements()),
'Failed to get lasso elements',
);
const pageSize = throwIfFailed(
asResponse<Size>(await PluginFileAPI.getPageSize(filePath, page)),
'Failed to get page size',
);
const fastPathOutcome = await buildFastPathPlan(
filePath,
page,
lassoElements,
pageSize,
);
if (fastPathOutcome.kind === 'plan') {
await executeFastPath(fastPathOutcome.plan);
return;
}
if (fastPathOutcome.kind === 'no_match') {
await showStatus(
'Snap Shape could not find a clear shape match for this selection.',
false,
);
return;
}
await executeFallbackPageReplace(filePath, page, lassoElements, pageSize);
} catch (error) {
const message = describeError(error);
console.error('Snap Shape failed', message, error);
await showStatus(`Snap Shape failed:\n${message}`, false);
} finally {
isSnapping = false;
}
}