@papyrus-sdk/engine-native 0.2.21 → 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.
@@ -0,0 +1,2147 @@
1
+ #import "PapyrusPdfDocumentView.h"
2
+
3
+ #import <QuartzCore/QuartzCore.h>
4
+ #import <PencilKit/PencilKit.h>
5
+ #import <dispatch/dispatch.h>
6
+ #import <math.h>
7
+
8
+ #import "PapyrusEngineStore.h"
9
+
10
+ static const CGFloat PapyrusPdfMinimumZoom = 0.5;
11
+ static const CGFloat PapyrusPdfMaximumZoom = 4.0;
12
+ static const CGFloat PapyrusPdfZoomEventTolerance = 0.02;
13
+ static const NSTimeInterval PapyrusPdfZoomEventInterval = 0.10;
14
+ static const NSTimeInterval PapyrusPdfScrollEventInterval = 0.08;
15
+ static void *PapyrusPdfScrollObservationContext = &PapyrusPdfScrollObservationContext;
16
+
17
+ static NSDictionary *PapyrusNormalizedSelectionRect(CGRect rect, CGRect pageBounds) {
18
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) return nil;
19
+ rect = CGRectIntersection(rect, pageBounds);
20
+ if (CGRectIsNull(rect) || CGRectIsEmpty(rect)) return nil;
21
+
22
+ CGFloat pageWidth = CGRectGetWidth(pageBounds);
23
+ CGFloat pageHeight = CGRectGetHeight(pageBounds);
24
+ if (!isfinite(pageWidth) || !isfinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) {
25
+ return nil;
26
+ }
27
+
28
+ CGFloat x = (CGRectGetMinX(rect) - CGRectGetMinX(pageBounds)) / pageWidth;
29
+ CGFloat y = 1.0 - ((CGRectGetMaxY(rect) - CGRectGetMinY(pageBounds)) / pageHeight);
30
+ CGFloat width = CGRectGetWidth(rect) / pageWidth;
31
+ CGFloat height = CGRectGetHeight(rect) / pageHeight;
32
+ if (!isfinite(x) || !isfinite(y) || !isfinite(width) || !isfinite(height)) return nil;
33
+
34
+ x = MIN(1.0, MAX(0.0, x));
35
+ y = MIN(1.0, MAX(0.0, y));
36
+ width = MIN(1.0 - x, MAX(0.0, width));
37
+ height = MIN(1.0 - y, MAX(0.0, height));
38
+ if (width <= 0 || height <= 0) return nil;
39
+
40
+ return @{@"x" : @(x), @"y" : @(y), @"width" : @(width), @"height" : @(height)};
41
+ }
42
+
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>
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;
266
+ @property (nonatomic, weak) UIScrollView *observedScrollView;
267
+ @property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
268
+ @property (nonatomic, strong) UITapGestureRecognizer *doubleTapRecognizer;
269
+ @property (nonatomic, assign) CGSize lastLayoutSize;
270
+ @property (nonatomic, assign) NSInteger lastEmittedPage;
271
+ @property (nonatomic, assign) CGFloat lastEmittedZoom;
272
+ @property (nonatomic, copy) NSString *lastVisiblePagesSignature;
273
+ @property (nonatomic, assign) BOOL zoomEventScheduled;
274
+ @property (nonatomic, assign) BOOL suppressScaleSynchronization;
275
+ @property (nonatomic, assign) BOOL scrollEventScheduled;
276
+ @property (nonatomic, assign) CGFloat pendingScrollOffsetY;
277
+ @property (nonatomic, assign) CFTimeInterval lastScrollEventTime;
278
+ @property (nonatomic, copy) NSString *lastSelectionSignature;
279
+ @property (nonatomic, assign) NSInteger lastSelectionPageIndex;
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;
317
+ @end
318
+
319
+ @implementation PapyrusPdfDocumentView
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
+
330
+ - (instancetype)initWithFrame:(CGRect)frame {
331
+ self = [super initWithFrame:frame];
332
+ if (!self) return nil;
333
+
334
+ _pageTheme = @"normal";
335
+ _viewMode = @"continuous";
336
+ _zoom = 1.0;
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;
356
+ _lastEmittedPage = NSNotFound;
357
+ _lastSelectionPageIndex = NSNotFound;
358
+ _lastEmittedZoom = NAN;
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);
367
+ self.clipsToBounds = YES;
368
+ self.backgroundColor = UIColor.whiteColor;
369
+
370
+ _pdfView = [[PDFView alloc] initWithFrame:CGRectZero];
371
+ _pdfView.displayBox = kPDFDisplayBoxCropBox;
372
+ _pdfView.displayDirection = kPDFDisplayDirectionVertical;
373
+ _pdfView.displayMode = kPDFDisplaySinglePageContinuous;
374
+ _pdfView.displaysPageBreaks = YES;
375
+ _pdfView.autoScales = YES;
376
+ _pdfView.userInteractionEnabled = YES;
377
+ _pdfView.backgroundColor = UIColor.whiteColor;
378
+ _pdfView.clipsToBounds = YES;
379
+ [self addSubview:_pdfView];
380
+
381
+ if (@available(iOS 16.0, *)) {
382
+ _pdfView.pageOverlayViewProvider = self;
383
+ _editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
384
+ [_pdfView addInteraction:_editMenuInteraction];
385
+ }
386
+
387
+ _tapRecognizer = [[UITapGestureRecognizer alloc]
388
+ initWithTarget:self
389
+ action:@selector(handleDocumentTap:)];
390
+ _tapRecognizer.delegate = self;
391
+ _tapRecognizer.cancelsTouchesInView = NO;
392
+ _tapRecognizer.delaysTouchesBegan = NO;
393
+ [_pdfView addGestureRecognizer:_tapRecognizer];
394
+
395
+ _doubleTapRecognizer = [[UITapGestureRecognizer alloc]
396
+ initWithTarget:self
397
+ action:@selector(handleDocumentDoubleTap:)];
398
+ _doubleTapRecognizer.numberOfTapsRequired = 2;
399
+ _doubleTapRecognizer.delegate = self;
400
+ _doubleTapRecognizer.cancelsTouchesInView = NO;
401
+ _doubleTapRecognizer.delaysTouchesBegan = NO;
402
+ [_pdfView addGestureRecognizer:_doubleTapRecognizer];
403
+ [_tapRecognizer requireGestureRecognizerToFail:_doubleTapRecognizer];
404
+
405
+ NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
406
+ [center addObserver:self
407
+ selector:@selector(handlePdfPageChanged:)
408
+ name:PDFViewPageChangedNotification
409
+ object:_pdfView];
410
+ [center addObserver:self
411
+ selector:@selector(handlePdfScaleChanged:)
412
+ name:PDFViewScaleChangedNotification
413
+ object:_pdfView];
414
+ [center addObserver:self
415
+ selector:@selector(handlePdfVisiblePagesChanged:)
416
+ name:PDFViewVisiblePagesChangedNotification
417
+ object:_pdfView];
418
+ [center addObserver:self
419
+ selector:@selector(handlePdfSelectionChanged:)
420
+ name:PDFViewSelectionChangedNotification
421
+ object:_pdfView];
422
+ [center addObserver:self
423
+ selector:@selector(handleStoredDocumentChanged:)
424
+ name:PapyrusEngineStoreDocumentDidChangeNotification
425
+ object:[PapyrusEngineStore shared]];
426
+
427
+ return self;
428
+ }
429
+
430
+ - (void)setSelectionActive:(BOOL)selectionActive {
431
+ _selectionActive = selectionActive;
432
+ if (!selectionActive) {
433
+ [self clearCurrentSelection];
434
+ }
435
+ }
436
+
437
+ - (void)layoutSubviews {
438
+ [super layoutSubviews];
439
+ self.pdfView.frame = self.bounds;
440
+
441
+ if (!CGSizeEqualToSize(self.lastLayoutSize, self.bounds.size)) {
442
+ self.lastLayoutSize = self.bounds.size;
443
+ [self updateFitScalePreservingViewport];
444
+ }
445
+
446
+ [self refreshScrollViewObservation];
447
+ [self emitVisiblePagesIfNeeded];
448
+ }
449
+
450
+ - (void)setEngineId:(NSString *)engineId {
451
+ NSString *normalized = engineId.length > 0 ? [engineId copy] : nil;
452
+ if ((_engineId == normalized) || [_engineId isEqualToString:normalized]) return;
453
+ _engineId = normalized;
454
+ [self reloadDocumentFromStore];
455
+ }
456
+
457
+ - (void)setPageTheme:(NSString *)pageTheme {
458
+ _pageTheme = pageTheme.length > 0 ? [pageTheme copy] : @"normal";
459
+ // Non-normal page themes route to the compatibility viewer in JavaScript.
460
+ self.backgroundColor = UIColor.whiteColor;
461
+ self.pdfView.backgroundColor = UIColor.whiteColor;
462
+ }
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
+
497
+ - (void)setViewMode:(NSString *)viewMode {
498
+ NSString *normalized = [viewMode isEqualToString:@"single"] ? @"single" : @"continuous";
499
+ if ([_viewMode isEqualToString:normalized]) return;
500
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
501
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
502
+ self.suppressScaleSynchronization = YES;
503
+ PDFPage *currentPage = self.pdfView.currentPage;
504
+ _viewMode = normalized;
505
+ self.pdfView.displayMode = [normalized isEqualToString:@"single"]
506
+ ? kPDFDisplaySinglePage
507
+ : kPDFDisplaySinglePageContinuous;
508
+ _zoom = desiredZoom;
509
+ [self updateFitScalePreservingViewport];
510
+ if (currentPage) {
511
+ [self.pdfView goToPage:currentPage];
512
+ } else {
513
+ [self applyCurrentPage];
514
+ }
515
+ _zoom = desiredZoom;
516
+ [self applyNormalizedZoom];
517
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
518
+ }
519
+
520
+ - (void)setCurrentPage:(NSInteger)currentPage {
521
+ _currentPage = MAX(1, currentPage);
522
+ [self applyCurrentPage];
523
+ }
524
+
525
+ - (void)setZoom:(CGFloat)zoom {
526
+ if (!isfinite(zoom)) return;
527
+ CGFloat normalized = [self clampedZoom:zoom];
528
+ CGFloat currentNativeZoom = [self normalizedZoomForPdfView];
529
+ _zoom = normalized;
530
+ if (currentNativeZoom > 0 && fabs(currentNativeZoom - normalized) <= 0.015) {
531
+ self.lastEmittedZoom = normalized;
532
+ return;
533
+ }
534
+ [self applyNormalizedZoom];
535
+ self.lastEmittedZoom = normalized;
536
+ }
537
+
538
+ - (void)handleStoredDocumentChanged:(NSNotification *)notification {
539
+ NSString *changedEngineId = [notification.userInfo[PapyrusEngineStoreEngineIdKey] copy];
540
+ if (changedEngineId.length == 0) return;
541
+
542
+ __weak typeof(self) weakSelf = self;
543
+ dispatch_async(dispatch_get_main_queue(), ^{
544
+ typeof(self) strongSelf = weakSelf;
545
+ if (!strongSelf || ![changedEngineId isEqualToString:strongSelf.engineId]) return;
546
+ [strongSelf reloadDocumentFromStore];
547
+ });
548
+ }
549
+
550
+ - (void)reloadDocumentFromStore {
551
+ NSAssert(NSThread.isMainThread, @"PDFView must only be updated on the main thread");
552
+ PDFDocument *document = self.engineId.length > 0
553
+ ? [[PapyrusEngineStore shared] documentForEngine:self.engineId]
554
+ : nil;
555
+ if (self.pdfView.document == document) {
556
+ [self applyCurrentPage];
557
+ [self rebuildSearchHighlights];
558
+ [self reconcilePapyrusAnnotations];
559
+ [self reconcileInkOverlays];
560
+ return;
561
+ }
562
+
563
+ [self dismissAnnotationMenuForDocumentChange];
564
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
565
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
566
+ self.suppressScaleSynchronization = YES;
567
+ self.lastVisiblePagesSignature = nil;
568
+ self.lastEmittedPage = NSNotFound;
569
+ [self resetInkOverlaysForDocumentChange];
570
+ [self clearPapyrusAnnotationsForDocument:self.pdfView.document];
571
+ [self clearCurrentSelection];
572
+ self.pdfView.document = document;
573
+ if (!document) {
574
+ [self rebuildSearchHighlights];
575
+ [self reconcilePapyrusAnnotations];
576
+ self.lastEmittedZoom = NAN;
577
+ _zoom = desiredZoom;
578
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
579
+ return;
580
+ }
581
+
582
+ [self configureDisplayMode];
583
+ self.pdfView.autoScales = YES;
584
+ [self.pdfView layoutDocumentView];
585
+ [self updateScaleLimitsForFitScale:self.pdfView.scaleFactorForSizeToFit];
586
+ self.pdfView.autoScales = NO;
587
+ _zoom = desiredZoom;
588
+ [self applyNormalizedZoom];
589
+ [self applyCurrentPage];
590
+ _zoom = desiredZoom;
591
+ [self applyNormalizedZoom];
592
+ [self refreshScrollViewObservation];
593
+ [self emitVisiblePagesIfNeeded];
594
+ [self rebuildSearchHighlights];
595
+ [self reconcilePapyrusAnnotations];
596
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
597
+ }
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
+
1461
+ - (void)configureDisplayMode {
1462
+ self.pdfView.displayBox = kPDFDisplayBoxCropBox;
1463
+ self.pdfView.displayDirection = kPDFDisplayDirectionVertical;
1464
+ self.pdfView.displaysPageBreaks = YES;
1465
+ self.pdfView.displayMode = [self.viewMode isEqualToString:@"single"]
1466
+ ? kPDFDisplaySinglePage
1467
+ : kPDFDisplaySinglePageContinuous;
1468
+ }
1469
+
1470
+ - (void)updateFitScalePreservingViewport {
1471
+ if (!self.pdfView.document || CGRectGetWidth(self.bounds) <= 0 || CGRectGetHeight(self.bounds) <= 0) return;
1472
+
1473
+ CGFloat desiredZoom = [self clampedZoom:self.zoom];
1474
+ BOOL wasSuppressingScaleSynchronization = self.suppressScaleSynchronization;
1475
+ self.suppressScaleSynchronization = YES;
1476
+ PDFPage *currentPage = self.pdfView.currentPage;
1477
+ self.pdfView.autoScales = YES;
1478
+ [self.pdfView layoutDocumentView];
1479
+ [self updateScaleLimitsForFitScale:self.pdfView.scaleFactorForSizeToFit];
1480
+ self.pdfView.autoScales = NO;
1481
+ _zoom = desiredZoom;
1482
+ [self applyNormalizedZoom];
1483
+
1484
+ if (currentPage) {
1485
+ [self.pdfView goToPage:currentPage];
1486
+ } else {
1487
+ [self applyCurrentPage];
1488
+ }
1489
+ _zoom = desiredZoom;
1490
+ [self applyNormalizedZoom];
1491
+ self.suppressScaleSynchronization = wasSuppressingScaleSynchronization;
1492
+ }
1493
+
1494
+ - (void)updateScaleLimitsForFitScale:(CGFloat)fitScale {
1495
+ if (!isfinite(fitScale) || fitScale <= 0) return;
1496
+ self.pdfView.minScaleFactor = fitScale * PapyrusPdfMinimumZoom;
1497
+ self.pdfView.maxScaleFactor = fitScale * PapyrusPdfMaximumZoom;
1498
+ }
1499
+
1500
+ - (void)applyNormalizedZoom {
1501
+ CGFloat fitScale = self.pdfView.scaleFactorForSizeToFit;
1502
+ if (!isfinite(fitScale) || fitScale <= 0) return;
1503
+ [self updateScaleLimitsForFitScale:fitScale];
1504
+
1505
+ CGFloat targetScale = fitScale * [self clampedZoom:self.zoom];
1506
+ targetScale = MAX(self.pdfView.minScaleFactor,
1507
+ MIN(self.pdfView.maxScaleFactor, targetScale));
1508
+ if (fabs(self.pdfView.scaleFactor - targetScale) > 0.001) {
1509
+ self.pdfView.scaleFactor = targetScale;
1510
+ }
1511
+ }
1512
+
1513
+ - (CGFloat)normalizedZoomForPdfView {
1514
+ CGFloat fitScale = self.pdfView.scaleFactorForSizeToFit;
1515
+ if (!isfinite(fitScale) || fitScale <= 0) return 0;
1516
+ CGFloat normalized = self.pdfView.scaleFactor / fitScale;
1517
+ return isfinite(normalized) ? [self clampedZoom:normalized] : 0;
1518
+ }
1519
+
1520
+ - (CGFloat)clampedZoom:(CGFloat)zoom {
1521
+ return MAX(PapyrusPdfMinimumZoom, MIN(PapyrusPdfMaximumZoom, zoom));
1522
+ }
1523
+
1524
+ - (void)applyCurrentPage {
1525
+ PDFDocument *document = self.pdfView.document;
1526
+ if (!document || document.pageCount <= 0 || self.currentPage <= 0) return;
1527
+ NSInteger targetPage = MAX(1, MIN(self.currentPage, document.pageCount));
1528
+ _currentPage = targetPage;
1529
+ PDFPage *page = [document pageAtIndex:targetPage - 1];
1530
+ if (page && self.pdfView.currentPage != page) {
1531
+ [self.pdfView goToPage:page];
1532
+ }
1533
+ }
1534
+
1535
+ - (void)handlePdfPageChanged:(NSNotification *)notification {
1536
+ if (notification.object != self.pdfView) return;
1537
+ [self updateInkCanvasInputAndPicker];
1538
+ [self emitCurrentPageIfNeeded];
1539
+ [self emitVisiblePagesIfNeeded];
1540
+ }
1541
+
1542
+ - (void)emitCurrentPageIfNeeded {
1543
+ PDFDocument *document = self.pdfView.document;
1544
+ PDFPage *page = self.pdfView.currentPage;
1545
+ if (!document || !page) return;
1546
+ NSInteger pageNumber = [document indexForPage:page] + 1;
1547
+ if (pageNumber <= 0 || pageNumber == self.lastEmittedPage) return;
1548
+
1549
+ _currentPage = pageNumber;
1550
+ self.lastEmittedPage = pageNumber;
1551
+ if (self.onPageChange) {
1552
+ self.onPageChange(@{@"page" : @(pageNumber)});
1553
+ }
1554
+ }
1555
+
1556
+ - (void)handlePdfScaleChanged:(NSNotification *)notification {
1557
+ if (notification.object != self.pdfView) return;
1558
+ if (self.suppressScaleSynchronization) return;
1559
+ CGFloat normalized = [self normalizedZoomForPdfView];
1560
+ if (normalized <= 0) return;
1561
+ _zoom = normalized;
1562
+ if (self.zoomEventScheduled) return;
1563
+
1564
+ self.zoomEventScheduled = YES;
1565
+ __weak typeof(self) weakSelf = self;
1566
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
1567
+ (int64_t)(PapyrusPdfZoomEventInterval * NSEC_PER_SEC)),
1568
+ dispatch_get_main_queue(), ^{
1569
+ typeof(self) strongSelf = weakSelf;
1570
+ if (!strongSelf) return;
1571
+ strongSelf.zoomEventScheduled = NO;
1572
+ [strongSelf emitZoomIfNeeded];
1573
+ });
1574
+ }
1575
+
1576
+ - (void)emitZoomIfNeeded {
1577
+ CGFloat normalized = [self normalizedZoomForPdfView];
1578
+ if (normalized <= 0) return;
1579
+ if (isfinite(self.lastEmittedZoom) &&
1580
+ fabs(normalized - self.lastEmittedZoom) <= PapyrusPdfZoomEventTolerance) {
1581
+ return;
1582
+ }
1583
+
1584
+ _zoom = normalized;
1585
+ self.lastEmittedZoom = normalized;
1586
+ if (self.onZoomChange) {
1587
+ self.onZoomChange(@{@"zoom" : @(normalized)});
1588
+ }
1589
+ }
1590
+
1591
+ - (void)handlePdfVisiblePagesChanged:(NSNotification *)notification {
1592
+ if (notification.object != self.pdfView) return;
1593
+ [self emitVisiblePagesIfNeeded];
1594
+ }
1595
+
1596
+ - (void)handlePdfSelectionChanged:(NSNotification *)notification {
1597
+ if (notification.object != self.pdfView) return;
1598
+ [self emitCurrentSelectionIfNeeded];
1599
+ }
1600
+
1601
+ - (void)emitCurrentSelectionIfNeeded {
1602
+ PDFSelection *selection = self.pdfView.currentSelection;
1603
+ NSString *text = selection.string ?: @"";
1604
+ PDFDocument *document = self.pdfView.document;
1605
+ PDFPage *page = selection.pages.firstObject;
1606
+ NSInteger pageIndex = document && page ? [document indexForPage:page] : NSNotFound;
1607
+ if (!document || !page || pageIndex == NSNotFound || text.length == 0 ||
1608
+ [text stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet].length == 0) {
1609
+ [self emitSelectionClearedIfNeeded];
1610
+ return;
1611
+ }
1612
+
1613
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1614
+ if (CGRectIsEmpty(pageBounds)) {
1615
+ [self emitSelectionClearedIfNeeded];
1616
+ return;
1617
+ }
1618
+
1619
+ NSMutableArray<NSDictionary *> *rects = [NSMutableArray array];
1620
+ for (PDFSelection *line in selection.selectionsByLine) {
1621
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1622
+ [line boundsForPage:page], pageBounds);
1623
+ if (normalizedRect) [rects addObject:normalizedRect];
1624
+ }
1625
+
1626
+ if (rects.count == 0) {
1627
+ NSDictionary *normalizedRect = PapyrusNormalizedSelectionRect(
1628
+ [selection boundsForPage:page], pageBounds);
1629
+ if (normalizedRect) [rects addObject:normalizedRect];
1630
+ }
1631
+
1632
+ NSString *signature = [NSString stringWithFormat:@"%ld|%@|%@", (long)pageIndex, text, rects];
1633
+ if (self.lastSelectionWasActive && [signature isEqualToString:self.lastSelectionSignature]) return;
1634
+ self.lastSelectionWasActive = YES;
1635
+ self.lastSelectionPageIndex = pageIndex;
1636
+ self.lastSelectionSignature = signature;
1637
+ if (self.onTextSelected) {
1638
+ self.onTextSelected(@{@"text" : text, @"pageIndex" : @(pageIndex), @"rects" : rects});
1639
+ }
1640
+ [self scheduleSelectionEditMenuForSignature:signature];
1641
+ }
1642
+
1643
+ - (void)emitSelectionClearedIfNeeded {
1644
+ if (!self.lastSelectionWasActive) return;
1645
+ self.selectionMenuGeneration += 1;
1646
+ if (@available(iOS 16.0, *)) {
1647
+ [self.editMenuInteraction dismissMenu];
1648
+ }
1649
+ NSInteger pageIndex = self.lastSelectionPageIndex;
1650
+ if (pageIndex == NSNotFound) pageIndex = MAX(0, self.currentPage - 1);
1651
+ self.lastSelectionWasActive = NO;
1652
+ self.lastSelectionSignature = nil;
1653
+ self.lastSelectionPageIndex = NSNotFound;
1654
+ if (self.onTextSelected) {
1655
+ self.onTextSelected(@{@"text" : @"", @"pageIndex" : @(pageIndex), @"rects" : @[]});
1656
+ }
1657
+ }
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
+
1881
+ - (void)clearCurrentSelection {
1882
+ if (self.pdfView.currentSelection) {
1883
+ self.pdfView.currentSelection = nil;
1884
+ }
1885
+ [self emitSelectionClearedIfNeeded];
1886
+ }
1887
+
1888
+ - (void)emitVisiblePagesIfNeeded {
1889
+ PDFDocument *document = self.pdfView.document;
1890
+ if (!document || self.pdfView.bounds.size.width <= 0 || self.pdfView.bounds.size.height <= 0) return;
1891
+
1892
+ NSMutableArray<NSDictionary *> *pages = [NSMutableArray array];
1893
+ NSMutableArray<NSString *> *signatureParts = [NSMutableArray array];
1894
+ for (PDFPage *page in self.pdfView.visiblePages) {
1895
+ NSInteger pageIndex = [document indexForPage:page];
1896
+ if (pageIndex == NSNotFound) continue;
1897
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
1898
+ CGRect viewBounds = [self.pdfView convertRect:pageBounds fromPage:page];
1899
+ CGRect intersection = CGRectIntersection(self.pdfView.bounds, viewBounds);
1900
+ CGFloat pageArea = CGRectGetWidth(viewBounds) * CGRectGetHeight(viewBounds);
1901
+ CGFloat visibleArea = CGRectIsNull(intersection)
1902
+ ? 0
1903
+ : CGRectGetWidth(intersection) * CGRectGetHeight(intersection);
1904
+ if (!isfinite(pageArea) || pageArea <= 0 || visibleArea <= 0) continue;
1905
+
1906
+ CGFloat visibleRatio = MIN(1.0, MAX(0.0, visibleArea / pageArea));
1907
+ if (visibleRatio <= 0) continue;
1908
+ [pages addObject:@{@"pageIndex" : @(pageIndex), @"visibleRatio" : @(visibleRatio)}];
1909
+ NSInteger bucket = (NSInteger)llround(visibleRatio * 20.0);
1910
+ [signatureParts addObject:[NSString stringWithFormat:@"%ld:%ld", (long)pageIndex, (long)bucket]];
1911
+ }
1912
+
1913
+ if (pages.count == 0) return;
1914
+ NSString *signature = [signatureParts componentsJoinedByString:@"|"];
1915
+ if ([signature isEqualToString:self.lastVisiblePagesSignature]) return;
1916
+ self.lastVisiblePagesSignature = signature;
1917
+ if (self.onVisiblePagesChange) {
1918
+ self.onVisiblePagesChange(@{@"pages" : pages});
1919
+ }
1920
+ }
1921
+
1922
+ - (UIScrollView *)findScrollViewInView:(UIView *)view {
1923
+ for (UIView *subview in view.subviews) {
1924
+ if ([subview isKindOfClass:[UIScrollView class]]) {
1925
+ return (UIScrollView *)subview;
1926
+ }
1927
+ UIScrollView *nested = [self findScrollViewInView:subview];
1928
+ if (nested) return nested;
1929
+ }
1930
+ return nil;
1931
+ }
1932
+
1933
+ - (void)refreshScrollViewObservation {
1934
+ UIScrollView *scrollView = [self findScrollViewInView:self.pdfView];
1935
+ if (scrollView == self.observedScrollView) return;
1936
+ [self stopObservingScrollView];
1937
+ self.observedScrollView = scrollView;
1938
+ if (!scrollView) return;
1939
+
1940
+ @try {
1941
+ [scrollView addObserver:self
1942
+ forKeyPath:@"contentOffset"
1943
+ options:NSKeyValueObservingOptionNew
1944
+ context:PapyrusPdfScrollObservationContext];
1945
+ } @catch (__unused NSException *exception) {
1946
+ self.observedScrollView = nil;
1947
+ }
1948
+ }
1949
+
1950
+ - (void)stopObservingScrollView {
1951
+ UIScrollView *scrollView = self.observedScrollView;
1952
+ if (!scrollView) return;
1953
+ @try {
1954
+ [scrollView removeObserver:self
1955
+ forKeyPath:@"contentOffset"
1956
+ context:PapyrusPdfScrollObservationContext];
1957
+ } @catch (__unused NSException *exception) {
1958
+ }
1959
+ self.observedScrollView = nil;
1960
+ }
1961
+
1962
+ - (void)observeValueForKeyPath:(NSString *)keyPath
1963
+ ofObject:(id)object
1964
+ change:(NSDictionary<NSKeyValueChangeKey, id> *)change
1965
+ context:(void *)context {
1966
+ if (context != PapyrusPdfScrollObservationContext) {
1967
+ [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
1968
+ return;
1969
+ }
1970
+ if (![keyPath isEqualToString:@"contentOffset"]) return;
1971
+ if (!NSThread.isMainThread) {
1972
+ __weak typeof(self) weakSelf = self;
1973
+ dispatch_async(dispatch_get_main_queue(), ^{
1974
+ typeof(self) strongSelf = weakSelf;
1975
+ if (strongSelf && object == strongSelf.observedScrollView) {
1976
+ UIScrollView *scrollView = strongSelf.observedScrollView;
1977
+ [strongSelf scheduleScrollEventWithOffsetY:scrollView.contentOffset.y];
1978
+ }
1979
+ });
1980
+ return;
1981
+ }
1982
+ if (object != self.observedScrollView) return;
1983
+ UIScrollView *scrollView = self.observedScrollView;
1984
+ CGFloat offsetY = scrollView.contentOffset.y;
1985
+ [self scheduleScrollEventWithOffsetY:offsetY];
1986
+ }
1987
+
1988
+ - (void)scheduleScrollEventWithOffsetY:(CGFloat)offsetY {
1989
+ self.pendingScrollOffsetY = offsetY;
1990
+ CFTimeInterval now = CACurrentMediaTime();
1991
+ CFTimeInterval elapsed = now - self.lastScrollEventTime;
1992
+ if (elapsed >= PapyrusPdfScrollEventInterval && !self.scrollEventScheduled) {
1993
+ [self emitScrollEvent];
1994
+ return;
1995
+ }
1996
+ if (self.scrollEventScheduled) return;
1997
+
1998
+ self.scrollEventScheduled = YES;
1999
+ CFTimeInterval delay = MAX(0, PapyrusPdfScrollEventInterval - elapsed);
2000
+ __weak typeof(self) weakSelf = self;
2001
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
2002
+ dispatch_get_main_queue(), ^{
2003
+ typeof(self) strongSelf = weakSelf;
2004
+ if (!strongSelf) return;
2005
+ strongSelf.scrollEventScheduled = NO;
2006
+ [strongSelf emitScrollEvent];
2007
+ });
2008
+ }
2009
+
2010
+ - (void)emitScrollEvent {
2011
+ self.lastScrollEventTime = CACurrentMediaTime();
2012
+ if (self.onScroll) {
2013
+ self.onScroll(@{@"offsetY" : @(self.pendingScrollOffsetY)});
2014
+ }
2015
+ }
2016
+
2017
+ - (void)handleDocumentTap:(UITapGestureRecognizer *)recognizer {
2018
+ if (recognizer.state != UIGestureRecognizerStateEnded) return;
2019
+ if ([self.activeTool isEqualToString:@"ink"]) return;
2020
+ PDFDocument *document = self.pdfView.document;
2021
+ if (!document) return;
2022
+
2023
+ CGPoint viewPoint = [recognizer locationInView:self.pdfView];
2024
+ PDFPage *page = [self.pdfView pageForPoint:viewPoint nearest:YES];
2025
+ if (!page) return;
2026
+ CGRect pageBounds = [page boundsForBox:kPDFDisplayBoxCropBox];
2027
+ if (CGRectGetWidth(pageBounds) <= 0 || CGRectGetHeight(pageBounds) <= 0) return;
2028
+ CGPoint pagePoint = [self.pdfView convertPoint:viewPoint toPage:page];
2029
+ CGFloat x = (pagePoint.x - CGRectGetMinX(pageBounds)) / CGRectGetWidth(pageBounds);
2030
+ CGFloat y = 1.0 - ((pagePoint.y - CGRectGetMinY(pageBounds)) / CGRectGetHeight(pageBounds));
2031
+ NSInteger pageIndex = [document indexForPage:page];
2032
+ if (pageIndex == NSNotFound) return;
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
+
2101
+ if (self.onTap) {
2102
+ self.onTap(@{
2103
+ @"pageIndex" : @(pageIndex),
2104
+ @"x" : @(normalizedPoint.x),
2105
+ @"y" : @(normalizedPoint.y)
2106
+ });
2107
+ }
2108
+ }
2109
+
2110
+ - (void)handleDocumentDoubleTap:(UITapGestureRecognizer *)recognizer {
2111
+ if (recognizer.state != UIGestureRecognizerStateEnded) return;
2112
+ if ([self.activeTool isEqualToString:@"ink"]) return;
2113
+ PDFDocument *document = self.pdfView.document;
2114
+ if (!document) return;
2115
+
2116
+ CGPoint viewPoint = [recognizer locationInView:self.pdfView];
2117
+ PDFPage *page = [self.pdfView pageForPoint:viewPoint nearest:YES];
2118
+ if (!page) return;
2119
+ CGPoint pagePoint = [self.pdfView convertPoint:viewPoint toPage:page];
2120
+ PDFSelection *selection = [page selectionForWordAtPoint:pagePoint];
2121
+ self.pdfView.currentSelection = selection;
2122
+ [self emitCurrentSelectionIfNeeded];
2123
+ }
2124
+
2125
+ - (BOOL)selectionContainsViewPoint:(CGPoint)viewPoint {
2126
+ PDFSelection *selection = self.pdfView.currentSelection;
2127
+ if (!selection) return NO;
2128
+
2129
+ NSArray<PDFSelection *> *lines = selection.selectionsByLine;
2130
+ if (lines.count == 0) lines = @[selection];
2131
+ for (PDFPage *page in selection.pages) {
2132
+ for (PDFSelection *line in lines) {
2133
+ CGRect pageRect = [line boundsForPage:page];
2134
+ if (CGRectIsNull(pageRect) || CGRectIsEmpty(pageRect)) continue;
2135
+ CGRect viewRect = [self.pdfView convertRect:pageRect fromPage:page];
2136
+ if (CGRectContainsPoint(CGRectInset(viewRect, -6, -6), viewPoint)) return YES;
2137
+ }
2138
+ }
2139
+ return NO;
2140
+ }
2141
+
2142
+ - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
2143
+ shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
2144
+ return YES;
2145
+ }
2146
+
2147
+ @end