@papyrus-sdk/engine-native 0.2.22-beta.0 → 0.2.22-beta.1

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.
@@ -1,6 +1,7 @@
1
1
  #import "PapyrusPdfDocumentView.h"
2
2
 
3
3
  #import <QuartzCore/QuartzCore.h>
4
+ #import <PencilKit/PencilKit.h>
4
5
  #import <dispatch/dispatch.h>
5
6
  #import <math.h>
6
7
 
@@ -39,8 +40,229 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
39
40
  return @{@"x" : @(x), @"y" : @(y), @"width" : @(width), @"height" : @(height)};
40
41
  }
41
42
 
42
- @interface PapyrusPdfDocumentView ()
43
+ static CGRect PapyrusPdfRectFromNormalizedRect(NSDictionary *normalizedRect, CGRect pageBounds) {
44
+ if (![normalizedRect isKindOfClass:NSDictionary.class] ||
45
+ CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) {
46
+ return CGRectNull;
47
+ }
48
+
49
+ id xValue = normalizedRect[@"x"];
50
+ id yValue = normalizedRect[@"y"];
51
+ id widthValue = normalizedRect[@"width"];
52
+ id heightValue = normalizedRect[@"height"];
53
+ if (![xValue respondsToSelector:@selector(doubleValue)] ||
54
+ ![yValue respondsToSelector:@selector(doubleValue)] ||
55
+ ![widthValue respondsToSelector:@selector(doubleValue)] ||
56
+ ![heightValue respondsToSelector:@selector(doubleValue)]) {
57
+ return CGRectNull;
58
+ }
59
+
60
+ CGFloat x = [xValue doubleValue];
61
+ CGFloat y = [yValue doubleValue];
62
+ CGFloat width = [widthValue doubleValue];
63
+ CGFloat height = [heightValue doubleValue];
64
+ if (!isfinite(x) || !isfinite(y) || !isfinite(width) || !isfinite(height) ||
65
+ width <= 0 || height <= 0) {
66
+ return CGRectNull;
67
+ }
68
+
69
+ CGFloat normalizedX = MIN(1.0, MAX(0.0, x));
70
+ CGFloat normalizedY = MIN(1.0, MAX(0.0, y));
71
+ CGFloat normalizedRight = MIN(1.0, MAX(normalizedX, x + width));
72
+ CGFloat normalizedBottom = MIN(1.0, MAX(normalizedY, y + height));
73
+ CGFloat normalizedWidth = normalizedRight - normalizedX;
74
+ CGFloat normalizedHeight = normalizedBottom - normalizedY;
75
+ if (normalizedWidth <= 0 || normalizedHeight <= 0) return CGRectNull;
76
+
77
+ return CGRectMake(
78
+ CGRectGetMinX(pageBounds) + normalizedX * CGRectGetWidth(pageBounds),
79
+ CGRectGetMinY(pageBounds) +
80
+ (1.0 - normalizedY - normalizedHeight) * CGRectGetHeight(pageBounds),
81
+ normalizedWidth * CGRectGetWidth(pageBounds),
82
+ normalizedHeight * CGRectGetHeight(pageBounds));
83
+ }
84
+
85
+ static UIColor *PapyrusAnnotationColor(NSString *hexColor, CGFloat opacity) {
86
+ NSString *source = [hexColor isKindOfClass:NSString.class] ? hexColor : @"#fbbf24";
87
+ NSString *hex = [[source stringByTrimmingCharactersInSet:
88
+ NSCharacterSet.whitespaceAndNewlineCharacterSet] uppercaseString];
89
+ if ([hex hasPrefix:@"#"]) hex = [hex substringFromIndex:1];
90
+ if (hex.length == 3) {
91
+ NSMutableString *expanded = [NSMutableString string];
92
+ for (NSUInteger index = 0; index < hex.length; index += 1) {
93
+ unichar digit = [hex characterAtIndex:index];
94
+ [expanded appendFormat:@"%C%C", digit, digit];
95
+ }
96
+ hex = expanded;
97
+ }
98
+
99
+ unsigned int rgb = 0;
100
+ NSScanner *scanner = [NSScanner scannerWithString:hex];
101
+ UIColor *baseColor = [scanner scanHexInt:&rgb] && scanner.isAtEnd && hex.length == 6
102
+ ? [UIColor colorWithRed:((rgb >> 16) & 0xff) / 255.0
103
+ green:((rgb >> 8) & 0xff) / 255.0
104
+ blue:(rgb & 0xff) / 255.0
105
+ alpha:1.0]
106
+ : [UIColor colorWithRed:1.0 green:0.75 blue:0.1 alpha:1.0];
107
+ return [baseColor colorWithAlphaComponent:MIN(1.0, MAX(0.0, opacity))];
108
+ }
109
+
110
+ static NSMapTable<UIWindow *, PKToolPicker *> *PapyrusToolPickersByWindow(void) {
111
+ static NSMapTable<UIWindow *, PKToolPicker *> *pickers;
112
+ static dispatch_once_t onceToken;
113
+ dispatch_once(&onceToken, ^{
114
+ pickers = [NSMapTable weakToStrongObjectsMapTable];
115
+ });
116
+ return pickers;
117
+ }
118
+
119
+ static NSString *PapyrusHexColorFromUIColor(UIColor *color, CGFloat *opacity) {
120
+ CGFloat red = 0;
121
+ CGFloat green = 0;
122
+ CGFloat blue = 0;
123
+ CGFloat alpha = 1;
124
+ if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
125
+ CGColorRef cgColor = color.CGColor;
126
+ const CGFloat *components = CGColorGetComponents(cgColor);
127
+ size_t componentCount = CGColorGetNumberOfComponents(cgColor);
128
+ CGColorSpaceModel model = CGColorSpaceGetModel(CGColorGetColorSpace(cgColor));
129
+ if (components && model == kCGColorSpaceModelMonochrome && componentCount >= 2) {
130
+ red = green = blue = components[0];
131
+ alpha = components[1];
132
+ } else if (components && componentCount >= 4) {
133
+ red = components[0];
134
+ green = components[1];
135
+ blue = components[2];
136
+ alpha = components[3];
137
+ }
138
+ }
139
+ if (opacity) *opacity = MIN(1.0, MAX(0.0, alpha));
140
+ return [NSString stringWithFormat:@"#%02X%02X%02X",
141
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, red)) * 255.0),
142
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, green)) * 255.0),
143
+ (unsigned int)lrint(MIN(1.0, MAX(0.0, blue)) * 255.0)];
144
+ }
145
+
146
+ @interface PapyrusPdfPageInkCanvasView : PKCanvasView
147
+ @property (nonatomic, assign) NSInteger papyrusPageIndex;
148
+ @property (nonatomic, assign) BOOL applyingStoreDrawing;
149
+ @property (nonatomic, assign) BOOL hasUncommittedChanges;
150
+ @property (nonatomic, assign) NSUInteger pendingCommitGeneration;
151
+ @property (nonatomic, copy) NSString *appliedStoreSignature;
152
+ @property (nonatomic, weak) PKToolPicker *observedToolPicker;
153
+ @end
154
+
155
+ @implementation PapyrusPdfPageInkCanvasView
156
+ @end
157
+
158
+ @interface PapyrusSquigglyPdfAnnotation : PDFAnnotation
159
+ @end
160
+
161
+ @implementation PapyrusSquigglyPdfAnnotation
162
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
163
+ (void)box;
164
+ CGRect bounds = self.bounds;
165
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
166
+
167
+ CGFloat height = CGRectGetHeight(bounds);
168
+ CGFloat wavelength = MAX(2.0, height * 0.7);
169
+ CGFloat amplitude = MAX(0.6, height * 0.16);
170
+ CGFloat centerY = CGRectGetMidY(bounds);
171
+ CGContextSaveGState(context);
172
+ CGContextSetStrokeColorWithColor(context, self.color.CGColor);
173
+ CGContextSetLineWidth(context, MAX(0.65, height * 0.08));
174
+ CGMutablePathRef path = CGPathCreateMutable();
175
+ CGFloat minX = CGRectGetMinX(bounds);
176
+ CGFloat maxX = CGRectGetMaxX(bounds);
177
+ BOOL first = YES;
178
+ for (CGFloat x = minX; x <= maxX; x += 1.5) {
179
+ CGFloat y = centerY + sin((x - minX) * M_PI * 2.0 / wavelength) * amplitude;
180
+ if (first) {
181
+ CGPathMoveToPoint(path, NULL, x, y);
182
+ first = NO;
183
+ } else {
184
+ CGPathAddLineToPoint(path, NULL, x, y);
185
+ }
186
+ }
187
+ CGPathAddLineToPoint(path, NULL, maxX, centerY);
188
+ CGContextAddPath(context, path);
189
+ CGContextStrokePath(context);
190
+ CGPathRelease(path);
191
+ CGContextRestoreGState(context);
192
+ }
193
+ @end
194
+
195
+ @interface PapyrusCommentPdfAnnotation : PDFAnnotation
196
+ @end
197
+
198
+ @implementation PapyrusCommentPdfAnnotation
199
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
200
+ (void)box;
201
+ CGRect bounds = self.bounds;
202
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
203
+
204
+ CGFloat inset = MAX(1.0, CGRectGetHeight(bounds) * 0.08);
205
+ CGRect noteRect = CGRectInset(bounds, inset, inset);
206
+ CGFloat fold = MIN(CGRectGetWidth(noteRect), CGRectGetHeight(noteRect)) * 0.24;
207
+ CGFloat radius = MIN(CGRectGetHeight(noteRect) * 0.12, 4.0);
208
+ CGPathRef notePath = CGPathCreateWithRoundedRect(noteRect, radius, radius, NULL);
209
+ CGContextSaveGState(context);
210
+ CGContextAddPath(context, notePath);
211
+ CGContextSetFillColorWithColor(context, self.color.CGColor);
212
+ CGContextFillPath(context);
213
+ CGPathRelease(notePath);
214
+
215
+ CGContextSetStrokeColorWithColor(context, UIColor.whiteColor.CGColor);
216
+ CGContextSetLineWidth(context, MAX(0.7, CGRectGetHeight(noteRect) * 0.045));
217
+ CGFloat left = CGRectGetMinX(noteRect) + inset;
218
+ CGFloat right = CGRectGetMaxX(noteRect) - fold - inset;
219
+ CGFloat firstY = CGRectGetMinY(noteRect) + CGRectGetHeight(noteRect) * 0.38;
220
+ CGFloat secondY = CGRectGetMinY(noteRect) + CGRectGetHeight(noteRect) * 0.62;
221
+ CGContextMoveToPoint(context, left, firstY);
222
+ CGContextAddLineToPoint(context, right, firstY);
223
+ CGContextMoveToPoint(context, left, secondY);
224
+ CGContextAddLineToPoint(context, right, secondY);
225
+ CGContextStrokePath(context);
226
+ CGContextRestoreGState(context);
227
+ }
228
+ @end
229
+
230
+ @interface PapyrusSelectionOutlinePdfAnnotation : PDFAnnotation
231
+ @end
232
+
233
+ @implementation PapyrusSelectionOutlinePdfAnnotation
234
+ - (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
235
+ (void)box;
236
+ CGRect bounds = self.bounds;
237
+ if (CGRectIsNull(bounds) || CGRectIsEmpty(bounds) || !context) return;
238
+
239
+ CGFloat lineWidth = 1.5;
240
+ CGRect outline = CGRectInset(bounds, lineWidth / 2.0, lineWidth / 2.0);
241
+ if (CGRectIsNull(outline) || CGRectIsEmpty(outline)) return;
242
+ CGContextSaveGState(context);
243
+ CGContextSetStrokeColorWithColor(context, self.color.CGColor);
244
+ CGContextSetLineWidth(context, lineWidth);
245
+ CGContextStrokeRect(context, outline);
246
+ CGContextRestoreGState(context);
247
+ }
248
+ @end
249
+
250
+ @interface PapyrusPdfDocumentView () <UIEditMenuInteractionDelegate,
251
+ PDFPageOverlayViewProvider,
252
+ PKCanvasViewDelegate,
253
+ PKToolPickerObserver>
43
254
  @property (nonatomic, strong) PDFView *pdfView;
255
+ @property (nonatomic, strong) UIEditMenuInteraction *editMenuInteraction;
256
+ @property (nonatomic, copy) NSArray<PDFSelection *> *searchSelections;
257
+ @property (nonatomic, copy) NSDictionary<NSNumber *, PDFSelection *> *searchSelectionsByResultIndex;
258
+ @property (nonatomic, strong) NSMutableDictionary<NSString *, NSArray<PDFAnnotation *> *> *papyrusAnnotationsById;
259
+ @property (nonatomic, strong) NSMutableDictionary<NSString *, NSString *> *papyrusAnnotationSignaturesById;
260
+ @property (nonatomic, strong) NSMapTable<PDFAnnotation *, NSString *> *papyrusAnnotationIdsByObject;
261
+ @property (nonatomic, copy) NSArray<PDFAnnotation *> *selectedAnnotationAdornmentAnnotations;
262
+ @property (nonatomic, copy, nullable) NSString *contextualAnnotationMenuId;
263
+ @property (nonatomic, copy, nullable) NSString *contextualAnnotationMenuConfigurationId;
264
+ @property (nonatomic, assign) CGPoint contextualAnnotationMenuSourcePoint;
265
+ @property (nonatomic, assign) NSUInteger searchNavigationGeneration;
44
266
  @property (nonatomic, weak) UIScrollView *observedScrollView;
45
267
  @property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
46
268
  @property (nonatomic, strong) UITapGestureRecognizer *doubleTapRecognizer;
@@ -56,10 +278,55 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
56
278
  @property (nonatomic, copy) NSString *lastSelectionSignature;
57
279
  @property (nonatomic, assign) NSInteger lastSelectionPageIndex;
58
280
  @property (nonatomic, assign) BOOL lastSelectionWasActive;
281
+ @property (nonatomic, assign) NSUInteger selectionMenuGeneration;
282
+ @property (nonatomic, strong) NSMutableDictionary<NSNumber *, PapyrusPdfPageInkCanvasView *> *inkCanvasesByPageIndex;
283
+ @property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSString *> *inkAnnotationSignaturesByPageIndex;
284
+ @property (nonatomic, weak) PapyrusPdfPageInkCanvasView *activeInkCanvas;
285
+ @property (nonatomic, strong) PKToolPicker *activeInkToolPicker;
286
+ @property (nonatomic, copy) NSString *lastAppliedInkToolConfiguration;
287
+ - (void)scheduleSelectionEditMenuForSignature:(NSString *)signature;
288
+ - (void)attemptSelectionEditMenuForSignature:(NSString *)signature generation:(NSUInteger)generation;
289
+ - (BOOL)hasActiveGestureInView:(UIView *)view;
290
+ - (void)emitDefineSelection;
291
+ - (void)rebuildSearchHighlights;
292
+ - (void)updateSearchHighlightColorsFromResultIndex:(NSInteger)previousSearchIndex;
293
+ - (void)scheduleNavigationToSearchResultAtIndex:(NSInteger)activeSearchIndex;
294
+ - (UIColor *)searchHighlightColorForActive:(BOOL)isActive;
295
+ - (void)reconcilePapyrusAnnotations;
296
+ - (void)updateSelectedAnnotationAdornment;
297
+ - (void)removeSelectedAnnotationAdornment;
298
+ - (void)dismissAnnotationMenuForDocumentChange;
299
+ - (void)removePapyrusAnnotationWithId:(NSString *)annotationId;
300
+ - (void)clearPapyrusAnnotationsForDocument:(nullable PDFDocument *)document;
301
+ - (NSArray<PDFAnnotation *> *)createPdfAnnotationsForPapyrusAnnotation:(NSDictionary *)annotation;
302
+ - (NSString *)annotationSignature:(NSDictionary *)annotation;
303
+ - (void)emitAnnotationFromCurrentSelectionWithType:(NSString *)type;
304
+ - (void)presentAnnotationEditMenuForId:(NSString *)annotationId atPoint:(CGPoint)point;
305
+ - (void)emitAnnotationDeleteWithId:(NSString *)annotationId;
306
+ - (void)emitCommentAtPage:(PDFPage *)page pageIndex:(NSInteger)pageIndex normalizedPoint:(CGPoint)point;
307
+ - (void)reconcileInkOverlays;
308
+ - (void)applyStoreInkAnnotationsToCanvas:(PapyrusPdfPageInkCanvasView *)canvas force:(BOOL)force;
309
+ - (void)updateInkCanvasInputAndPicker;
310
+ - (void)activateInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
311
+ - (void)deactivateInkCanvas;
312
+ - (void)releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
313
+ - (void)commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
314
+ - (NSString *)inkAnnotationSignatureForPage:(NSInteger)pageIndex;
315
+ - (NSArray<NSDictionary *> *)inkDrawingPayloadForCanvas:(PapyrusPdfPageInkCanvasView *)canvas;
316
+ - (void)resetInkOverlaysForDocumentChange;
59
317
  @end
60
318
 
61
319
  @implementation PapyrusPdfDocumentView
62
320
 
321
+ - (void)dealloc {
322
+ [self stopObservingScrollView];
323
+ [self resetInkOverlaysForDocumentChange];
324
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
325
+ self.tapRecognizer.delegate = nil;
326
+ self.doubleTapRecognizer.delegate = nil;
327
+ [self clearPapyrusAnnotationsForDocument:self.pdfView.document];
328
+ }
329
+
63
330
  - (instancetype)initWithFrame:(CGRect)frame {
64
331
  self = [super initWithFrame:frame];
65
332
  if (!self) return nil;
@@ -68,10 +335,35 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
68
335
  _viewMode = @"continuous";
69
336
  _zoom = 1.0;
70
337
  _currentPage = 1;
338
+ _searchResults = @[];
339
+ _activeSearchIndex = -1;
340
+ _searchSelections = @[];
341
+ _searchSelectionsByResultIndex = @{};
342
+ _annotations = @[];
343
+ _activeTool = @"select";
344
+ _activeDrawToolPreset = @"ink";
345
+ _inkStrokeWidth = 0.006;
346
+ _annotationColor = @"#fbbf24";
347
+ _annotationSelectionColor = @"#2563eb";
348
+ _annotationOpacity = 1.0;
349
+ _papyrusAnnotationsById = [NSMutableDictionary dictionary];
350
+ _papyrusAnnotationSignaturesById = [NSMutableDictionary dictionary];
351
+ _papyrusAnnotationIdsByObject = [NSMapTable strongToStrongObjectsMapTable];
352
+ _selectedAnnotationAdornmentAnnotations = @[];
353
+ _inkCanvasesByPageIndex = [NSMutableDictionary dictionary];
354
+ _inkAnnotationSignaturesByPageIndex = [NSMutableDictionary dictionary];
355
+ _searchNavigationGeneration = 0;
71
356
  _lastEmittedPage = NSNotFound;
72
357
  _lastSelectionPageIndex = NSNotFound;
73
358
  _lastEmittedZoom = NAN;
74
359
  _lastLayoutSize = CGSizeZero;
360
+ _defineLabel = NSLocalizedString(@"Define", nil);
361
+ _annotateLabel = NSLocalizedString(@"Annotate", nil);
362
+ _annotationHighlightLabel = NSLocalizedString(@"Highlight", nil);
363
+ _annotationUnderlineLabel = NSLocalizedString(@"Underline", nil);
364
+ _annotationStrikeoutLabel = NSLocalizedString(@"Strikeout", nil);
365
+ _annotationSquigglyLabel = NSLocalizedString(@"Squiggly", nil);
366
+ _annotationNoteLabel = NSLocalizedString(@"Note", nil);
75
367
  self.clipsToBounds = YES;
76
368
  self.backgroundColor = UIColor.whiteColor;
77
369
 
@@ -86,6 +378,12 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
86
378
  _pdfView.clipsToBounds = YES;
87
379
  [self addSubview:_pdfView];
88
380
 
381
+ if (@available(iOS 16.0, *)) {
382
+ _pdfView.pageOverlayViewProvider = self;
383
+ _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
384
+ [_pdfView addInteraction:_editMenuInteraction];
385
+ }
386
+
89
387
  _tapRecognizer = [[UITapGestureRecognizer alloc]
90
388
  initWithTarget:self
91
389
  action:@selector(handleDocumentTap:)];
@@ -129,13 +427,6 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
129
427
  return self;
130
428
  }
131
429
 
132
- - (void)dealloc {
133
- [self stopObservingScrollView];
134
- [[NSNotificationCenter defaultCenter] removeObserver:self];
135
- self.tapRecognizer.delegate = nil;
136
- self.doubleTapRecognizer.delegate = nil;
137
- }
138
-
139
430
  - (void)setSelectionActive:(BOOL)selectionActive {
140
431
  _selectionActive = selectionActive;
141
432
  if (!selectionActive) {
@@ -170,6 +461,39 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
170
461
  self.pdfView.backgroundColor = UIColor.whiteColor;
171
462
  }
172
463
 
464
+ - (void)setActiveTool:(NSString *)activeTool {
465
+ _activeTool = activeTool.length > 0 ? [activeTool copy] : @"select";
466
+ [self updateInkCanvasInputAndPicker];
467
+ }
468
+
469
+ - (void)setActiveDrawToolPreset:(NSString *)activeDrawToolPreset {
470
+ NSSet<NSString *> *presets = [NSSet setWithArray:@[@"ink", @"highlight", @"underline"]];
471
+ _activeDrawToolPreset = [presets containsObject:activeDrawToolPreset]
472
+ ? [activeDrawToolPreset copy] : @"ink";
473
+ self.lastAppliedInkToolConfiguration = nil;
474
+ [self updateInkCanvasInputAndPicker];
475
+ }
476
+
477
+ - (void)setInkStrokeWidth:(CGFloat)inkStrokeWidth {
478
+ if (!isfinite(inkStrokeWidth)) return;
479
+ _inkStrokeWidth = MIN(0.02, MAX(0.0025, inkStrokeWidth));
480
+ self.lastAppliedInkToolConfiguration = nil;
481
+ [self updateInkCanvasInputAndPicker];
482
+ }
483
+
484
+ - (void)setAnnotationColor:(NSString *)annotationColor {
485
+ _annotationColor = annotationColor.length > 0 ? [annotationColor copy] : @"#fbbf24";
486
+ self.lastAppliedInkToolConfiguration = nil;
487
+ [self updateInkCanvasInputAndPicker];
488
+ }
489
+
490
+ - (void)setAnnotationOpacity:(CGFloat)annotationOpacity {
491
+ if (!isfinite(annotationOpacity)) return;
492
+ _annotationOpacity = MIN(1.0, MAX(0.1, annotationOpacity));
493
+ self.lastAppliedInkToolConfiguration = nil;
494
+ [self updateInkCanvasInputAndPicker];
495
+ }
496
+
173
497
  - (void)setViewMode:(NSString *)viewMode {
174
498
  NSString *normalized = [viewMode isEqualToString:@"single"] ? @"single" : @"continuous";
175
499
  if ([_viewMode isEqualToString:normalized]) return;
@@ -230,17 +554,25 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
230
554
  : nil;
231
555
  if (self.pdfView.document == document) {
232
556
  [self applyCurrentPage];
557
+ [self rebuildSearchHighlights];
558
+ [self reconcilePapyrusAnnotations];
559
+ [self reconcileInkOverlays];
233
560
  return;
234
561
  }
235
562
 
563
+ [self dismissAnnotationMenuForDocumentChange];
236
564
  CGFloat desiredZoom = [self clampedZoom:self.zoom];
237
565
  BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
238
566
  self.suppressScaleSynchronization = YES;
239
567
  self.lastVisiblePagesSignature = nil;
240
568
  self.lastEmittedPage = NSNotFound;
569
+ [self resetInkOverlaysForDocumentChange];
570
+ [self clearPapyrusAnnotationsForDocument:self.pdfView.document];
241
571
  [self clearCurrentSelection];
242
572
  self.pdfView.document = document;
243
573
  if (!document) {
574
+ [self rebuildSearchHighlights];
575
+ [self reconcilePapyrusAnnotations];
244
576
  self.lastEmittedZoom = NAN;
245
577
  _zoom = desiredZoom;
246
578
  self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
@@ -259,9 +591,873 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
259
591
  [self applyNormalizedZoom];
260
592
  [self refreshScrollViewObservation];
261
593
  [self emitVisiblePagesIfNeeded];
594
+ [self rebuildSearchHighlights];
595
+ [self reconcilePapyrusAnnotations];
262
596
  self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
263
597
  }
264
598
 
599
+ - (void)setSearchResults:(NSArray<NSDictionary *> *)searchResults {
600
+ _searchResults = [searchResults copy] ?: @[];
601
+ [self rebuildSearchHighlights];
602
+ }
603
+
604
+ - (void)setActiveSearchIndex:(NSInteger)activeSearchIndex {
605
+ NSInteger previousSearchIndex = _activeSearchIndex;
606
+ _activeSearchIndex = activeSearchIndex;
607
+ [self updateSearchHighlightColorsFromResultIndex:previousSearchIndex];
608
+ [self scheduleNavigationToSearchResultAtIndex:activeSearchIndex];
609
+ }
610
+
611
+ - (void)setAnnotations:(NSArray<NSDictionary *> *)annotations {
612
+ _annotations = [annotations copy] ?: @[];
613
+ [self reconcilePapyrusAnnotations];
614
+ [self reconcileInkOverlays];
615
+ }
616
+
617
+ - (UIView *)pdfView:(PDFView *)pdfView overlayViewForPage:(PDFPage *)page {
618
+ if (@available(iOS 16.0, *)) {
619
+ PDFDocument *document = pdfView.document;
620
+ NSInteger pageIndex = document ? (NSInteger)[document indexForPage:page] : NSNotFound;
621
+ if (pageIndex < 0 || pageIndex == NSNotFound) return nil;
622
+
623
+ NSNumber *key = @(pageIndex);
624
+ PapyrusPdfPageInkCanvasView *canvas = self.inkCanvasesByPageIndex[key];
625
+ if (!canvas) {
626
+ canvas = [[PapyrusPdfPageInkCanvasView alloc] initWithFrame:CGRectZero];
627
+ canvas.papyrusPageIndex = pageIndex;
628
+ canvas.backgroundColor = UIColor.clearColor;
629
+ canvas.opaque = NO;
630
+ canvas.clipsToBounds = YES;
631
+ canvas.drawingPolicy = PKCanvasViewDrawingPolicyAnyInput;
632
+ canvas.scrollEnabled = NO;
633
+ canvas.delegate = self;
634
+ canvas.userInteractionEnabled = NO;
635
+ self.inkCanvasesByPageIndex[key] = canvas;
636
+ [self applyStoreInkAnnotationsToCanvas:canvas force:YES];
637
+ }
638
+ return canvas;
639
+ }
640
+ return nil;
641
+ }
642
+
643
+ - (void)pdfView:(PDFView *)pdfView
644
+ willDisplayOverlayView:(UIView *)overlayView
645
+ forPage:(PDFPage *)page {
646
+ (void)pdfView;
647
+ (void)page;
648
+ if (![overlayView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) return;
649
+ PapyrusPdfPageInkCanvasView *canvas = (PapyrusPdfPageInkCanvasView *)overlayView;
650
+ self.inkCanvasesByPageIndex[@(canvas.papyrusPageIndex)] = canvas;
651
+ [self applyStoreInkAnnotationsToCanvas:canvas force:NO];
652
+ [self updateInkCanvasInputAndPicker];
653
+ }
654
+
655
+ - (void)pdfView:(PDFView *)pdfView
656
+ willEndDisplayingOverlayView:(UIView *)overlayView
657
+ forPage:(PDFPage *)page {
658
+ (void)pdfView;
659
+ (void)page;
660
+ if ([overlayView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) {
661
+ [self releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)overlayView];
662
+ }
663
+ }
664
+
665
+ - (NSString *)inkAnnotationSignatureForPage:(NSInteger)pageIndex {
666
+ NSMutableArray<NSDictionary *> *pageAnnotations = [NSMutableArray array];
667
+ for (id value in self.annotations) {
668
+ if (![value isKindOfClass:NSDictionary.class]) continue;
669
+ NSDictionary *annotation = (NSDictionary *)value;
670
+ if (![annotation[@"type"] isEqual:@"ink"] ||
671
+ [annotation[@"pageIndex"] integerValue] != pageIndex) {
672
+ continue;
673
+ }
674
+ [pageAnnotations addObject:@{
675
+ @"path" : annotation[@"path"] ?: @[],
676
+ @"color" : annotation[@"color"] ?: @"#111827",
677
+ @"opacity" : annotation[@"opacity"] ?: @1,
678
+ @"strokeWidth" : annotation[@"strokeWidth"] ?: @0.006
679
+ }];
680
+ }
681
+
682
+ NSError *error = nil;
683
+ NSData *data = [NSJSONSerialization dataWithJSONObject:pageAnnotations
684
+ options:NSJSONWritingSortedKeys
685
+ error:&error];
686
+ if (!data || error) return pageAnnotations.description ?: @"[]";
687
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]";
688
+ }
689
+
690
+ - (void)applyStoreInkAnnotationsToCanvas:(PapyrusPdfPageInkCanvasView *)canvas
691
+ force:(BOOL)force {
692
+ if (!canvas || !self.pdfView.document) return;
693
+ NSInteger pageIndex = canvas.papyrusPageIndex;
694
+ NSString *signature = [self inkAnnotationSignatureForPage:pageIndex];
695
+ if (!force && [canvas.appliedStoreSignature isEqualToString:signature]) return;
696
+
697
+ CGFloat canvasWidth = CGRectGetWidth(canvas.bounds);
698
+ CGFloat canvasHeight = CGRectGetHeight(canvas.bounds);
699
+ PDFPage *page = [self.pdfView.document pageAtIndex:(NSUInteger)pageIndex];
700
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
701
+ if (canvasWidth <= 0) canvasWidth = CGRectGetWidth(pageBounds);
702
+ if (canvasHeight <= 0) canvasHeight = CGRectGetHeight(pageBounds);
703
+ if (canvasWidth <= 0 || canvasHeight <= 0) return;
704
+
705
+ NSMutableArray<PKStroke *> *strokes = [NSMutableArray array];
706
+ for (id value in self.annotations) {
707
+ if (![value isKindOfClass:NSDictionary.class]) continue;
708
+ NSDictionary *annotation = (NSDictionary *)value;
709
+ if (![annotation[@"type"] isEqual:@"ink"] ||
710
+ [annotation[@"pageIndex"] integerValue] != pageIndex) {
711
+ continue;
712
+ }
713
+ NSArray *pathValues = [annotation[@"path"] isKindOfClass:NSArray.class]
714
+ ? annotation[@"path"] : @[];
715
+ if (pathValues.count == 0) continue;
716
+
717
+ CGFloat opacity = [annotation[@"opacity"] respondsToSelector:@selector(doubleValue)]
718
+ ? [annotation[@"opacity"] doubleValue] : 1.0;
719
+ opacity = isfinite(opacity) ? MIN(1.0, MAX(0.0, opacity)) : 1.0;
720
+ NSString *hexColor = [annotation[@"color"] isKindOfClass:NSString.class]
721
+ ? annotation[@"color"] : @"#111827";
722
+ UIColor *color = PapyrusAnnotationColor(hexColor, opacity);
723
+ PKInkType inkType = opacity <= 0.35 ? PKInkTypeMarker : PKInkTypePen;
724
+ PKInk *ink = [[PKInk alloc] initWithInkType:inkType color:color];
725
+ CGFloat normalizedWidth = [annotation[@"strokeWidth"] respondsToSelector:@selector(doubleValue)]
726
+ ? [annotation[@"strokeWidth"] doubleValue] : 0.006;
727
+ if (!isfinite(normalizedWidth) || normalizedWidth <= 0) normalizedWidth = 0.006;
728
+ CGFloat pointWidth = MAX(0.6, normalizedWidth * canvasWidth);
729
+
730
+ NSMutableArray<PKStrokePoint *> *controlPoints = [NSMutableArray array];
731
+ for (id pointValue in pathValues) {
732
+ if (![pointValue isKindOfClass:NSDictionary.class]) continue;
733
+ NSDictionary *point = (NSDictionary *)pointValue;
734
+ CGFloat x = [point[@"x"] respondsToSelector:@selector(doubleValue)]
735
+ ? [point[@"x"] doubleValue] : NAN;
736
+ CGFloat y = [point[@"y"] respondsToSelector:@selector(doubleValue)]
737
+ ? [point[@"y"] doubleValue] : NAN;
738
+ if (!isfinite(x) || !isfinite(y)) continue;
739
+ CGPoint location = CGPointMake(
740
+ MIN(1.0, MAX(0.0, x)) * canvasWidth,
741
+ MIN(1.0, MAX(0.0, y)) * canvasHeight);
742
+ NSTimeInterval timeOffset = (NSTimeInterval)controlPoints.count / 60.0;
743
+ [controlPoints addObject:[[PKStrokePoint alloc]
744
+ initWithLocation:location
745
+ timeOffset:timeOffset
746
+ size:CGSizeMake(pointWidth, pointWidth)
747
+ opacity:1.0
748
+ force:1.0
749
+ azimuth:0.0
750
+ altitude:(CGFloat)M_PI_2]];
751
+ }
752
+ if (controlPoints.count == 0) continue;
753
+ if (controlPoints.count == 1) {
754
+ PKStrokePoint *firstPoint = controlPoints.firstObject;
755
+ [controlPoints addObject:[[PKStrokePoint alloc]
756
+ initWithLocation:firstPoint.location
757
+ timeOffset:firstPoint.timeOffset + (1.0 / 60.0)
758
+ size:firstPoint.size
759
+ opacity:firstPoint.opacity
760
+ force:firstPoint.force
761
+ azimuth:firstPoint.azimuth
762
+ altitude:firstPoint.altitude]];
763
+ }
764
+
765
+ PKStrokePath *strokePath = [[PKStrokePath alloc]
766
+ initWithControlPoints:controlPoints
767
+ creationDate:NSDate.date];
768
+ PKStroke *stroke = [[PKStroke alloc]
769
+ initWithInk:ink
770
+ strokePath:strokePath
771
+ transform:CGAffineTransformIdentity
772
+ mask:nil];
773
+ [strokes addObject:stroke];
774
+ }
775
+
776
+ canvas.applyingStoreDrawing = YES;
777
+ canvas.drawing = [[PKDrawing alloc] initWithStrokes:strokes];
778
+ canvas.applyingStoreDrawing = NO;
779
+ canvas.hasUncommittedChanges = NO;
780
+ canvas.pendingCommitGeneration += 1;
781
+ canvas.appliedStoreSignature = signature;
782
+ self.inkAnnotationSignaturesByPageIndex[@(pageIndex)] = signature;
783
+ }
784
+
785
+ - (void)reconcileInkOverlays {
786
+ for (NSNumber *pageKey in self.inkCanvasesByPageIndex.allKeys.copy) {
787
+ PapyrusPdfPageInkCanvasView *canvas = self.inkCanvasesByPageIndex[pageKey];
788
+ [self applyStoreInkAnnotationsToCanvas:canvas force:NO];
789
+ }
790
+ }
791
+
792
+ - (void)updateInkCanvasInputAndPicker {
793
+ BOOL drawingActive = [self.activeTool isEqualToString:@"ink"];
794
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
795
+ canvas.userInteractionEnabled = drawingActive;
796
+ }
797
+ if (!drawingActive) {
798
+ if (self.activeInkCanvas.hasUncommittedChanges) {
799
+ [self commitInkDrawingForCanvas:self.activeInkCanvas];
800
+ }
801
+ [self deactivateInkCanvas];
802
+ return;
803
+ }
804
+
805
+ PDFPage *page = self.pdfView.currentPage;
806
+ NSInteger pageIndex = page && self.pdfView.document
807
+ ? (NSInteger)[self.pdfView.document indexForPage:page] : NSNotFound;
808
+ PapyrusPdfPageInkCanvasView *canvas =
809
+ pageIndex == NSNotFound ? nil : self.inkCanvasesByPageIndex[@(pageIndex)];
810
+ if (!canvas) canvas = self.inkCanvasesByPageIndex.allValues.firstObject;
811
+ if (canvas) [self activateInkCanvas:canvas];
812
+ }
813
+
814
+ - (void)activateInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
815
+ if (!canvas || !canvas.window || ![self.activeTool isEqualToString:@"ink"]) return;
816
+ if (self.activeInkCanvas != canvas) [self deactivateInkCanvas];
817
+
818
+ UIWindow *window = canvas.window;
819
+ PKToolPicker *picker = [PapyrusToolPickersByWindow() objectForKey:window];
820
+ if (!picker) {
821
+ picker = [[PKToolPicker alloc] init];
822
+ [PapyrusToolPickersByWindow() setObject:picker forKey:window];
823
+ }
824
+ for (PapyrusPdfPageInkCanvasView *visibleCanvas in self.inkCanvasesByPageIndex.allValues) {
825
+ if (visibleCanvas.observedToolPicker == picker) continue;
826
+ [visibleCanvas.observedToolPicker removeObserver:visibleCanvas];
827
+ [picker addObserver:visibleCanvas];
828
+ visibleCanvas.observedToolPicker = picker;
829
+ }
830
+ if (self.activeInkToolPicker != picker) [picker addObserver:self];
831
+ self.activeInkToolPicker = picker;
832
+ self.activeInkCanvas = canvas;
833
+ canvas.delegate = self;
834
+ canvas.userInteractionEnabled = YES;
835
+
836
+ NSString *configuration = [NSString stringWithFormat:@"%@|%@|%.5f|%.5f",
837
+ self.activeDrawToolPreset ?: @"ink",
838
+ self.annotationColor ?: @"#111827",
839
+ self.annotationOpacity,
840
+ self.inkStrokeWidth];
841
+ if (![self.lastAppliedInkToolConfiguration isEqualToString:configuration]) {
842
+ PDFPage *page = [self.pdfView.document pageAtIndex:(NSUInteger)canvas.papyrusPageIndex];
843
+ CGFloat pageWidth = CGRectGetWidth([page boundsForBox:kPDFDisplayBoxCropBox]);
844
+ CGFloat toolWidth = MAX(0.6, self.inkStrokeWidth * pageWidth);
845
+ PKInkType type = [self.activeDrawToolPreset isEqualToString:@"highlight"]
846
+ ? PKInkTypeMarker : PKInkTypePen;
847
+ picker.selectedTool = [[PKInkingTool alloc]
848
+ initWithInkType:type
849
+ color:PapyrusAnnotationColor(self.annotationColor, self.annotationOpacity)
850
+ width:toolWidth];
851
+ self.lastAppliedInkToolConfiguration = configuration;
852
+ }
853
+
854
+ [canvas becomeFirstResponder];
855
+ if (@available(iOS 16.0, *)) {
856
+ [picker setVisible:YES forFirstResponder:canvas];
857
+ }
858
+ }
859
+
860
+ - (void)deactivateInkCanvas {
861
+ PapyrusPdfPageInkCanvasView *canvas = self.activeInkCanvas;
862
+ PKToolPicker *picker = self.activeInkToolPicker;
863
+ for (PapyrusPdfPageInkCanvasView *visibleCanvas in self.inkCanvasesByPageIndex.allValues) {
864
+ PKToolPicker *observedPicker = visibleCanvas.observedToolPicker;
865
+ if (observedPicker) [observedPicker removeObserver:visibleCanvas];
866
+ visibleCanvas.observedToolPicker = nil;
867
+ }
868
+ if (picker) {
869
+ if (canvas) {
870
+ if (@available(iOS 16.0, *)) {
871
+ [picker setVisible:NO forFirstResponder:canvas];
872
+ }
873
+ [canvas resignFirstResponder];
874
+ }
875
+ [picker removeObserver:self];
876
+ }
877
+ canvas.userInteractionEnabled = NO;
878
+ self.activeInkCanvas = nil;
879
+ self.activeInkToolPicker = nil;
880
+ }
881
+
882
+ - (void)releaseInkCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
883
+ if (!canvas) return;
884
+ if (canvas.hasUncommittedChanges) [self commitInkDrawingForCanvas:canvas];
885
+ if (self.activeInkCanvas == canvas) [self deactivateInkCanvas];
886
+ else if (canvas.observedToolPicker) {
887
+ [canvas.observedToolPicker removeObserver:canvas];
888
+ canvas.observedToolPicker = nil;
889
+ }
890
+ NSNumber *key = @(canvas.papyrusPageIndex);
891
+ if (self.inkCanvasesByPageIndex[key] == canvas) {
892
+ [self.inkCanvasesByPageIndex removeObjectForKey:key];
893
+ [self.inkAnnotationSignaturesByPageIndex removeObjectForKey:key];
894
+ }
895
+ canvas.delegate = nil;
896
+ canvas.userInteractionEnabled = NO;
897
+ }
898
+
899
+ - (void)canvasViewDrawingDidChange:(PKCanvasView *)canvasView {
900
+ if (![canvasView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) return;
901
+ PapyrusPdfPageInkCanvasView *canvas = (PapyrusPdfPageInkCanvasView *)canvasView;
902
+ if (canvas.applyingStoreDrawing || ![self.activeTool isEqualToString:@"ink"]) return;
903
+ canvas.hasUncommittedChanges = YES;
904
+ NSUInteger generation = ++canvas.pendingCommitGeneration;
905
+ __weak typeof(self) weakSelf = self;
906
+ __weak PapyrusPdfPageInkCanvasView *weakCanvas = canvas;
907
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.40 * NSEC_PER_SEC)),
908
+ dispatch_get_main_queue(), ^{
909
+ typeof(self) strongSelf = weakSelf;
910
+ PapyrusPdfPageInkCanvasView *strongCanvas = weakCanvas;
911
+ if (!strongSelf || !strongCanvas ||
912
+ strongCanvas.pendingCommitGeneration != generation ||
913
+ !strongCanvas.hasUncommittedChanges) return;
914
+ UIGestureRecognizerState state = strongCanvas.drawingGestureRecognizer.state;
915
+ if (state == UIGestureRecognizerStateBegan ||
916
+ state == UIGestureRecognizerStateChanged) {
917
+ [strongSelf canvasViewDrawingDidChange:strongCanvas];
918
+ return;
919
+ }
920
+ [strongSelf commitInkDrawingForCanvas:strongCanvas];
921
+ });
922
+ }
923
+
924
+ - (void)canvasViewDidEndUsingTool:(PKCanvasView *)canvasView {
925
+ if ([canvasView isKindOfClass:PapyrusPdfPageInkCanvasView.class]) {
926
+ [self commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvasView];
927
+ }
928
+ }
929
+
930
+ - (void)commitInkDrawingForCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
931
+ if (!canvas || !canvas.hasUncommittedChanges) return;
932
+ canvas.pendingCommitGeneration += 1;
933
+ canvas.hasUncommittedChanges = NO;
934
+ NSArray<NSDictionary *> *strokes = [self inkDrawingPayloadForCanvas:canvas];
935
+ canvas.appliedStoreSignature = nil;
936
+ if (self.onInkDrawingCommitted) {
937
+ self.onInkDrawingCommitted(@{
938
+ @"pageIndex" : @(canvas.papyrusPageIndex),
939
+ @"strokes" : strokes
940
+ });
941
+ }
942
+ }
943
+
944
+ - (NSArray<NSDictionary *> *)inkDrawingPayloadForCanvas:(PapyrusPdfPageInkCanvasView *)canvas {
945
+ CGFloat width = CGRectGetWidth(canvas.bounds);
946
+ CGFloat height = CGRectGetHeight(canvas.bounds);
947
+ if (width <= 0 || height <= 0) return @[];
948
+
949
+ NSMutableArray<NSDictionary *> *payload = [NSMutableArray array];
950
+ for (PKStroke *stroke in canvas.drawing.strokes) {
951
+ // The universal Papyrus path has no clipping mask. Use the vector eraser so
952
+ // erased strokes disappear as complete paths instead of persisting masked ink.
953
+ if (stroke.mask != nil) continue;
954
+ PKStrokePath *path = stroke.path;
955
+ NSMutableArray<NSDictionary *> *points = [NSMutableArray array];
956
+ NSMutableArray<NSNumber *> *strokeWidthSamples = [NSMutableArray array];
957
+ CGAffineTransform strokeTransform = stroke.transform;
958
+ CGFloat transformDeterminant =
959
+ strokeTransform.a * strokeTransform.d - strokeTransform.b * strokeTransform.c;
960
+ CGFloat strokeWidthScale = sqrt(fabs(transformDeterminant));
961
+ if (!isfinite(strokeWidthScale) || strokeWidthScale <= 0) strokeWidthScale = 1.0;
962
+ for (NSUInteger index = 0; index < path.count; index += 1) {
963
+ PKStrokePoint *strokePoint = [path pointAtIndex:index];
964
+ CGPoint location = CGPointApplyAffineTransform(strokePoint.location, strokeTransform);
965
+ CGFloat x = MIN(1.0, MAX(0.0, location.x / width));
966
+ CGFloat y = MIN(1.0, MAX(0.0, location.y / height));
967
+ if (!isfinite(x) || !isfinite(y)) continue;
968
+ [points addObject:@{@"x" : @(x), @"y" : @(y)}];
969
+
970
+ CGFloat pointWidth = strokePoint.size.width * strokeWidthScale;
971
+ if (isfinite(pointWidth) && pointWidth > 0) {
972
+ [strokeWidthSamples addObject:@(pointWidth)];
973
+ }
974
+ }
975
+ if (points.count == 0) continue;
976
+ if (points.count == 1) [points addObject:points.firstObject];
977
+
978
+ CGFloat opacity = 1.0;
979
+ NSString *color = PapyrusHexColorFromUIColor(stroke.ink.color, &opacity);
980
+ if ([stroke.ink.inkType isEqualToString:PKInkTypeMarker]) {
981
+ // The universal Papyrus ink contract uses opacity <= 0.35 to restore a marker.
982
+ opacity = MIN(opacity, 0.28);
983
+ }
984
+
985
+ CGFloat representativeWidth = width * 0.006;
986
+ if (strokeWidthSamples.count > 0) {
987
+ NSArray<NSNumber *> *sortedWidthSamples =
988
+ [strokeWidthSamples sortedArrayUsingSelector:@selector(compare:)];
989
+ NSUInteger middleIndex = sortedWidthSamples.count / 2;
990
+ if (sortedWidthSamples.count % 2 == 0) {
991
+ representativeWidth =
992
+ (sortedWidthSamples[middleIndex - 1].doubleValue +
993
+ sortedWidthSamples[middleIndex].doubleValue) / 2.0;
994
+ } else {
995
+ representativeWidth = sortedWidthSamples[middleIndex].doubleValue;
996
+ }
997
+ }
998
+
999
+ CGFloat normalizedWidth = representativeWidth / width;
1000
+ if (!isfinite(normalizedWidth) || normalizedWidth <= 0) normalizedWidth = 0.006;
1001
+ [payload addObject:@{
1002
+ @"path" : points,
1003
+ @"color" : color ?: @"#111827",
1004
+ @"opacity" : @(opacity),
1005
+ @"strokeWidth" : @(normalizedWidth)
1006
+ }];
1007
+ }
1008
+ return [payload copy];
1009
+ }
1010
+
1011
+ - (void)toolPickerSelectedToolDidChange:(PKToolPicker *)toolPicker {
1012
+ PKTool *selectedTool = toolPicker.selectedTool;
1013
+ if (![selectedTool isKindOfClass:PKEraserTool.class]) return;
1014
+ PKEraserTool *eraser = (PKEraserTool *)selectedTool;
1015
+ if (eraser.eraserType == PKEraserTypeVector) return;
1016
+ // Papyrus stores normalized centerlines rather than PencilKit masks, so keep
1017
+ // erasing stroke-based and representable by the shared Annotation model.
1018
+ toolPicker.selectedTool = [[PKEraserTool alloc] initWithEraserType:PKEraserTypeVector];
1019
+ }
1020
+
1021
+ - (void)resetInkOverlaysForDocumentChange {
1022
+ [self deactivateInkCanvas];
1023
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
1024
+ canvas.delegate = nil;
1025
+ canvas.userInteractionEnabled = NO;
1026
+ }
1027
+ [self.inkCanvasesByPageIndex removeAllObjects];
1028
+ [self.inkAnnotationSignaturesByPageIndex removeAllObjects];
1029
+ }
1030
+
1031
+ - (void)didMoveToWindow {
1032
+ [super didMoveToWindow];
1033
+ if (!self.window) {
1034
+ [self deactivateInkCanvas];
1035
+ for (PapyrusPdfPageInkCanvasView *canvas in self.inkCanvasesByPageIndex.allValues) {
1036
+ canvas.userInteractionEnabled = NO;
1037
+ }
1038
+ return;
1039
+ }
1040
+ [self updateInkCanvasInputAndPicker];
1041
+ }
1042
+
1043
+ - (void)setAnnotationSelectionColor:(NSString *)annotationSelectionColor {
1044
+ NSString *normalized = annotationSelectionColor.length > 0
1045
+ ? [annotationSelectionColor copy] : @"#2563eb";
1046
+ if ([_annotationSelectionColor isEqualToString:normalized]) return;
1047
+ _annotationSelectionColor = normalized;
1048
+ [self updateSelectedAnnotationAdornment];
1049
+ }
1050
+
1051
+ - (void)setSelectedAnnotationId:(NSString *)selectedAnnotationId {
1052
+ NSString *normalized = selectedAnnotationId.length > 0
1053
+ ? [selectedAnnotationId copy] : nil;
1054
+ if ((_selectedAnnotationId == normalized) ||
1055
+ [_selectedAnnotationId isEqualToString:normalized]) return;
1056
+ _selectedAnnotationId = normalized;
1057
+ [self updateSelectedAnnotationAdornment];
1058
+ }
1059
+
1060
+ - (NSString *)annotationSignature:(NSDictionary *)annotation {
1061
+ NSArray<NSString *> *signatureKeys = @[
1062
+ @"id", @"type", @"pageIndex", @"rect", @"rects", @"color", @"opacity", @"content"
1063
+ ];
1064
+ NSMutableDictionary *signatureFields = [NSMutableDictionary dictionary];
1065
+ for (NSString *key in signatureKeys) {
1066
+ id value = annotation[key];
1067
+ if (value) signatureFields[key] = value;
1068
+ }
1069
+ if (![NSJSONSerialization isValidJSONObject:signatureFields]) {
1070
+ return signatureFields.description ?: @"";
1071
+ }
1072
+ NSError *error = nil;
1073
+ NSData *data = [NSJSONSerialization dataWithJSONObject:signatureFields
1074
+ options:NSJSONWritingSortedKeys
1075
+ error:&error];
1076
+ if (!data || error) return annotation.description ?: @"";
1077
+ return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
1078
+ }
1079
+
1080
+ - (void)removePapyrusAnnotationWithId:(NSString *)annotationId {
1081
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId] ?: @[];
1082
+ for (PDFAnnotation *annotation in representations) {
1083
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:annotation];
1084
+ if (![registeredId isEqualToString:annotationId]) continue;
1085
+ PDFPage *page = annotation.page;
1086
+ if (page) [page removeAnnotation:annotation];
1087
+ [self.papyrusAnnotationIdsByObject removeObjectForKey:annotation];
1088
+ }
1089
+ [self.papyrusAnnotationsById removeObjectForKey:annotationId];
1090
+ [self.papyrusAnnotationSignaturesById removeObjectForKey:annotationId];
1091
+ }
1092
+
1093
+ - (void)clearPapyrusAnnotationsForDocument:(PDFDocument *)document {
1094
+ (void)document;
1095
+ [self removeSelectedAnnotationAdornment];
1096
+ NSArray<NSString *> *annotationIds = self.papyrusAnnotationsById.allKeys.copy;
1097
+ for (NSString *annotationId in annotationIds) {
1098
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId] ?: @[];
1099
+ for (PDFAnnotation *annotation in representations) {
1100
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:annotation];
1101
+ if ([registeredId isEqualToString:annotationId] && annotation.page) {
1102
+ [annotation.page removeAnnotation:annotation];
1103
+ }
1104
+ [self.papyrusAnnotationIdsByObject removeObjectForKey:annotation];
1105
+ }
1106
+ }
1107
+ [self.papyrusAnnotationsById removeAllObjects];
1108
+ [self.papyrusAnnotationSignaturesById removeAllObjects];
1109
+ [self.papyrusAnnotationIdsByObject removeAllObjects];
1110
+ }
1111
+
1112
+ - (void)removeSelectedAnnotationAdornment {
1113
+ for (PDFAnnotation *annotation in self.selectedAnnotationAdornmentAnnotations ?: @[]) {
1114
+ PDFPage *page = annotation.page;
1115
+ if (page) [page removeAnnotation:annotation];
1116
+ }
1117
+ self.selectedAnnotationAdornmentAnnotations = @[];
1118
+ }
1119
+
1120
+ - (void)updateSelectedAnnotationAdornment {
1121
+ [self removeSelectedAnnotationAdornment];
1122
+ NSString *annotationId = self.selectedAnnotationId;
1123
+ NSArray<PDFAnnotation *> *representations = annotationId.length > 0
1124
+ ? self.papyrusAnnotationsById[annotationId] : @[];
1125
+ if (representations.count == 0) {
1126
+ [self.pdfView setNeedsDisplay];
1127
+ return;
1128
+ }
1129
+
1130
+ UIColor *selectionColor = PapyrusAnnotationColor(self.annotationSelectionColor, 1.0);
1131
+ NSMutableArray<PDFAnnotation *> *adornments = [NSMutableArray array];
1132
+ for (PDFAnnotation *representation in representations) {
1133
+ PDFPage *page = representation.page;
1134
+ CGRect bounds = representation.bounds;
1135
+ if (!page || CGRectIsNull(bounds) || CGRectIsEmpty(bounds)) continue;
1136
+
1137
+ PDFAnnotation *adornment = [[PapyrusSelectionOutlinePdfAnnotation alloc]
1138
+ initWithBounds:bounds forType:@"Stamp" withProperties:nil];
1139
+ adornment.color = selectionColor;
1140
+ adornment.shouldDisplay = YES;
1141
+ [page addAnnotation:adornment];
1142
+ [adornments addObject:adornment];
1143
+ }
1144
+ self.selectedAnnotationAdornmentAnnotations = [adornments copy];
1145
+ [self.pdfView setNeedsDisplay];
1146
+ }
1147
+
1148
+ - (NSArray<PDFAnnotation *> *)createPdfAnnotationsForPapyrusAnnotation:(NSDictionary *)annotation {
1149
+ PDFDocument *document = self.pdfView.document;
1150
+ if (!document || ![annotation isKindOfClass:NSDictionary.class]) return @[];
1151
+ id pageIndexValue = annotation[@"pageIndex"];
1152
+ if (![pageIndexValue isKindOfClass:NSNumber.class]) return @[];
1153
+ double pageIndexNumber = [pageIndexValue doubleValue];
1154
+ if (!isfinite(pageIndexNumber) || floor(pageIndexNumber) != pageIndexNumber ||
1155
+ pageIndexNumber < 0 || pageIndexNumber >= (double)document.pageCount) {
1156
+ return @[];
1157
+ }
1158
+
1159
+ NSString *type = [annotation[@"type"] isKindOfClass:NSString.class]
1160
+ ? annotation[@"type"] : @"";
1161
+ NSString *subtype = nil;
1162
+ if ([type isEqualToString:@"highlight"]) subtype = @"Highlight";
1163
+ else if ([type isEqualToString:@"underline"]) subtype = @"Underline";
1164
+ else if ([type isEqualToString:@"strikeout"]) subtype = @"StrikeOut";
1165
+ else if ([type isEqualToString:@"squiggly"] ||
1166
+ [type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1167
+ // Custom drawing stays in the subclasses; Stamp is a PDFKit-supported carrier subtype.
1168
+ subtype = @"Stamp";
1169
+ }
1170
+ if (!subtype) return @[];
1171
+
1172
+ PDFPage *page = [document pageAtIndex:(NSUInteger)pageIndexNumber];
1173
+ if (!page) return @[];
1174
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1175
+ if (CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) return @[];
1176
+
1177
+ NSArray *rects = [annotation[@"rects"] isKindOfClass:NSArray.class]
1178
+ ? annotation[@"rects"] : @[];
1179
+ if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1180
+ NSDictionary *rect = [annotation[@"rect"] isKindOfClass:NSDictionary.class]
1181
+ ? annotation[@"rect"] : (rects.firstObject ?: @{});
1182
+ rects = rect.count > 0 ? @[rect] : @[];
1183
+ } else if (rects.count == 0 && [annotation[@"rect"] isKindOfClass:NSDictionary.class]) {
1184
+ rects = @[annotation[@"rect"]];
1185
+ }
1186
+ if (rects.count == 0) return @[];
1187
+
1188
+ CGFloat defaultOpacity = [type isEqualToString:@"highlight"] ? 0.38 : 1.0;
1189
+ CGFloat opacity = [annotation[@"opacity"] respondsToSelector:@selector(doubleValue)]
1190
+ ? [annotation[@"opacity"] doubleValue] : defaultOpacity;
1191
+ if (!isfinite(opacity)) opacity = 1.0;
1192
+ NSString *hexColor = [annotation[@"color"] isKindOfClass:NSString.class]
1193
+ ? annotation[@"color"] : self.annotationColor;
1194
+ UIColor *color = PapyrusAnnotationColor(hexColor, opacity);
1195
+ NSString *content = [annotation[@"content"] isKindOfClass:NSString.class]
1196
+ ? annotation[@"content"] : @"";
1197
+ NSMutableArray<PDFAnnotation *> *representations = [NSMutableArray array];
1198
+
1199
+ for (id rectValue in rects) {
1200
+ if (![rectValue isKindOfClass:NSDictionary.class]) continue;
1201
+ CGRect pageRect = PapyrusPdfRectFromNormalizedRect(rectValue, pageBounds);
1202
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
1203
+
1204
+ PDFAnnotation *representation = nil;
1205
+ if ([type isEqualToString:@"squiggly"]) {
1206
+ representation = [[PapyrusSquigglyPdfAnnotation alloc]
1207
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1208
+ } else if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1209
+ representation = [[PapyrusCommentPdfAnnotation alloc]
1210
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1211
+ } else {
1212
+ representation = [[PDFAnnotation alloc]
1213
+ initWithBounds:pageRect forType:subtype withProperties:nil];
1214
+ }
1215
+ representation.color = color;
1216
+ representation.contents = content;
1217
+ representation.shouldDisplay = YES;
1218
+
1219
+ if ([type isEqualToString:@"highlight"] || [type isEqualToString:@"underline"] ||
1220
+ [type isEqualToString:@"strikeout"]) {
1221
+ CGFloat width = CGRectGetWidth(pageRect);
1222
+ CGFloat height = CGRectGetHeight(pageRect);
1223
+ representation.quadrilateralPoints = @[
1224
+ [NSValue valueWithCGPoint:CGPointMake(0, height)],
1225
+ [NSValue valueWithCGPoint:CGPointMake(width, height)],
1226
+ [NSValue valueWithCGPoint:CGPointMake(0, 0)],
1227
+ [NSValue valueWithCGPoint:CGPointMake(width, 0)]
1228
+ ];
1229
+ }
1230
+
1231
+ [page addAnnotation:representation];
1232
+ [representations addObject:representation];
1233
+ }
1234
+ return [representations copy];
1235
+ }
1236
+
1237
+ - (void)reconcilePapyrusAnnotations {
1238
+ PDFDocument *document = self.pdfView.document;
1239
+ if (!document) return;
1240
+ BOOL didChangeRepresentations = NO;
1241
+
1242
+ NSMutableDictionary<NSString *, NSDictionary *> *incomingById = [NSMutableDictionary dictionary];
1243
+ for (id value in self.annotations) {
1244
+ if (![value isKindOfClass:NSDictionary.class]) continue;
1245
+ NSDictionary *annotation = (NSDictionary *)value;
1246
+ NSString *annotationId = [annotation[@"id"] isKindOfClass:NSString.class]
1247
+ ? annotation[@"id"] : @"";
1248
+ if (annotationId.length == 0) continue;
1249
+ incomingById[annotationId] = annotation;
1250
+ }
1251
+
1252
+ for (NSString *existingId in self.papyrusAnnotationsById.allKeys.copy) {
1253
+ NSDictionary *updated = incomingById[existingId];
1254
+ NSString *nextSignature = updated ? [self annotationSignature:updated] : nil;
1255
+ if (!updated || ![nextSignature isEqualToString:self.papyrusAnnotationSignaturesById[existingId]]) {
1256
+ [self removePapyrusAnnotationWithId:existingId];
1257
+ didChangeRepresentations = YES;
1258
+ }
1259
+ }
1260
+
1261
+ for (NSString *annotationId in incomingById) {
1262
+ if (self.papyrusAnnotationSignaturesById[annotationId]) continue;
1263
+ NSDictionary *annotation = incomingById[annotationId];
1264
+ NSArray<PDFAnnotation *> *representations =
1265
+ [self createPdfAnnotationsForPapyrusAnnotation:annotation];
1266
+ for (PDFAnnotation *representation in representations) {
1267
+ [self.papyrusAnnotationIdsByObject setObject:annotationId forKey:representation];
1268
+ }
1269
+ self.papyrusAnnotationsById[annotationId] = representations;
1270
+ self.papyrusAnnotationSignaturesById[annotationId] =
1271
+ [self annotationSignature:annotation];
1272
+ didChangeRepresentations = YES;
1273
+ }
1274
+ if (didChangeRepresentations) {
1275
+ [self updateSelectedAnnotationAdornment];
1276
+ [self.pdfView setNeedsDisplay];
1277
+ }
1278
+ }
1279
+
1280
+ - (void)emitAnnotationFromCurrentSelectionWithType:(NSString *)type {
1281
+ if (!self.onAnnotationCreated) return;
1282
+ PDFSelection *selection = self.pdfView.currentSelection;
1283
+ NSString *text = selection.string ?: @"";
1284
+ PDFDocument *document = self.pdfView.document;
1285
+ PDFPage *page = selection.pages.firstObject;
1286
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
1287
+ if (!document || !page || pageIndex == NSNotFound || text.length == 0) return;
1288
+
1289
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1290
+ if (CGRectIsNull(pageBounds) || CGRectIsEmpty(pageBounds)) return;
1291
+ NSMutableArray<NSDictionary *> *rects = [NSMutableArray array];
1292
+ for (PDFSelection *line in selection.selectionsByLine) {
1293
+ if (![line.pages containsObject:page]) continue;
1294
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1295
+ [line boundsForPage:page], pageBounds);
1296
+ if (normalizedRect) [rects addObject:normalizedRect];
1297
+ }
1298
+ if (rects.count == 0) {
1299
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1300
+ [selection boundsForPage:page], pageBounds);
1301
+ if (normalizedRect) [rects addObject:normalizedRect];
1302
+ }
1303
+ if (rects.count == 0) return;
1304
+
1305
+ CGFloat minX = 1.0, minY = 1.0, maxX = 0.0, maxY = 0.0;
1306
+ for (NSDictionary *rect in rects) {
1307
+ CGFloat x = [rect[@"x"] doubleValue];
1308
+ CGFloat y = [rect[@"y"] doubleValue];
1309
+ minX = MIN(minX, x);
1310
+ minY = MIN(minY, y);
1311
+ maxX = MAX(maxX, x + [rect[@"width"] doubleValue]);
1312
+ maxY = MAX(maxY, y + [rect[@"height"] doubleValue]);
1313
+ }
1314
+
1315
+ CGFloat opacity = MIN(1.0, MAX(0.0, self.annotationOpacity));
1316
+ NSDictionary *annotationRect = nil;
1317
+ if ([type isEqualToString:@"comment"] || [type isEqualToString:@"text"]) {
1318
+ NSDictionary *firstRect = rects.firstObject;
1319
+ CGFloat width = MIN(1.0, MAX(0.08, [firstRect[@"width"] doubleValue]));
1320
+ CGFloat height = MIN(1.0, MAX(0.06, [firstRect[@"height"] doubleValue]));
1321
+ CGFloat x = MIN(1.0 - width, MAX(0.0, [firstRect[@"x"] doubleValue]));
1322
+ CGFloat y = MIN(1.0 - height, MAX(0.0, [firstRect[@"y"] doubleValue]));
1323
+ annotationRect = @{@"x" : @(x), @"y" : @(y), @"width" : @(width), @"height" : @(height)};
1324
+ } else {
1325
+ annotationRect = @{@"x" : @(minX), @"y" : @(minY), @"width" : @(maxX - minX), @"height" : @(maxY - minY)};
1326
+ }
1327
+
1328
+ NSDictionary *annotation = @{
1329
+ @"id" : [[NSUUID UUID] UUIDString],
1330
+ @"pageIndex" : @(pageIndex),
1331
+ @"type" : type,
1332
+ @"rect" : annotationRect,
1333
+ @"rects" : rects,
1334
+ @"color" : self.annotationColor ?: @"#fbbf24",
1335
+ @"opacity" : @(opacity),
1336
+ @"content" : text,
1337
+ @"createdAt" : @((long long)([[NSDate date] timeIntervalSince1970] * 1000.0))
1338
+ };
1339
+ self.onAnnotationCreated(annotation);
1340
+ }
1341
+
1342
+ - (void)emitCommentAtPage:(PDFPage *)page pageIndex:(NSInteger)pageIndex normalizedPoint:(CGPoint)point {
1343
+ if (!self.onAnnotationCreated || !page || pageIndex < 0) return;
1344
+ CGFloat x = MIN(0.92, MAX(0.0, point.x - 0.02));
1345
+ CGFloat y = MIN(0.94, MAX(0.0, point.y - 0.02));
1346
+ NSDictionary *rect = @{@"x" : @(x), @"y" : @(y), @"width" : @0.08, @"height" : @0.06};
1347
+ NSDictionary *annotation = @{
1348
+ @"id" : [[NSUUID UUID] UUIDString],
1349
+ @"pageIndex" : @(pageIndex),
1350
+ @"type" : @"comment",
1351
+ @"rect" : rect,
1352
+ @"rects" : @[rect],
1353
+ @"color" : self.annotationColor ?: @"#fbbf24",
1354
+ @"opacity" : @(MIN(1.0, MAX(0.0, self.annotationOpacity))),
1355
+ @"content" : @"",
1356
+ @"createdAt" : @((long long)([[NSDate date] timeIntervalSince1970] * 1000.0))
1357
+ };
1358
+ self.onAnnotationCreated(annotation);
1359
+ }
1360
+
1361
+ - (UIColor *)searchHighlightColorForActive:(BOOL)isActive {
1362
+ return isActive
1363
+ ? [UIColor colorWithRed:1.0 green:0.66 blue:0.08 alpha:0.54]
1364
+ : [UIColor colorWithRed:1.0 green:0.82 blue:0.20 alpha:0.25];
1365
+ }
1366
+
1367
+ - (void)rebuildSearchHighlights {
1368
+ PDFDocument *document = self.pdfView.document;
1369
+ if (!document || self.searchResults.count == 0) {
1370
+ self.searchSelections = @[];
1371
+ self.searchSelectionsByResultIndex = @{};
1372
+ self.pdfView.highlightedSelections = nil;
1373
+ [self scheduleNavigationToSearchResultAtIndex:self.activeSearchIndex];
1374
+ return;
1375
+ }
1376
+
1377
+ NSMutableArray<PDFSelection *> *selections =
1378
+ [NSMutableArray arrayWithCapacity:self.searchResults.count];
1379
+ NSMutableDictionary<NSNumber *, PDFSelection *> *selectionsByResultIndex =
1380
+ [NSMutableDictionary dictionaryWithCapacity:self.searchResults.count];
1381
+ for (NSUInteger resultIndex = 0; resultIndex < self.searchResults.count; resultIndex += 1) {
1382
+ id resultValue = self.searchResults[resultIndex];
1383
+ if (![resultValue isKindOfClass:NSDictionary.class]) continue;
1384
+ NSDictionary *result = (NSDictionary *)resultValue;
1385
+ id pageIndexValue = result[@"pageIndex"];
1386
+ if (![pageIndexValue isKindOfClass:NSNumber.class]) continue;
1387
+ double pageIndexNumber = [pageIndexValue doubleValue];
1388
+ if (!isfinite(pageIndexNumber) || floor(pageIndexNumber) != pageIndexNumber ||
1389
+ pageIndexNumber < 0 || pageIndexNumber >= (double)document.pageCount) {
1390
+ continue;
1391
+ }
1392
+ NSUInteger pageIndex = (NSUInteger)pageIndexNumber;
1393
+
1394
+ PDFPage *page = [document pageAtIndex:pageIndex];
1395
+ id rectsValue = result[@"rects"];
1396
+ NSArray *rects = [rectsValue isKindOfClass:NSArray.class] ? rectsValue : @[];
1397
+ if (!page || rects.count == 0) continue;
1398
+
1399
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1400
+ if (pageBounds.size.width <= 0 || pageBounds.size.height <= 0) continue;
1401
+
1402
+ PDFSelection *match = [[PDFSelection alloc] initWithDocument:document];
1403
+ BOOL hasSelectedText = NO;
1404
+ for (id rectValue in rects) {
1405
+ if (![rectValue isKindOfClass:NSDictionary.class]) continue;
1406
+ CGRect pageRect = PapyrusPdfRectFromNormalizedRect((NSDictionary *)rectValue, pageBounds);
1407
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
1408
+ PDFSelection *lineSelection = [page selectionForRect:pageRect];
1409
+ if (!lineSelection.string.length) continue;
1410
+
1411
+ [match addSelection:lineSelection];
1412
+ hasSelectedText = YES;
1413
+ }
1414
+
1415
+ if (!hasSelectedText) continue;
1416
+ match.color = [self searchHighlightColorForActive:
1417
+ ((NSInteger)resultIndex == self.activeSearchIndex)];
1418
+ [selections addObject:match];
1419
+ selectionsByResultIndex[@(resultIndex)] = match;
1420
+ }
1421
+
1422
+ self.searchSelections = [selections copy];
1423
+ self.searchSelectionsByResultIndex = [selectionsByResultIndex copy];
1424
+ self.pdfView.highlightedSelections =
1425
+ self.searchSelections.count > 0 ? self.searchSelections : nil;
1426
+ [self scheduleNavigationToSearchResultAtIndex:self.activeSearchIndex];
1427
+ }
1428
+
1429
+ - (void)updateSearchHighlightColorsFromResultIndex:(NSInteger)previousSearchIndex {
1430
+ if (previousSearchIndex == self.activeSearchIndex) return;
1431
+
1432
+ PDFSelection *previousSelection =
1433
+ self.searchSelectionsByResultIndex[@(previousSearchIndex)];
1434
+ PDFSelection *activeSelection =
1435
+ self.searchSelectionsByResultIndex[@(self.activeSearchIndex)];
1436
+ if (previousSelection) {
1437
+ previousSelection.color = [self searchHighlightColorForActive:NO];
1438
+ }
1439
+ if (activeSelection) {
1440
+ activeSelection.color = [self searchHighlightColorForActive:YES];
1441
+ }
1442
+ if (previousSelection || activeSelection) {
1443
+ self.pdfView.highlightedSelections = self.searchSelections;
1444
+ }
1445
+ }
1446
+
1447
+ - (void)scheduleNavigationToSearchResultAtIndex:(NSInteger)activeSearchIndex {
1448
+ NSUInteger generation = ++self.searchNavigationGeneration;
1449
+ dispatch_async(dispatch_get_main_queue(), ^{
1450
+ if (self.searchNavigationGeneration != generation ||
1451
+ self.activeSearchIndex != activeSearchIndex) {
1452
+ return;
1453
+ }
1454
+ PDFSelection *selection =
1455
+ self.searchSelectionsByResultIndex[@(activeSearchIndex)];
1456
+ if (!selection) return;
1457
+ [self.pdfView goToSelection:selection];
1458
+ });
1459
+ }
1460
+
265
1461
  - (void)configureDisplayMode {
266
1462
  self.pdfView.displayBox = kPDFDisplayBoxCropBox;
267
1463
  self.pdfView.displayDirection = kPDFDisplayDirectionVertical;
@@ -338,6 +1534,7 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
338
1534
 
339
1535
  - (void)handlePdfPageChanged:(NSNotification *)notification {
340
1536
  if (notification.object != self.pdfView) return;
1537
+ [self updateInkCanvasInputAndPicker];
341
1538
  [self emitCurrentPageIfNeeded];
342
1539
  [self emitVisiblePagesIfNeeded];
343
1540
  }
@@ -440,10 +1637,15 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
440
1637
  if (self.onTextSelected) {
441
1638
  self.onTextSelected(@{@"text" : text, @"pageIndex" : @(pageIndex), @"rects" : rects});
442
1639
  }
1640
+ [self scheduleSelectionEditMenuForSignature:signature];
443
1641
  }
444
1642
 
445
1643
  - (void)emitSelectionClearedIfNeeded {
446
1644
  if (!self.lastSelectionWasActive) return;
1645
+ self.selectionMenuGeneration += 1;
1646
+ if (@available(iOS 16.0, *)) {
1647
+ [self.editMenuInteraction dismissMenu];
1648
+ }
447
1649
  NSInteger pageIndex = self.lastSelectionPageIndex;
448
1650
  if (pageIndex == NSNotFound) pageIndex = MAX(0, self.currentPage - 1);
449
1651
  self.lastSelectionWasActive = NO;
@@ -454,6 +1656,228 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
454
1656
  }
455
1657
  }
456
1658
 
1659
+ - (void)scheduleSelectionEditMenuForSignature:(NSString *)signature {
1660
+ if (@available(iOS 16.0, *)) {
1661
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1662
+ if (!interaction || signature.length == 0) return;
1663
+
1664
+ NSUInteger generation = ++self.selectionMenuGeneration;
1665
+ __weak typeof(self) weakSelf = self;
1666
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.22 * NSEC_PER_SEC)),
1667
+ dispatch_get_main_queue(), ^{
1668
+ typeof(self) strongSelf = weakSelf;
1669
+ [strongSelf attemptSelectionEditMenuForSignature:signature generation:generation];
1670
+ });
1671
+ }
1672
+ }
1673
+
1674
+ - (void)attemptSelectionEditMenuForSignature:(NSString *)signature generation:(NSUInteger)generation {
1675
+ if (@available(iOS 16.0, *)) {
1676
+ if (generation != self.selectionMenuGeneration ||
1677
+ ![signature isEqualToString:self.lastSelectionSignature]) {
1678
+ return;
1679
+ }
1680
+
1681
+ if ([self hasActiveGestureInView:self.pdfView]) {
1682
+ __weak typeof(self) weakSelf = self;
1683
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.10 * NSEC_PER_SEC)),
1684
+ dispatch_get_main_queue(), ^{
1685
+ typeof(self) strongSelf = weakSelf;
1686
+ [strongSelf attemptSelectionEditMenuForSignature:signature generation:generation];
1687
+ });
1688
+ return;
1689
+ }
1690
+
1691
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1692
+ PDFSelection *selection = self.pdfView.currentSelection;
1693
+ PDFPage *page = selection.pages.firstObject;
1694
+ if (!interaction || !selection.string.length || !page ||
1695
+ (!self.onDefineSelection && !self.onAnnotationCreated)) return;
1696
+
1697
+ CGRect selectionRect = [selection boundsForPage:page];
1698
+ CGRect viewRect = [self.pdfView convertRect:selectionRect fromPage:page];
1699
+ if (CGRectIsNull(viewRect) || CGRectIsEmpty(viewRect)) return;
1700
+ self.contextualAnnotationMenuId = nil;
1701
+ self.contextualAnnotationMenuConfigurationId = nil;
1702
+ CGPoint sourcePoint = CGPointMake(CGRectGetMidX(viewRect), CGRectGetMidY(viewRect));
1703
+ UIEditMenuConfiguration *configuration =
1704
+ [[UIEditMenuConfiguration alloc] initWithIdentifier:signature sourcePoint:sourcePoint];
1705
+ [interaction presentEditMenuWithConfiguration:configuration];
1706
+ }
1707
+ }
1708
+
1709
+ - (void)presentAnnotationEditMenuForId:(NSString *)annotationId atPoint:(CGPoint)point {
1710
+ if (@available(iOS 16.0, *)) {
1711
+ UIEditMenuInteraction *interaction = self.editMenuInteraction;
1712
+ if (!interaction || !self.onAnnotationDelete ||
1713
+ self.annotationDeleteLabel.length == 0 || annotationId.length == 0) return;
1714
+
1715
+ NSString *configurationId = [NSString stringWithFormat:
1716
+ @"com.papyrus.annotation.delete.%@.%@", annotationId, [[NSUUID UUID] UUIDString]];
1717
+ self.contextualAnnotationMenuId = [annotationId copy];
1718
+ self.contextualAnnotationMenuConfigurationId = configurationId;
1719
+ self.contextualAnnotationMenuSourcePoint = point;
1720
+ UIEditMenuConfiguration *configuration = [[UIEditMenuConfiguration alloc]
1721
+ initWithIdentifier:configurationId sourcePoint:point];
1722
+ [interaction presentEditMenuWithConfiguration:configuration];
1723
+ }
1724
+ }
1725
+
1726
+ - (void)dismissAnnotationMenuForDocumentChange {
1727
+ self.contextualAnnotationMenuId = nil;
1728
+ self.contextualAnnotationMenuConfigurationId = nil;
1729
+ self.contextualAnnotationMenuSourcePoint = CGPointZero;
1730
+ if (@available(iOS 16.0, *)) {
1731
+ [self.editMenuInteraction dismissMenu];
1732
+ }
1733
+ if (self.onAnnotationDeselected) self.onAnnotationDeselected(@{});
1734
+ }
1735
+
1736
+ - (BOOL)hasActiveGestureInView:(UIView *)view {
1737
+ for (UIGestureRecognizer *recognizer in view.gestureRecognizers) {
1738
+ if (recognizer.state == UIGestureRecognizerStateBegan ||
1739
+ recognizer.state == UIGestureRecognizerStateChanged) {
1740
+ return YES;
1741
+ }
1742
+ }
1743
+
1744
+ for (UIView *subview in view.subviews) {
1745
+ if ([self hasActiveGestureInView:subview]) return YES;
1746
+ }
1747
+ return NO;
1748
+ }
1749
+
1750
+ - (nullable UIMenu *)editMenuInteraction:(UIEditMenuInteraction *)interaction
1751
+ menuForConfiguration:(UIEditMenuConfiguration *)configuration
1752
+ suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions API_AVAILABLE(ios(16.0)) {
1753
+ if (self.contextualAnnotationMenuId.length > 0 &&
1754
+ [configuration.identifier isEqual:self.contextualAnnotationMenuConfigurationId]) {
1755
+ NSString *annotationId = [self.contextualAnnotationMenuId copy];
1756
+ if (!self.onAnnotationDelete || self.annotationDeleteLabel.length == 0) return nil;
1757
+ PDFDocument *documentAtPresentation = self.pdfView.document;
1758
+ __weak typeof(self) weakSelf = self;
1759
+ UIAction *deleteAction = [UIAction
1760
+ actionWithTitle:self.annotationDeleteLabel
1761
+ image:[UIImage systemImageNamed:@"trash"]
1762
+ identifier:@"com.papyrus.annotation.delete"
1763
+ handler:^(__kindof UIAction *action) {
1764
+ typeof(self) strongSelf = weakSelf;
1765
+ if (!strongSelf || strongSelf.pdfView.document != documentAtPresentation) return;
1766
+ [strongSelf emitAnnotationDeleteWithId:annotationId];
1767
+ }];
1768
+ return [UIMenu menuWithChildren:@[deleteAction]];
1769
+ }
1770
+
1771
+ NSMutableArray<UIMenuElement *> *actions = [suggestedActions mutableCopy];
1772
+ if (!actions) actions = [NSMutableArray array];
1773
+
1774
+ if (self.onDefineSelection && self.defineLabel.length > 0 &&
1775
+ self.pdfView.currentSelection.string.length > 0) {
1776
+ __weak typeof(self) weakSelf = self;
1777
+ UIAction *defineAction = [UIAction
1778
+ actionWithTitle:self.defineLabel
1779
+ image:[UIImage systemImageNamed:@"text.magnifyingglass"]
1780
+ identifier:@"com.papyrus.define-selection"
1781
+ handler:^(__kindof UIAction *action) {
1782
+ [weakSelf emitDefineSelection];
1783
+ }];
1784
+ [actions addObject:defineAction];
1785
+ }
1786
+
1787
+ if (self.onAnnotationCreated && self.annotateLabel.length > 0 &&
1788
+ self.pdfView.currentSelection.string.length > 0) {
1789
+ __weak typeof(self) weakSelf = self;
1790
+ UIAction *highlightAction = [UIAction
1791
+ actionWithTitle:self.annotationHighlightLabel
1792
+ image:[UIImage systemImageNamed:@"highlighter"]
1793
+ identifier:@"com.papyrus.annotation.highlight"
1794
+ handler:^(__kindof UIAction *action) {
1795
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"highlight"];
1796
+ }];
1797
+ UIAction *underlineAction = [UIAction
1798
+ actionWithTitle:self.annotationUnderlineLabel
1799
+ image:[UIImage systemImageNamed:@"underline"]
1800
+ identifier:@"com.papyrus.annotation.underline"
1801
+ handler:^(__kindof UIAction *action) {
1802
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"underline"];
1803
+ }];
1804
+ UIAction *strikeoutAction = [UIAction
1805
+ actionWithTitle:self.annotationStrikeoutLabel
1806
+ image:[UIImage systemImageNamed:@"strikethrough"]
1807
+ identifier:@"com.papyrus.annotation.strikeout"
1808
+ handler:^(__kindof UIAction *action) {
1809
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"strikeout"];
1810
+ }];
1811
+ UIAction *squigglyAction = [UIAction
1812
+ actionWithTitle:self.annotationSquigglyLabel
1813
+ image:[UIImage systemImageNamed:@"scribble"]
1814
+ identifier:@"com.papyrus.annotation.squiggly"
1815
+ handler:^(__kindof UIAction *action) {
1816
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"squiggly"];
1817
+ }];
1818
+ UIAction *noteAction = [UIAction
1819
+ actionWithTitle:self.annotationNoteLabel
1820
+ image:[UIImage systemImageNamed:@"note.text"]
1821
+ identifier:@"com.papyrus.annotation.comment"
1822
+ handler:^(__kindof UIAction *action) {
1823
+ [weakSelf emitAnnotationFromCurrentSelectionWithType:@"comment"];
1824
+ }];
1825
+ UIMenu *annotationMenu = [UIMenu menuWithTitle:self.annotateLabel
1826
+ children:@[highlightAction, underlineAction,
1827
+ strikeoutAction, squigglyAction, noteAction]];
1828
+ [actions addObject:annotationMenu];
1829
+ }
1830
+
1831
+ return [UIMenu menuWithChildren:actions];
1832
+ }
1833
+
1834
+ - (CGRect)editMenuInteraction:(UIEditMenuInteraction *)interaction
1835
+ targetRectForConfiguration:(UIEditMenuConfiguration *)configuration API_AVAILABLE(ios(16.0)) {
1836
+ if (self.contextualAnnotationMenuId.length > 0 &&
1837
+ [configuration.identifier isEqual:self.contextualAnnotationMenuConfigurationId]) {
1838
+ CGPoint point = self.contextualAnnotationMenuSourcePoint;
1839
+ return CGRectMake(point.x, point.y, 1.0, 1.0);
1840
+ }
1841
+
1842
+ PDFSelection *selection = self.pdfView.currentSelection;
1843
+ PDFPage *page = selection.pages.firstObject;
1844
+ if (!selection || !page) return CGRectZero;
1845
+
1846
+ CGRect selectionRect = [selection boundsForPage:page];
1847
+ CGRect viewRect = [self.pdfView convertRect:selectionRect fromPage:page];
1848
+ return CGRectIsNull(viewRect) || CGRectIsEmpty(viewRect) ? CGRectZero : viewRect;
1849
+ }
1850
+
1851
+ - (void)editMenuInteraction:(UIEditMenuInteraction *)interaction
1852
+ willDismissMenuForConfiguration:(UIEditMenuConfiguration *)configuration
1853
+ animator:(id<UIEditMenuInteractionAnimating>)animator API_AVAILABLE(ios(16.0)) {
1854
+ if (self.contextualAnnotationMenuId.length == 0 ||
1855
+ ![configuration.identifier isEqual:self.contextualAnnotationMenuConfigurationId]) return;
1856
+
1857
+ self.contextualAnnotationMenuId = nil;
1858
+ self.contextualAnnotationMenuConfigurationId = nil;
1859
+ self.contextualAnnotationMenuSourcePoint = CGPointZero;
1860
+ if (self.onAnnotationDeselected) self.onAnnotationDeselected(@{});
1861
+ }
1862
+
1863
+ - (void)emitDefineSelection {
1864
+ if (!self.onDefineSelection) return;
1865
+ PDFSelection *selection = self.pdfView.currentSelection;
1866
+ NSString *text = selection.string ?: @"";
1867
+ PDFDocument *document = self.pdfView.document;
1868
+ PDFPage *page = selection.pages.firstObject;
1869
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
1870
+ if (text.length == 0 || !document || !page || pageIndex == NSNotFound) return;
1871
+
1872
+ self.onDefineSelection(@{@"text" : text, @"pageIndex" : @(pageIndex)});
1873
+ }
1874
+
1875
+ - (void)emitAnnotationDeleteWithId:(NSString *)annotationId {
1876
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[annotationId];
1877
+ if (annotationId.length == 0 || representations.count == 0 || !self.onAnnotationDelete) return;
1878
+ self.onAnnotationDelete(@{@"id" : annotationId});
1879
+ }
1880
+
457
1881
  - (void)clearCurrentSelection {
458
1882
  if (self.pdfView.currentSelection) {
459
1883
  self.pdfView.currentSelection = nil;
@@ -592,14 +2016,11 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
592
2016
 
593
2017
  - (void)handleDocumentTap:(UITapGestureRecognizer *)recognizer {
594
2018
  if (recognizer.state != UIGestureRecognizerStateEnded) return;
2019
+ if ([self.activeTool isEqualToString:@"ink"]) return;
595
2020
  PDFDocument *document = self.pdfView.document;
596
2021
  if (!document) return;
597
2022
 
598
2023
  CGPoint viewPoint = [recognizer locationInView:self.pdfView];
599
- if (self.pdfView.currentSelection && ![self selectionContainsViewPoint:viewPoint]) {
600
- [self clearCurrentSelection];
601
- return;
602
- }
603
2024
  PDFPage *page = [self.pdfView pageForPoint:viewPoint nearest:YES];
604
2025
  if (!page) return;
605
2026
  CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
@@ -610,17 +2031,85 @@ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBoun
610
2031
  NSInteger pageIndex = [document indexForPage:page];
611
2032
  if (pageIndex == NSNotFound) return;
612
2033
 
2034
+ PDFAnnotation *hitAnnotation = nil;
2035
+ NSString *annotationId = nil;
2036
+ for (id candidateValue in [self.annotations reverseObjectEnumerator]) {
2037
+ if (![candidateValue isKindOfClass:NSDictionary.class]) continue;
2038
+ NSDictionary *candidate = (NSDictionary *)candidateValue;
2039
+ NSString *candidateId = [candidate[@"id"] isKindOfClass:NSString.class]
2040
+ ? candidate[@"id"] : nil;
2041
+ if (candidateId.length == 0) continue;
2042
+ NSArray<PDFAnnotation *> *representations = self.papyrusAnnotationsById[candidateId] ?: @[];
2043
+ for (PDFAnnotation *representation in [representations reverseObjectEnumerator]) {
2044
+ if (representation.page != page ||
2045
+ !CGRectContainsPoint(CGRectInset(representation.bounds, -4.0, -4.0), pagePoint)) {
2046
+ continue;
2047
+ }
2048
+ NSString *registeredId = [self.papyrusAnnotationIdsByObject objectForKey:representation];
2049
+ if (![registeredId isEqualToString:candidateId]) continue;
2050
+ hitAnnotation = representation;
2051
+ annotationId = candidateId;
2052
+ break;
2053
+ }
2054
+ if (hitAnnotation) break;
2055
+ }
2056
+ if (annotationId.length > 0) {
2057
+ NSDictionary *papyrusAnnotation = nil;
2058
+ for (id value in self.annotations) {
2059
+ if (![value isKindOfClass:NSDictionary.class]) continue;
2060
+ NSDictionary *candidate = (NSDictionary *)value;
2061
+ if ([candidate[@"id"] isEqual:annotationId]) {
2062
+ papyrusAnnotation = candidate;
2063
+ break;
2064
+ }
2065
+ }
2066
+ if (@available(iOS 16.0, *)) {
2067
+ [self.editMenuInteraction dismissMenu];
2068
+ }
2069
+ if (self.onAnnotationTap) {
2070
+ self.onAnnotationTap(@{
2071
+ @"id" : annotationId,
2072
+ @"pageIndex" : @(pageIndex),
2073
+ @"type" : papyrusAnnotation[@"type"] ?: @"",
2074
+ @"color" : papyrusAnnotation[@"color"] ?: @""
2075
+ });
2076
+ }
2077
+ NSString *annotationType = [papyrusAnnotation[@"type"] isKindOfClass:NSString.class]
2078
+ ? papyrusAnnotation[@"type"] : @"";
2079
+ if (![annotationType isEqualToString:@"comment"] &&
2080
+ ![annotationType isEqualToString:@"text"]) {
2081
+ [self presentAnnotationEditMenuForId:annotationId atPoint:viewPoint];
2082
+ }
2083
+ return;
2084
+ }
2085
+
2086
+ if (self.pdfView.currentSelection && ![self selectionContainsViewPoint:viewPoint]) {
2087
+ [self clearCurrentSelection];
2088
+ return;
2089
+ }
2090
+
2091
+ CGPoint normalizedPoint = CGPointMake(MIN(1.0, MAX(0.0, x)),
2092
+ MIN(1.0, MAX(0.0, y)));
2093
+ if ([self.activeTool isEqualToString:@"comment"]) {
2094
+ CGRect pageViewBounds = [self.pdfView convertRect:pageBounds fromPage:page];
2095
+ if (CGRectContainsPoint(pageViewBounds, viewPoint)) {
2096
+ [self emitCommentAtPage:page pageIndex:pageIndex normalizedPoint:normalizedPoint];
2097
+ }
2098
+ return;
2099
+ }
2100
+
613
2101
  if (self.onTap) {
614
2102
  self.onTap(@{
615
2103
  @"pageIndex" : @(pageIndex),
616
- @"x" : @(MIN(1.0, MAX(0.0, x))),
617
- @"y" : @(MIN(1.0, MAX(0.0, y)))
2104
+ @"x" : @(normalizedPoint.x),
2105
+ @"y" : @(normalizedPoint.y)
618
2106
  });
619
2107
  }
620
2108
  }
621
2109
 
622
2110
  - (void)handleDocumentDoubleTap:(UITapGestureRecognizer *)recognizer {
623
2111
  if (recognizer.state != UIGestureRecognizerStateEnded) return;
2112
+ if ([self.activeTool isEqualToString:@"ink"]) return;
624
2113
  PDFDocument *document = self.pdfView.document;
625
2114
  if (!document) return;
626
2115