@papyrus-sdk/engine-native 0.2.23 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,21 @@
1
1
  #import "PapyrusComicDocumentView.h"
2
+ #import "PapyrusComicZoomGeometry.h"
2
3
  #import "../vendor/libarchive/PapyrusComicArchive.h"
3
4
  #import <ImageIO/ImageIO.h>
4
5
  #import <math.h>
6
+ #import <os/log.h>
7
+ #import <os/signpost.h>
5
8
 
6
9
  static NSString * const PapyrusComicCellId = @"PapyrusComicPageCell";
10
+ static os_log_t PapyrusComicZoomSignpostLog(void) {
11
+ static os_log_t log;
12
+ static dispatch_once_t once;
13
+ dispatch_once(&once, ^{
14
+ log = os_log_create("com.papyrus.sdk", "ComicZoom");
15
+ });
16
+ return log;
17
+ }
18
+
7
19
  static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
8
20
  static NSCache<NSString *, UIImage *> *cache;
9
21
  static dispatch_once_t once;
@@ -66,9 +78,180 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
66
78
  }
67
79
  @end
68
80
 
81
+ @interface PapyrusComicContinuousLayout : UICollectionViewLayout
82
+ @property (nonatomic, assign) CGFloat zoomScale;
83
+ - (void)configureWithPageCount:(NSInteger)pageCount
84
+ viewportSize:(CGSize)viewportSize
85
+ fitPage:(BOOL)fitPage
86
+ imageSizes:(NSDictionary<NSNumber *, NSValue *> *)imageSizes;
87
+ - (void)updateImageSizes:(NSDictionary<NSNumber *, NSValue *> *)imageSizes;
88
+ @end
89
+
90
+ @interface PapyrusComicContinuousLayout ()
91
+ @property (nonatomic, assign) NSInteger pageCount;
92
+ @property (nonatomic, assign) CGSize viewportSize;
93
+ @property (nonatomic, assign) BOOL fitPage;
94
+ @property (nonatomic, copy) NSDictionary<NSNumber *, NSValue *> *imageSizes;
95
+ @property (nonatomic, strong) NSMutableData *prefixHeights;
96
+ @property (nonatomic, assign) BOOL geometryDirty;
97
+ @end
98
+
99
+ @implementation PapyrusComicContinuousLayout
100
+ - (instancetype)init {
101
+ self = [super init];
102
+ if (self) {
103
+ _zoomScale = 1.0;
104
+ _geometryDirty = YES;
105
+ _imageSizes = @{};
106
+ }
107
+ return self;
108
+ }
109
+
110
+ - (void)configureWithPageCount:(NSInteger)pageCount
111
+ viewportSize:(CGSize)viewportSize
112
+ fitPage:(BOOL)fitPage
113
+ imageSizes:(NSDictionary<NSNumber *, NSValue *> *)imageSizes {
114
+ NSInteger safePageCount = MAX(0, pageCount);
115
+ NSDictionary<NSNumber *, NSValue *> *safeImageSizes = imageSizes ?: @{};
116
+ BOOL changed = self.pageCount != safePageCount ||
117
+ !CGSizeEqualToSize(self.viewportSize, viewportSize) ||
118
+ self.fitPage != fitPage ||
119
+ ![self.imageSizes isEqualToDictionary:safeImageSizes];
120
+ if (!changed) return;
121
+ self.pageCount = safePageCount;
122
+ self.viewportSize = viewportSize;
123
+ self.fitPage = fitPage;
124
+ self.imageSizes = [safeImageSizes copy];
125
+ self.geometryDirty = YES;
126
+ [self invalidateLayout];
127
+ }
128
+
129
+ - (void)updateImageSizes:(NSDictionary<NSNumber *, NSValue *> *)imageSizes {
130
+ if (imageSizes.count == 0) return;
131
+ NSMutableDictionary<NSNumber *, NSValue *> *merged = [self.imageSizes mutableCopy] ?: [NSMutableDictionary dictionary];
132
+ const double *prefix = (const double *)self.prefixHeights.bytes;
133
+ NSUInteger count = (NSUInteger)MAX(0, self.pageCount);
134
+ BOOL hasPrefix = !self.geometryDirty && self.prefixHeights.length >= sizeof(double) * (count + 1);
135
+ NSMutableData *heightDeltasData = hasPrefix ? [NSMutableData dataWithLength:sizeof(double) * count] : nil;
136
+ double *heightDeltas = (double *)heightDeltasData.mutableBytes;
137
+ CGFloat width = MAX(1.0, self.viewportSize.width);
138
+ CGFloat height = MAX(1.0, self.viewportSize.height);
139
+
140
+ [imageSizes enumerateKeysAndObjectsUsingBlock:^(NSNumber *pageNumber, NSValue *sizeValue, BOOL *stop) {
141
+ #pragma unused(stop)
142
+ NSInteger page = pageNumber.integerValue;
143
+ if (page < 0 || (NSUInteger)page >= count) return;
144
+ NSValue *oldValue = merged[pageNumber];
145
+ if ([oldValue isEqual:sizeValue]) return;
146
+ CGSize size = sizeValue.CGSizeValue;
147
+ double nextHeight = PapyrusComicContinuousPageHeight(size.width, size.height,
148
+ width, height, self.fitPage, 1.0);
149
+ if (hasPrefix) {
150
+ double oldHeight = prefix[page + 1] - prefix[page];
151
+ heightDeltas[page] = nextHeight - oldHeight;
152
+ }
153
+ merged[pageNumber] = sizeValue;
154
+ }];
155
+
156
+ self.imageSizes = [merged copy];
157
+ if (!hasPrefix) {
158
+ self.geometryDirty = YES;
159
+ [self invalidateLayout];
160
+ return;
161
+ }
162
+
163
+ double *mutablePrefix = (double *)self.prefixHeights.mutableBytes;
164
+ PapyrusComicContinuousApplyHeightDeltas(mutablePrefix, heightDeltas, count);
165
+ [self invalidateLayout];
166
+ }
167
+
168
+ - (void)setZoomScale:(CGFloat)zoomScale {
169
+ CGFloat safeZoom = PapyrusComicClampZoom(zoomScale);
170
+ if (fabs(safeZoom - _zoomScale) < 0.0001) return;
171
+ _zoomScale = safeZoom;
172
+ // Page aspect ratios and prefix heights are unchanged by zoom. Invalidating
173
+ // asks UIKit for attributes only in its queried visible rect; it does not
174
+ // rebuild the document geometry cache for every pinch update.
175
+ [self invalidateLayout];
176
+ }
177
+
178
+ - (void)prepareLayout {
179
+ [super prepareLayout];
180
+ CGSize measuredViewport = self.collectionView.bounds.size;
181
+ if (measuredViewport.width > 0 && !CGSizeEqualToSize(measuredViewport, self.viewportSize)) {
182
+ self.viewportSize = measuredViewport;
183
+ self.geometryDirty = YES;
184
+ }
185
+ if (!self.geometryDirty) return;
186
+
187
+ NSUInteger count = (NSUInteger)MAX(0, self.pageCount);
188
+ self.prefixHeights = [NSMutableData dataWithLength:sizeof(double) * (count + 1)];
189
+ double *prefix = (double *)self.prefixHeights.mutableBytes;
190
+ prefix[0] = 0.0;
191
+ CGFloat width = MAX(1.0, self.viewportSize.width);
192
+ CGFloat height = MAX(1.0, self.viewportSize.height);
193
+ for (NSUInteger page = 0; page < count; page++) {
194
+ CGSize imageSize = self.imageSizes[@(page)] ? self.imageSizes[@(page)].CGSizeValue : CGSizeZero;
195
+ double pageHeight = PapyrusComicContinuousPageHeight(imageSize.width, imageSize.height,
196
+ width, height, self.fitPage, 1.0);
197
+ prefix[page + 1] = prefix[page] + pageHeight;
198
+ }
199
+ self.geometryDirty = NO;
200
+ }
201
+
202
+ - (CGSize)collectionViewContentSize {
203
+ if (self.geometryDirty) [self prepareLayout];
204
+ const double *prefix = (const double *)self.prefixHeights.bytes;
205
+ NSUInteger count = (NSUInteger)MAX(0, self.pageCount);
206
+ return CGSizeMake(PapyrusComicContinuousContentWidth(self.viewportSize.width, self.zoomScale),
207
+ PapyrusComicContinuousDocumentHeight(prefix, count, self.zoomScale));
208
+ }
209
+
210
+ - (UICollectionViewLayoutAttributes *)layoutAttributesForPage:(NSUInteger)page {
211
+ if (self.geometryDirty) [self prepareLayout];
212
+ NSUInteger count = (NSUInteger)MAX(0, self.pageCount);
213
+ const double *prefix = (const double *)self.prefixHeights.bytes;
214
+ PapyrusComicLayoutFrame frame = PapyrusComicContinuousPageFrame(prefix, count, page,
215
+ self.viewportSize.width, self.zoomScale);
216
+ if (frame.width <= 0.0 || frame.height <= 0.0) return nil;
217
+ NSIndexPath *indexPath = [NSIndexPath indexPathForItem:(NSInteger)page inSection:0];
218
+ UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
219
+ attributes.frame = CGRectMake(frame.originX, frame.originY, frame.width, frame.height);
220
+ return attributes;
221
+ }
222
+
223
+ - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
224
+ if (indexPath.section != 0 || indexPath.item < 0 || indexPath.item >= self.pageCount) return nil;
225
+ return [self layoutAttributesForPage:(NSUInteger)indexPath.item];
226
+ }
227
+
228
+ - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
229
+ if (self.geometryDirty) [self prepareLayout];
230
+ NSUInteger count = (NSUInteger)MAX(0, self.pageCount);
231
+ const double *prefix = (const double *)self.prefixHeights.bytes;
232
+ NSUInteger page = PapyrusComicContinuousFirstVisiblePage(prefix, count,
233
+ CGRectGetMinY(rect), self.zoomScale);
234
+ if (page >= count) return @[];
235
+
236
+ NSMutableArray<UICollectionViewLayoutAttributes *> *attributes = [NSMutableArray array];
237
+ while (page < count) {
238
+ UICollectionViewLayoutAttributes *attribute = [self layoutAttributesForPage:page];
239
+ if (!attribute || CGRectGetMinY(attribute.frame) >= CGRectGetMaxY(rect)) break;
240
+ if (CGRectIntersectsRect(attribute.frame, rect)) [attributes addObject:attribute];
241
+ page++;
242
+ }
243
+ return attributes;
244
+ }
245
+
246
+ - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
247
+ return !CGSizeEqualToSize(newBounds.size, self.viewportSize);
248
+ }
249
+ @end
250
+
69
251
  @interface PapyrusComicDocumentView () <UIGestureRecognizerDelegate>
70
252
  @property (nonatomic, strong) UICollectionView *collectionView;
71
253
  @property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
254
+ @property (nonatomic, strong) PapyrusComicContinuousLayout *continuousLayout;
72
255
  @property (nonatomic, strong) UIPinchGestureRecognizer *pinchRecognizer;
73
256
  @property (nonatomic, strong) UITapGestureRecognizer *doubleTapRecognizer;
74
257
  @property (nonatomic, strong) UIPanGestureRecognizer *pagePanRecognizer;
@@ -82,6 +265,9 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
82
265
  @property (nonatomic, assign) BOOL pendingNavigation;
83
266
  @property (nonatomic, assign) CGPoint panOffset;
84
267
  @property (nonatomic, assign) CGPoint panGestureStartOffset;
268
+ - (void)updateContinuousLayoutGeometry;
269
+ - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
270
+ - (CGSize)pageSizeAtIndex:(NSInteger)page;
85
271
  @end
86
272
 
87
273
  @implementation PapyrusComicDocumentView
@@ -104,6 +290,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
104
290
  _flowLayout = [[UICollectionViewFlowLayout alloc] init];
105
291
  _flowLayout.minimumLineSpacing = 0;
106
292
  _flowLayout.minimumInteritemSpacing = 0;
293
+ _continuousLayout = [[PapyrusComicContinuousLayout alloc] init];
107
294
  _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:_flowLayout];
108
295
  _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
109
296
  _collectionView.dataSource = self;
@@ -132,10 +319,27 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
132
319
  [_collectionView addGestureRecognizer:_pagePanRecognizer];
133
320
  [self applyLayoutMode];
134
321
  [self applyTheme];
322
+ [self updateContinuousLayoutGeometry];
135
323
  }
136
324
  return self;
137
325
  }
138
326
 
327
+ - (void)updateContinuousLayoutGeometry {
328
+ CGSize viewport = self.viewportSize;
329
+ if (viewport.width <= 0 || viewport.height <= 0) viewport = self.collectionView.bounds.size;
330
+ // Recover dimensions already held in the bounded image cache only when
331
+ // document geometry changes, never on each pinch update.
332
+ for (NSInteger page = 0; page < self.pageCount; page++) [self pageSizeAtIndex:page];
333
+ [self.continuousLayout configureWithPageCount:self.pageCount
334
+ viewportSize:viewport
335
+ fitPage:[self.fitMode isEqualToString:@"page"]
336
+ imageSizes:self.pageSizes];
337
+ }
338
+
339
+ - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
340
+ return [self.collectionView.collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath];
341
+ }
342
+
139
343
  // Anchors reference the page, not an absolute document offset. Heights can change
140
344
  // above the viewport as images arrive; bitmap eviction must not change geometry.
141
345
  - (NSDictionary *)captureScrollAnchorForViewport:(CGSize)viewport {
@@ -145,7 +349,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
145
349
  UICollectionViewLayoutAttributes *nearest = nil;
146
350
  CGFloat distance = CGFLOAT_MAX;
147
351
  for (NSIndexPath *path in self.collectionView.indexPathsForVisibleItems) {
148
- UICollectionViewLayoutAttributes *attributes = [self.flowLayout layoutAttributesForItemAtIndexPath:path];
352
+ UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:path];
149
353
  if (!attributes) continue;
150
354
  CGFloat next = ABS(CGRectGetMidY(attributes.frame) - center.y);
151
355
  if (next < distance) { nearest = attributes; distance = next; }
@@ -153,7 +357,10 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
153
357
  }
154
358
  if (!nearest || nearest.frame.size.height <= 0) return nil;
155
359
  return @{ @"pageIndex": @([self logicalPageForItem:nearest.indexPath.item]),
156
- @"fraction": @(MAX(0, MIN(1, (center.y - nearest.frame.origin.y) / nearest.frame.size.height))) };
360
+ @"fractionX": @(PapyrusComicZoomAnchorFraction(self.collectionView.contentOffset.x, viewport.width / 2,
361
+ nearest.frame.origin.x, nearest.frame.size.width)),
362
+ @"fraction": @(PapyrusComicZoomAnchorFraction(self.collectionView.contentOffset.y, viewport.height / 2,
363
+ nearest.frame.origin.y, nearest.frame.size.height)) };
157
364
  }
158
365
 
159
366
  - (void)restoreScrollAnchor:(NSDictionary *)anchor {
@@ -162,14 +369,19 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
162
369
  NSInteger page = [anchor[@"pageIndex"] integerValue];
163
370
  if (page < 0 || page >= self.pageCount) return;
164
371
  NSInteger item = [self itemForLogicalPage:page + 1];
165
- UICollectionViewLayoutAttributes *attributes = [self.flowLayout layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
372
+ UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
166
373
  if (!attributes) return;
167
- CGFloat y = attributes.frame.origin.y + [anchor[@"fraction"] doubleValue] * attributes.frame.size.height - self.collectionView.bounds.size.height / 2;
168
- CGFloat minimum = -self.collectionView.adjustedContentInset.top;
169
- CGFloat maximum = MAX(minimum, self.collectionView.contentSize.height - self.collectionView.bounds.size.height + self.collectionView.adjustedContentInset.bottom);
374
+ CGFloat x = PapyrusComicZoomAnchorOffset(attributes.frame.origin.x, attributes.frame.size.width,
375
+ [anchor[@"fractionX"] doubleValue], self.collectionView.bounds.size.width / 2,
376
+ self.collectionView.contentSize.width, self.collectionView.bounds.size.width,
377
+ self.collectionView.adjustedContentInset.left, self.collectionView.adjustedContentInset.right);
378
+ CGFloat y = PapyrusComicZoomAnchorOffset(attributes.frame.origin.y, attributes.frame.size.height,
379
+ [anchor[@"fraction"] doubleValue], self.collectionView.bounds.size.height / 2,
380
+ self.collectionView.contentSize.height, self.collectionView.bounds.size.height,
381
+ self.collectionView.adjustedContentInset.top, self.collectionView.adjustedContentInset.bottom);
170
382
  BOOL wasApplying = self.applyingProgrammaticPage;
171
383
  self.applyingProgrammaticPage = YES;
172
- [self.collectionView setContentOffset:CGPointMake(self.collectionView.contentOffset.x, MAX(minimum, MIN(maximum, y))) animated:NO];
384
+ [self.collectionView setContentOffset:CGPointMake(x, y) animated:NO];
173
385
  self.applyingProgrammaticPage = wasApplying;
174
386
  }
175
387
 
@@ -190,11 +402,16 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
190
402
  self.applyingProgrammaticPage = YES;
191
403
  self.viewportSize = size;
192
404
  self.flowLayout.itemSize = size;
193
- [self.flowLayout invalidateLayout];
405
+ if ([self.layoutMode isEqualToString:@"continuous"]) {
406
+ [self updateContinuousLayoutGeometry];
407
+ self.continuousLayout.zoomScale = self.zoom;
408
+ } else {
409
+ [self.flowLayout invalidateLayout];
410
+ }
194
411
  [self.collectionView layoutIfNeeded];
195
412
  for (PapyrusComicPageCell *cell in self.collectionView.visibleCells) {
196
413
  [self configureCell:cell withImage:cell.imageView.image];
197
- cell.imageView.transform = [self imageTransform];
414
+ [self applyImageTransformToCell:cell];
198
415
  }
199
416
  if (self.pendingNavigation || ![self.layoutMode isEqualToString:@"continuous"]) {
200
417
  [self scrollToCurrentPageAnimated:NO];
@@ -209,6 +426,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
209
426
  _engineId = [engineId copy];
210
427
  [self.pageSizes removeAllObjects];
211
428
  [self.pendingPageSizes removeAllObjects];
429
+ [self updateContinuousLayoutGeometry];
212
430
  @synchronized (self.reportedErrors) { [self.reportedErrors removeAllObjects]; }
213
431
  self.pendingNavigation = YES;
214
432
  [self.collectionView reloadData];
@@ -219,6 +437,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
219
437
  _documentGeneration = value;
220
438
  [self.pageSizes removeAllObjects];
221
439
  [self.pendingPageSizes removeAllObjects];
440
+ [self updateContinuousLayoutGeometry];
222
441
  @synchronized (self.reportedErrors) { [self.reportedErrors removeAllObjects]; }
223
442
  self.pendingNavigation = YES;
224
443
  [self.collectionView reloadData];
@@ -229,6 +448,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
229
448
  if (_pageCount == count) return;
230
449
  _pageCount = count;
231
450
  _currentPage = count > 0 ? MIN(self.requestedPage, count) : self.requestedPage;
451
+ [self updateContinuousLayoutGeometry];
232
452
  self.pendingNavigation = YES;
233
453
  [self.collectionView reloadData];
234
454
  [self scrollToCurrentPageAnimated:NO];
@@ -246,6 +466,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
246
466
  NSString *mode = [value isEqualToString:@"continuous"] ? @"continuous" : @"single";
247
467
  if ([_layoutMode isEqualToString:mode]) return;
248
468
  _layoutMode = mode;
469
+ self.panOffset = CGPointZero;
249
470
  [self applyLayoutMode];
250
471
  self.pendingNavigation = YES;
251
472
  [self.collectionView reloadData];
@@ -258,7 +479,8 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
258
479
  self.applyingProgrammaticPage = YES;
259
480
  NSDictionary *anchor = [self captureScrollAnchorForViewport:self.collectionView.bounds.size];
260
481
  _fitMode = mode;
261
- [self.flowLayout invalidateLayout];
482
+ if ([self.layoutMode isEqualToString:@"continuous"]) [self updateContinuousLayoutGeometry];
483
+ [self.collectionView.collectionViewLayout invalidateLayout];
262
484
  [self.collectionView reloadData];
263
485
  [self.collectionView layoutIfNeeded];
264
486
  if ([self.layoutMode isEqualToString:@"continuous"]) [self restoreScrollAnchor:anchor];
@@ -280,19 +502,118 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
280
502
  self.applyingProgrammaticPage = wasApplying;
281
503
  }
282
504
  - (void)setZoom:(CGFloat)value {
283
- _zoom = MAX(1, MIN(5, value));
284
- self.collectionView.panGestureRecognizer.enabled = _zoom <= 1.0;
285
- self.pagePanRecognizer.enabled = _zoom > 1.0;
286
- if (_zoom <= 1.0) self.panOffset = CGPointZero;
287
- for (PapyrusComicPageCell *cell in self.collectionView.visibleCells) {
288
- cell.imageView.transform = [self imageTransform];
505
+ CGFloat target = PapyrusComicClampZoom(value);
506
+ if (fabs(target - _zoom) < 0.0001) {
507
+ [self updateZoomGestureAvailability];
508
+ return;
289
509
  }
510
+ CGPoint focus = CGPointMake(self.collectionView.bounds.size.width / 2, self.collectionView.bounds.size.height / 2);
511
+ if ([self.layoutMode isEqualToString:@"continuous"]) [self applyContinuousZoom:target atFocus:focus];
512
+ else [self applySingleZoom:target atFocus:focus];
290
513
  }
291
514
 
292
515
  - (CGAffineTransform)imageTransform {
293
516
  CGAffineTransform transform = CGAffineTransformMakeTranslation(self.panOffset.x, self.panOffset.y);
294
517
  return CGAffineTransformScale(transform, self.zoom, self.zoom);
295
518
  }
519
+
520
+ - (void)applyImageTransformToCell:(PapyrusComicPageCell *)cell {
521
+ cell.imageView.transform = [self.layoutMode isEqualToString:@"continuous"] ? CGAffineTransformIdentity : [self imageTransform];
522
+ }
523
+
524
+ - (void)updateZoomGestureAvailability {
525
+ BOOL continuous = [self.layoutMode isEqualToString:@"continuous"];
526
+ BOOL collectionCanPan = continuous || self.zoom <= 1.0;
527
+ BOOL pageCanPan = !continuous && self.zoom > 1.0;
528
+ if (self.collectionView.panGestureRecognizer.enabled != collectionCanPan) {
529
+ self.collectionView.panGestureRecognizer.enabled = collectionCanPan;
530
+ }
531
+ if (self.pagePanRecognizer.enabled != pageCanPan) self.pagePanRecognizer.enabled = pageCanPan;
532
+ }
533
+
534
+ - (NSDictionary *)captureContinuousZoomAnchorAtFocus:(CGPoint)focus {
535
+ if (![self.layoutMode isEqualToString:@"continuous"] || self.pageCount <= 0) return nil;
536
+ CGPoint contentFocus = CGPointMake(self.collectionView.contentOffset.x + focus.x,
537
+ self.collectionView.contentOffset.y + focus.y);
538
+ UICollectionViewLayoutAttributes *nearest = nil;
539
+ CGFloat nearestDistance = CGFLOAT_MAX;
540
+ for (NSIndexPath *path in self.collectionView.indexPathsForVisibleItems) {
541
+ UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:path];
542
+ if (!attributes || attributes.frame.size.width <= 0 || attributes.frame.size.height <= 0) continue;
543
+ if (CGRectContainsPoint(attributes.frame, contentFocus)) { nearest = attributes; break; }
544
+ CGFloat dx = MAX(CGRectGetMinX(attributes.frame) - contentFocus.x, MAX(0, contentFocus.x - CGRectGetMaxX(attributes.frame)));
545
+ CGFloat dy = MAX(CGRectGetMinY(attributes.frame) - contentFocus.y, MAX(0, contentFocus.y - CGRectGetMaxY(attributes.frame)));
546
+ CGFloat distance = dx * dx + dy * dy;
547
+ if (distance < nearestDistance) { nearest = attributes; nearestDistance = distance; }
548
+ }
549
+ if (!nearest) return nil;
550
+ return @{ @"pageIndex": @([self logicalPageForItem:nearest.indexPath.item]),
551
+ @"fractionX": @(PapyrusComicZoomAnchorFraction(self.collectionView.contentOffset.x, focus.x,
552
+ nearest.frame.origin.x, nearest.frame.size.width)),
553
+ @"fractionY": @(PapyrusComicZoomAnchorFraction(self.collectionView.contentOffset.y, focus.y,
554
+ nearest.frame.origin.y, nearest.frame.size.height)) };
555
+ }
556
+
557
+ - (void)restoreContinuousZoomAnchor:(NSDictionary *)anchor atFocus:(CGPoint)focus {
558
+ if (!anchor || ![self.layoutMode isEqualToString:@"continuous"] || self.pendingNavigation) return;
559
+ NSInteger page = [anchor[@"pageIndex"] integerValue];
560
+ if (page < 0 || page >= self.pageCount) return;
561
+ NSInteger item = [self itemForLogicalPage:page + 1];
562
+ NSIndexPath *path = [NSIndexPath indexPathForItem:item inSection:0];
563
+ UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:path];
564
+ if (!attributes) return;
565
+ CGFloat x = PapyrusComicZoomAnchorOffset(attributes.frame.origin.x, attributes.frame.size.width,
566
+ [anchor[@"fractionX"] doubleValue], focus.x, self.collectionView.contentSize.width,
567
+ self.collectionView.bounds.size.width, self.collectionView.adjustedContentInset.left,
568
+ self.collectionView.adjustedContentInset.right);
569
+ CGFloat y = PapyrusComicZoomAnchorOffset(attributes.frame.origin.y, attributes.frame.size.height,
570
+ [anchor[@"fractionY"] doubleValue], focus.y, self.collectionView.contentSize.height,
571
+ self.collectionView.bounds.size.height, self.collectionView.adjustedContentInset.top,
572
+ self.collectionView.adjustedContentInset.bottom);
573
+ BOOL wasApplying = self.applyingProgrammaticPage;
574
+ self.applyingProgrammaticPage = YES;
575
+ [self.collectionView setContentOffset:CGPointMake(x, y) animated:NO];
576
+ self.applyingProgrammaticPage = wasApplying;
577
+ }
578
+
579
+ - (void)applyContinuousZoom:(CGFloat)target atFocus:(CGPoint)focus {
580
+ CGFloat next = PapyrusComicClampZoom(target);
581
+ if (fabs(next - self.zoom) < 0.0001) return;
582
+ os_log_t signpostLog = PapyrusComicZoomSignpostLog();
583
+ os_signpost_id_t signpostId = os_signpost_id_generate(signpostLog);
584
+ os_signpost_interval_begin(signpostLog, signpostId, "ContinuousZoom");
585
+ NSDictionary *anchor = [self captureContinuousZoomAnchorAtFocus:focus];
586
+ _zoom = next;
587
+ self.panOffset = CGPointZero;
588
+ [self updateZoomGestureAvailability];
589
+ BOOL wasApplying = self.applyingProgrammaticPage;
590
+ self.applyingProgrammaticPage = YES;
591
+ self.continuousLayout.zoomScale = next;
592
+ [self.collectionView layoutIfNeeded];
593
+ [self restoreContinuousZoomAnchor:anchor atFocus:focus];
594
+ self.applyingProgrammaticPage = wasApplying;
595
+ if (!wasApplying) [self emitVisiblePage];
596
+ os_signpost_interval_end(signpostLog, signpostId, "ContinuousZoom");
597
+ }
598
+
599
+ - (void)applySingleZoom:(CGFloat)target atFocus:(CGPoint)focus {
600
+ CGFloat previous = MAX(1, self.zoom);
601
+ CGFloat next = PapyrusComicClampZoom(target);
602
+ if (next <= 1.0) {
603
+ self.panOffset = CGPointZero;
604
+ } else {
605
+ CGFloat ratio = next / previous;
606
+ CGPoint center = CGPointMake(self.collectionView.bounds.size.width / 2, self.collectionView.bounds.size.height / 2);
607
+ CGFloat maxX = self.collectionView.bounds.size.width * (next - 1.0) / 2.0;
608
+ CGFloat maxY = self.collectionView.bounds.size.height * (next - 1.0) / 2.0;
609
+ CGFloat x = ratio * self.panOffset.x + (1 - ratio) * (focus.x - center.x);
610
+ CGFloat y = ratio * self.panOffset.y + (1 - ratio) * (focus.y - center.y);
611
+ self.panOffset = CGPointMake(MAX(-maxX, MIN(maxX, x)), MAX(-maxY, MIN(maxY, y)));
612
+ }
613
+ _zoom = next;
614
+ [self updateZoomGestureAvailability];
615
+ for (PapyrusComicPageCell *cell in self.collectionView.visibleCells) [self applyImageTransformToCell:cell];
616
+ }
296
617
  - (void)setPageTheme:(NSString *)value {
297
618
  _pageTheme = [value copy] ?: @"normal";
298
619
  [self applyTheme];
@@ -300,10 +621,23 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
300
621
 
301
622
  - (void)applyLayoutMode {
302
623
  BOOL continuous = [self.layoutMode isEqualToString:@"continuous"];
303
- self.flowLayout.scrollDirection = continuous ? UICollectionViewScrollDirectionVertical : UICollectionViewScrollDirectionHorizontal;
624
+ self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
625
+ self.flowLayout.itemSize = self.collectionView.bounds.size;
304
626
  self.collectionView.pagingEnabled = !continuous;
305
627
  self.collectionView.semanticContentAttribute = [self.readingDirection isEqualToString:@"rtl"] ? UISemanticContentAttributeForceRightToLeft : UISemanticContentAttributeForceLeftToRight;
306
- [self.flowLayout invalidateLayout];
628
+ if (continuous) {
629
+ [self updateContinuousLayoutGeometry];
630
+ self.continuousLayout.zoomScale = self.zoom;
631
+ if (self.collectionView.collectionViewLayout != self.continuousLayout) {
632
+ [self.collectionView setCollectionViewLayout:self.continuousLayout animated:NO];
633
+ }
634
+ } else {
635
+ if (self.collectionView.collectionViewLayout != self.flowLayout) {
636
+ [self.collectionView setCollectionViewLayout:self.flowLayout animated:NO];
637
+ }
638
+ [self.flowLayout invalidateLayout];
639
+ }
640
+ [self updateZoomGestureAvailability];
307
641
  }
308
642
 
309
643
  - (void)applyTheme {
@@ -367,7 +701,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
367
701
  cell.representedKey = key;
368
702
  cell.imageView.image = [PapyrusComicImageCache() objectForKey:key];
369
703
  [self configureCell:cell withImage:cell.imageView.image];
370
- cell.imageView.transform = [self imageTransform];
704
+ [self applyImageTransformToCell:cell];
371
705
  if (!cell.imageView.image && engineId.length > 0 && generation > 0) {
372
706
  NSInteger maximumEdge = MAX(1024, (NSInteger)MAX(self.bounds.size.width, self.bounds.size.height) * 2);
373
707
  dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
@@ -410,7 +744,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
410
744
  if ([cell.representedKey isEqualToString:key]) {
411
745
  cell.imageView.image = page;
412
746
  [self configureCell:cell withImage:page];
413
- cell.imageView.transform = [self imageTransform];
747
+ [self applyImageTransformToCell:cell];
414
748
  }
415
749
  });
416
750
  });
@@ -421,17 +755,21 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
421
755
  // Keep geometry fixed during the native gesture; one compensation happens at idle.
422
756
  - (void)applyPendingPageSizes {
423
757
  if (self.collectionView.dragging || self.collectionView.decelerating) return;
758
+ if (self.pinchRecognizer.state == UIGestureRecognizerStateBegan || self.pinchRecognizer.state == UIGestureRecognizerStateChanged) return;
424
759
  if (self.pendingViewportLayout) { [self setNeedsLayout]; [self layoutIfNeeded]; }
425
760
  if (self.pendingPageSizes.count == 0) return;
426
761
  NSDictionary *anchor = [self captureScrollAnchorForViewport:self.collectionView.bounds.size];
427
762
  BOOL wasApplying = self.applyingProgrammaticPage;
428
763
  self.applyingProgrammaticPage = YES;
764
+ NSDictionary<NSNumber *, NSValue *> *pageSizeUpdates = [self.pendingPageSizes copy];
429
765
  [self.pageSizes addEntriesFromDictionary:self.pendingPageSizes];
430
766
  [self.pendingPageSizes removeAllObjects];
431
- [self.flowLayout invalidateLayout];
767
+ [self.continuousLayout updateImageSizes:pageSizeUpdates];
768
+ [self.collectionView.collectionViewLayout invalidateLayout];
432
769
  [self.collectionView layoutIfNeeded];
433
770
  [self restoreScrollAnchor:anchor];
434
771
  self.applyingProgrammaticPage = wasApplying;
772
+ if (!wasApplying) [self emitVisiblePage];
435
773
  }
436
774
 
437
775
  - (CGSize)pageSizeAtIndex:(NSInteger)page {
@@ -445,16 +783,8 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
445
783
  }
446
784
 
447
785
  - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
448
- #pragma unused(layout)
449
- if (![self.layoutMode isEqualToString:@"continuous"]) return collectionView.bounds.size;
450
- NSInteger page = [self logicalPageForItem:indexPath.item];
451
- CGSize imageSize = [self pageSizeAtIndex:page];
452
- CGSize viewport = self.pendingViewportLayout && self.viewportSize.width > 0 ? self.viewportSize : collectionView.bounds.size;
453
- if (imageSize.width <= 0 || imageSize.height <= 0) return viewport;
454
- CGFloat width = viewport.width;
455
- CGFloat height = width * imageSize.height / imageSize.width;
456
- if ([self.fitMode isEqualToString:@"page"]) height = MIN(height, viewport.height);
457
- return CGSizeMake(width, MAX(1, height));
786
+ #pragma unused(layout, indexPath)
787
+ return collectionView.bounds.size;
458
788
  }
459
789
 
460
790
  - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
@@ -496,26 +826,20 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
496
826
  self.pinchRecognizer.state == UIGestureRecognizerStateChanged) return;
497
827
  CGFloat previous = MAX(1, self.zoom);
498
828
  CGFloat target = previous > 1.05 ? 1.0 : 2.0;
499
- CGPoint focus = [recognizer locationInView:self.collectionView];
500
- CGPoint center = CGPointMake(CGRectGetMidX(self.collectionView.bounds),
501
- CGRectGetMidY(self.collectionView.bounds));
502
- if (target <= 1.0) {
503
- self.panOffset = CGPointZero;
504
- } else {
505
- CGFloat ratio = target / previous;
506
- CGFloat maxX = self.collectionView.bounds.size.width * (target - 1.0) / 2.0;
507
- CGFloat maxY = self.collectionView.bounds.size.height * (target - 1.0) / 2.0;
508
- CGFloat x = ratio * self.panOffset.x + (1 - ratio) * (focus.x - center.x);
509
- CGFloat y = ratio * self.panOffset.y + (1 - ratio) * (focus.y - center.y);
510
- self.panOffset = CGPointMake(MAX(-maxX, MIN(maxX, x)), MAX(-maxY, MIN(maxY, y)));
511
- }
512
- self.zoom = target;
829
+ CGPoint focus = [recognizer locationInView:self];
830
+ if ([self.layoutMode isEqualToString:@"continuous"]) [self applyContinuousZoom:target atFocus:focus];
831
+ else [self applySingleZoom:target atFocus:focus];
513
832
  if (self.onZoomChanged) self.onZoomChanged(@{ @"zoom": @(self.zoom) });
514
833
  }
515
834
 
516
835
  - (void)handlePinch:(UIPinchGestureRecognizer *)recognizer {
517
836
  if (recognizer.state == UIGestureRecognizerStateChanged) {
518
- self.zoom = MAX(1, MIN(5, self.zoom * recognizer.scale));
837
+ CGFloat target = PapyrusComicClampZoom(self.zoom * recognizer.scale);
838
+ // The collection fills this view. Its own UIScrollView coordinates can
839
+ // include contentOffset; the enclosing view keeps the focus viewport-local.
840
+ CGPoint focus = [recognizer locationInView:self];
841
+ if ([self.layoutMode isEqualToString:@"continuous"]) [self applyContinuousZoom:target atFocus:focus];
842
+ else [self applySingleZoom:target atFocus:focus];
519
843
  recognizer.scale = 1;
520
844
  } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateFailed) {
521
845
  [self applyPendingPageSizes];
@@ -529,12 +853,12 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
529
853
 
530
854
  - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
531
855
  #pragma unused(touch)
532
- if (gestureRecognizer == self.pagePanRecognizer) return self.zoom > 1.0;
856
+ if (gestureRecognizer == self.pagePanRecognizer) return ![self.layoutMode isEqualToString:@"continuous"] && self.zoom > 1.0;
533
857
  return YES;
534
858
  }
535
859
 
536
860
  - (void)handlePagePan:(UIPanGestureRecognizer *)recognizer {
537
- if (self.zoom <= 1.0) return;
861
+ if ([self.layoutMode isEqualToString:@"continuous"] || self.zoom <= 1.0) return;
538
862
  if (recognizer.state == UIGestureRecognizerStateBegan) {
539
863
  self.panGestureStartOffset = self.panOffset;
540
864
  } else if (recognizer.state == UIGestureRecognizerStateChanged) {
@@ -545,7 +869,7 @@ static NSCache<NSString *, UIImage *> *PapyrusComicImageCache(void) {
545
869
  MAX(-maxX, MIN(maxX, translation.x + self.panGestureStartOffset.x)),
546
870
  MAX(-maxY, MIN(maxY, translation.y + self.panGestureStartOffset.y))
547
871
  );
548
- for (PapyrusComicPageCell *cell in self.collectionView.visibleCells) cell.imageView.transform = [self imageTransform];
872
+ for (PapyrusComicPageCell *cell in self.collectionView.visibleCells) [self applyImageTransformToCell:cell];
549
873
  } else if (recognizer.state == UIGestureRecognizerStateEnded || recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateFailed) {
550
874
  [self applyPendingPageSizes];
551
875
  }
@@ -0,0 +1,118 @@
1
+ #pragma once
2
+
3
+ #include <math.h>
4
+ #include <stddef.h>
5
+
6
+ typedef struct {
7
+ double originX;
8
+ double originY;
9
+ double width;
10
+ double height;
11
+ } PapyrusComicLayoutFrame;
12
+
13
+ static inline double PapyrusComicClampZoom(double zoom) {
14
+ return fmax(1.0, fmin(5.0, zoom));
15
+ }
16
+
17
+ static inline double PapyrusComicZoomedExtent(double extent, double zoom) {
18
+ return fmax(1.0, extent) * PapyrusComicClampZoom(zoom);
19
+ }
20
+
21
+ static inline double PapyrusComicContinuousContentWidth(double viewportWidth, double zoom) {
22
+ return PapyrusComicZoomedExtent(viewportWidth, zoom);
23
+ }
24
+
25
+ static inline double PapyrusComicContinuousDocumentHeight(
26
+ const double *prefixHeights,
27
+ size_t pageCount,
28
+ double zoom) {
29
+ if (prefixHeights == NULL || pageCount == 0) return 0.0;
30
+ return fmax(0.0, prefixHeights[pageCount]) * PapyrusComicClampZoom(zoom);
31
+ }
32
+
33
+ static inline PapyrusComicLayoutFrame PapyrusComicContinuousPageFrame(
34
+ const double *prefixHeights,
35
+ size_t pageCount,
36
+ size_t pageIndex,
37
+ double viewportWidth,
38
+ double zoom) {
39
+ PapyrusComicLayoutFrame frame = {0.0, 0.0, 0.0, 0.0};
40
+ if (prefixHeights == NULL || pageIndex >= pageCount) return frame;
41
+ double scale = PapyrusComicClampZoom(zoom);
42
+ double start = fmax(0.0, prefixHeights[pageIndex]);
43
+ double end = fmax(start, prefixHeights[pageIndex + 1]);
44
+ frame.originY = start * scale;
45
+ frame.width = PapyrusComicContinuousContentWidth(viewportWidth, scale);
46
+ frame.height = fmax(1.0, (end - start) * scale);
47
+ return frame;
48
+ }
49
+
50
+ static inline size_t PapyrusComicContinuousFirstVisiblePage(
51
+ const double *prefixHeights,
52
+ size_t pageCount,
53
+ double minY,
54
+ double zoom) {
55
+ if (prefixHeights == NULL || pageCount == 0) return pageCount;
56
+ double scale = PapyrusComicClampZoom(zoom);
57
+ size_t lower = 0;
58
+ size_t upper = pageCount;
59
+ while (lower < upper) {
60
+ size_t middle = lower + (upper - lower) / 2;
61
+ if (prefixHeights[middle + 1] * scale <= minY) lower = middle + 1;
62
+ else upper = middle;
63
+ }
64
+ return lower;
65
+ }
66
+
67
+ static inline void PapyrusComicContinuousApplyHeightDeltas(
68
+ double *prefixHeights,
69
+ const double *heightDeltas,
70
+ size_t pageCount) {
71
+ if (prefixHeights == NULL || heightDeltas == NULL || pageCount == 0) return;
72
+ double accumulatedDelta = 0.0;
73
+ for (size_t boundary = 1; boundary <= pageCount; boundary++) {
74
+ accumulatedDelta += heightDeltas[boundary - 1];
75
+ prefixHeights[boundary] += accumulatedDelta;
76
+ }
77
+ }
78
+
79
+ static inline double PapyrusComicContinuousPageHeight(
80
+ double imageWidth,
81
+ double imageHeight,
82
+ double viewportWidth,
83
+ double viewportHeight,
84
+ int fitPage,
85
+ double zoom) {
86
+ double baseHeight = fmax(1.0, viewportHeight);
87
+ if (imageWidth > 0.0 && imageHeight > 0.0 && viewportWidth > 0.0) {
88
+ baseHeight = viewportWidth * imageHeight / imageWidth;
89
+ if (fitPage && viewportHeight > 0.0) baseHeight = fmin(baseHeight, viewportHeight);
90
+ }
91
+ return fmax(1.0, baseHeight) * PapyrusComicClampZoom(zoom);
92
+ }
93
+
94
+ static inline double PapyrusComicZoomAnchorFraction(
95
+ double contentOffset,
96
+ double focusInViewport,
97
+ double itemOrigin,
98
+ double itemExtent) {
99
+ if (itemExtent <= 0.0) return 0.0;
100
+ double fraction = (contentOffset + focusInViewport - itemOrigin) / itemExtent;
101
+ return fmax(0.0, fmin(1.0, fraction));
102
+ }
103
+
104
+ static inline double PapyrusComicZoomAnchorOffset(
105
+ double itemOrigin,
106
+ double itemExtent,
107
+ double fraction,
108
+ double focusInViewport,
109
+ double contentExtent,
110
+ double viewportExtent,
111
+ double leadingInset,
112
+ double trailingInset) {
113
+ double minimum = -leadingInset;
114
+ double maximum = fmax(minimum, contentExtent - viewportExtent + trailingInset);
115
+ double anchor = itemOrigin + itemExtent * fmax(0.0, fmin(1.0, fraction));
116
+ double offset = anchor - focusInViewport;
117
+ return fmax(minimum, fmin(maximum, offset));
118
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@papyrus-sdk/engine-native",
3
- "version": "0.2.23",
3
+ "version": "0.2.24",
4
4
  "license": "MIT",
5
5
  "keywords": [
6
6
  "papyrus",
@@ -48,17 +48,17 @@
48
48
  "bugs": {
49
49
  "url": "https://github.com/solrachix/Papyrus/issues"
50
50
  },
51
+ "scripts": {
52
+ "build": "tsup"
53
+ },
51
54
  "peerDependencies": {
52
- "@papyrus-sdk/core": "0.2.24",
55
+ "@papyrus-sdk/core": "0.2.25",
53
56
  "@papyrus-sdk/types": "0.2.17",
54
57
  "react-native": ">=0.81.0"
55
58
  },
56
59
  "devDependencies": {
57
- "@papyrus-sdk/core": "0.2.24",
60
+ "@papyrus-sdk/core": "0.2.25",
58
61
  "@papyrus-sdk/types": "0.2.17",
59
62
  "react-native": "^0.81.0"
60
- },
61
- "scripts": {
62
- "build": "tsup"
63
63
  }
64
- }
64
+ }
@@ -1,240 +0,0 @@
1
- #include "papyrus_outline_loader.h"
2
-
3
- #include <cstdlib>
4
- #include <cstring>
5
- #include <iostream>
6
- #include <string>
7
- #include <unordered_map>
8
-
9
- namespace {
10
-
11
- using PdfiumSymbol = OutlineLoaderDeps::PdfiumSymbol;
12
-
13
- struct FakeLoaderEnv {
14
- void *library_handle = reinterpret_cast<void *>(0x1);
15
- int dlopen_calls = 0;
16
- int dlsym_calls = 0;
17
- int dlclose_calls = 0;
18
- std::unordered_map<std::string, PdfiumSymbol> symbols;
19
- };
20
-
21
- FPDF_DOCUMENT FakeLoadDocument(const char *, const char *) {
22
- return nullptr;
23
- }
24
-
25
- void FakeCloseDocument(FPDF_DOCUMENT) {}
26
-
27
- FPDF_BOOKMARK FakeBookmarkGetFirstChild(FPDF_DOCUMENT, FPDF_BOOKMARK) {
28
- return nullptr;
29
- }
30
-
31
- FPDF_BOOKMARK FakeBookmarkGetNextSibling(FPDF_DOCUMENT, FPDF_BOOKMARK) {
32
- return nullptr;
33
- }
34
-
35
- unsigned long FakeBookmarkGetTitle(FPDF_BOOKMARK, void *, unsigned long) {
36
- return 0;
37
- }
38
-
39
- FPDF_DEST FakeBookmarkGetDest(FPDF_DOCUMENT, FPDF_BOOKMARK) {
40
- return nullptr;
41
- }
42
-
43
- int FakeDestGetPageIndex(FPDF_DOCUMENT, FPDF_DEST) {
44
- return -1;
45
- }
46
-
47
- template <typename FnType>
48
- PdfiumSymbol ToPdfiumSymbol(FnType fn) {
49
- PdfiumSymbol symbol = nullptr;
50
- static_assert(sizeof(symbol) == sizeof(fn),
51
- "Expected function pointers to share the same size");
52
- std::memcpy(&symbol, &fn, sizeof(symbol));
53
- return symbol;
54
- }
55
-
56
- PdfiumOutlineFns MakeCompleteOutlineFns() {
57
- PdfiumOutlineFns fns = {};
58
- fns.loadDocument = &FakeLoadDocument;
59
- fns.closeDocument = &FakeCloseDocument;
60
- fns.bookmarkGetFirstChild = &FakeBookmarkGetFirstChild;
61
- fns.bookmarkGetNextSibling = &FakeBookmarkGetNextSibling;
62
- fns.bookmarkGetTitle = &FakeBookmarkGetTitle;
63
- fns.bookmarkGetDest = &FakeBookmarkGetDest;
64
- fns.destGetPageIndex = &FakeDestGetPageIndex;
65
- return fns;
66
- }
67
-
68
- FakeLoaderEnv *GetEnv(void *user_data) {
69
- return static_cast<FakeLoaderEnv *>(user_data);
70
- }
71
-
72
- void *FakeDlopen(void *user_data, const char *, int) {
73
- FakeLoaderEnv *env = GetEnv(user_data);
74
- env->dlopen_calls += 1;
75
- return env->library_handle;
76
- }
77
-
78
- PdfiumSymbol FakeDlsym(void *user_data, void *, const char *symbol_name) {
79
- FakeLoaderEnv *env = GetEnv(user_data);
80
- env->dlsym_calls += 1;
81
-
82
- const auto it = env->symbols.find(symbol_name);
83
- if (it == env->symbols.end()) {
84
- return nullptr;
85
- }
86
-
87
- return it->second;
88
- }
89
-
90
- int FakeDlclose(void *user_data, void *) {
91
- FakeLoaderEnv *env = GetEnv(user_data);
92
- env->dlclose_calls += 1;
93
- return 0;
94
- }
95
-
96
- OutlineLoaderDeps MakeDeps(FakeLoaderEnv *env) {
97
- OutlineLoaderDeps deps = {};
98
- deps.user_data = env;
99
- deps.dlopen_fn = &FakeDlopen;
100
- deps.dlsym_fn = &FakeDlsym;
101
- deps.dlclose_fn = &FakeDlclose;
102
- deps.library_name = "libmodpdfium.so";
103
- deps.dlopen_flags = 0;
104
- return deps;
105
- }
106
-
107
- void InstallSymbols(FakeLoaderEnv *env, const PdfiumOutlineFns &fns) {
108
- env->symbols["FPDF_LoadDocument"] = ToPdfiumSymbol(fns.loadDocument);
109
- env->symbols["FPDF_CloseDocument"] = ToPdfiumSymbol(fns.closeDocument);
110
- env->symbols["FPDFBookmark_GetFirstChild"] = ToPdfiumSymbol(fns.bookmarkGetFirstChild);
111
- env->symbols["FPDFBookmark_GetNextSibling"] = ToPdfiumSymbol(fns.bookmarkGetNextSibling);
112
- env->symbols["FPDFBookmark_GetTitle"] = ToPdfiumSymbol(fns.bookmarkGetTitle);
113
- env->symbols["FPDFBookmark_GetDest"] = ToPdfiumSymbol(fns.bookmarkGetDest);
114
- env->symbols["FPDFDest_GetPageIndex"] = ToPdfiumSymbol(fns.destGetPageIndex);
115
- }
116
-
117
- [[noreturn]] void Fail(const char *expression, const char *file, int line) {
118
- std::cerr << file << ":" << line << ": assertion failed: " << expression << std::endl;
119
- std::exit(1);
120
- }
121
-
122
- #define EXPECT_TRUE(condition) \
123
- do { \
124
- if (!(condition)) { \
125
- Fail(#condition, __FILE__, __LINE__); \
126
- } \
127
- } while (false)
128
-
129
- #define EXPECT_FALSE(condition) EXPECT_TRUE(!(condition))
130
-
131
- #define EXPECT_EQ(expected, actual) \
132
- do { \
133
- const auto expected_value = (expected); \
134
- const auto actual_value = (actual); \
135
- if (!(expected_value == actual_value)) { \
136
- std::cerr << __FILE__ << ":" << __LINE__ \
137
- << ": expected equality for " << #expected << " and " << #actual << std::endl; \
138
- std::exit(1); \
139
- } \
140
- } while (false)
141
-
142
- void TestFullSymbolTableReturnsSupported() {
143
- FakeLoaderEnv env = {};
144
- const PdfiumOutlineFns complete_fns = MakeCompleteOutlineFns();
145
- InstallSymbols(&env, complete_fns);
146
-
147
- OutlineLoaderState state = {};
148
- const OutlineLoaderDeps deps = MakeDeps(&env);
149
-
150
- const OutlineLoadAttemptResult result = EnsureOutlinePdfiumLoaded(&state, &deps);
151
-
152
- EXPECT_TRUE(result.loaded);
153
- EXPECT_FALSE(result.transitioned_to_unsupported);
154
- EXPECT_EQ(OutlineLoadState::kSupported, state.load_state);
155
- EXPECT_TRUE(state.handle != nullptr);
156
- EXPECT_TRUE(HasCompleteOutlineFns(state.fns));
157
- EXPECT_EQ(1, env.dlopen_calls);
158
- EXPECT_EQ(7, env.dlsym_calls);
159
- EXPECT_EQ(0, env.dlclose_calls);
160
- }
161
-
162
- void TestMissingLibraryReturnsUnsupported() {
163
- FakeLoaderEnv env = {};
164
- env.library_handle = nullptr;
165
-
166
- OutlineLoaderState state = {};
167
- const OutlineLoaderDeps deps = MakeDeps(&env);
168
-
169
- const OutlineLoadAttemptResult result = EnsureOutlinePdfiumLoaded(&state, &deps);
170
-
171
- EXPECT_FALSE(result.loaded);
172
- EXPECT_TRUE(result.transitioned_to_unsupported);
173
- EXPECT_EQ(OutlineLoadState::kUnsupported, state.load_state);
174
- EXPECT_TRUE(state.handle == nullptr);
175
- EXPECT_FALSE(HasCompleteOutlineFns(state.fns));
176
- EXPECT_EQ(1, env.dlopen_calls);
177
- EXPECT_EQ(0, env.dlsym_calls);
178
- EXPECT_EQ(0, env.dlclose_calls);
179
- }
180
-
181
- void TestMissingSymbolReturnsUnsupportedAndClosesHandle() {
182
- FakeLoaderEnv env = {};
183
- const PdfiumOutlineFns partial_fns = MakeCompleteOutlineFns();
184
- InstallSymbols(&env, partial_fns);
185
- env.symbols.erase("FPDFBookmark_GetDest");
186
-
187
- OutlineLoaderState state = {};
188
- const OutlineLoaderDeps deps = MakeDeps(&env);
189
-
190
- const OutlineLoadAttemptResult result = EnsureOutlinePdfiumLoaded(&state, &deps);
191
-
192
- EXPECT_FALSE(result.loaded);
193
- EXPECT_TRUE(result.transitioned_to_unsupported);
194
- EXPECT_EQ(OutlineLoadState::kUnsupported, state.load_state);
195
- EXPECT_TRUE(state.handle == nullptr);
196
- EXPECT_FALSE(HasCompleteOutlineFns(state.fns));
197
- EXPECT_EQ(1, env.dlopen_calls);
198
- EXPECT_EQ(7, env.dlsym_calls);
199
- EXPECT_EQ(1, env.dlclose_calls);
200
- }
201
-
202
- void TestRepeatedCallsAfterFailureStayUnsupported() {
203
- FakeLoaderEnv env = {};
204
- const PdfiumOutlineFns partial_fns = MakeCompleteOutlineFns();
205
- InstallSymbols(&env, partial_fns);
206
- env.symbols.erase("FPDFDest_GetPageIndex");
207
-
208
- OutlineLoaderState state = {};
209
- const OutlineLoaderDeps deps = MakeDeps(&env);
210
-
211
- const OutlineLoadAttemptResult first = EnsureOutlinePdfiumLoaded(&state, &deps);
212
- EXPECT_FALSE(first.loaded);
213
- EXPECT_TRUE(first.transitioned_to_unsupported);
214
- EXPECT_EQ(OutlineLoadState::kUnsupported, state.load_state);
215
- EXPECT_TRUE(state.handle == nullptr);
216
- EXPECT_FALSE(HasCompleteOutlineFns(state.fns));
217
- EXPECT_EQ(1, env.dlopen_calls);
218
- EXPECT_EQ(7, env.dlsym_calls);
219
- EXPECT_EQ(1, env.dlclose_calls);
220
-
221
- const OutlineLoadAttemptResult second = EnsureOutlinePdfiumLoaded(&state, &deps);
222
- EXPECT_FALSE(second.loaded);
223
- EXPECT_FALSE(second.transitioned_to_unsupported);
224
- EXPECT_EQ(OutlineLoadState::kUnsupported, state.load_state);
225
- EXPECT_TRUE(state.handle == nullptr);
226
- EXPECT_FALSE(HasCompleteOutlineFns(state.fns));
227
- EXPECT_EQ(1, env.dlopen_calls);
228
- EXPECT_EQ(7, env.dlsym_calls);
229
- EXPECT_EQ(1, env.dlclose_calls);
230
- }
231
-
232
- } // namespace
233
-
234
- int main() {
235
- TestFullSymbolTableReturnsSupported();
236
- TestMissingLibraryReturnsUnsupported();
237
- TestMissingSymbolReturnsUnsupportedAndClosesHandle();
238
- TestRepeatedCallsAfterFailureStayUnsupported();
239
- return 0;
240
- }
@@ -1,72 +0,0 @@
1
- #include "papyrus_text_word.h"
2
-
3
- #include <iostream>
4
- #include <vector>
5
-
6
- namespace {
7
-
8
- int failures = 0;
9
-
10
- void ExpectTrue(bool value, const char *name) {
11
- if (!value) {
12
- std::cerr << "FAIL: " << name << std::endl;
13
- failures += 1;
14
- }
15
- }
16
-
17
- void ExpectRange(const std::vector<char16_t> &text, int index, int expectedStart,
18
- int expectedEnd, const char *name) {
19
- const auto range = papyrus::ResolveWordRange(text, index);
20
- if (range.first != expectedStart || range.second != expectedEnd) {
21
- std::cerr << "FAIL: " << name << " expected [" << expectedStart << ", "
22
- << expectedEnd << ") got [" << range.first << ", " << range.second
23
- << ")" << std::endl;
24
- failures += 1;
25
- }
26
- }
27
-
28
- } // namespace
29
-
30
- int main() {
31
- ExpectTrue(papyrus::IsWordCharacter(u'a'), "ascii letter");
32
- ExpectTrue(papyrus::IsWordCharacter(u'Z'), "ascii upper");
33
- ExpectTrue(papyrus::IsWordCharacter(u'7'), "digit");
34
- ExpectTrue(papyrus::IsWordCharacter(0x00E7), "c-cedilla");
35
- ExpectTrue(papyrus::IsWordCharacter(0x00E3), "a-tilde");
36
- ExpectTrue(papyrus::IsWordCharacter(u'\''), "apostrophe");
37
- ExpectTrue(papyrus::IsWordCharacter(0x2019), "curly apostrophe");
38
- ExpectTrue(papyrus::IsWordCharacter(u'-'), "hyphen");
39
- ExpectTrue(!papyrus::IsWordCharacter(u' '), "space is not a word char");
40
- ExpectTrue(!papyrus::IsWordCharacter(u'.'), "dot is not a word char");
41
- ExpectTrue(!papyrus::IsWordCharacter(u'\n'), "newline is not a word char");
42
-
43
- const std::vector<char16_t> simple = {u'd', u'i', u'n', u'a'};
44
- ExpectRange(simple, 0, 0, 4, "word from first char");
45
- ExpectRange(simple, 3, 0, 4, "word from last char");
46
- ExpectRange(simple, -1, -1, -1, "out of bounds start");
47
- ExpectRange(simple, 4, 4, 4, "out of bounds end");
48
-
49
- const std::vector<char16_t> accented = {u'c', u'o', u'm', u'p', u'i',
50
- u'l', u'a', 0x00E7, 0x00E3, u'o'};
51
- ExpectRange(accented, 7, 0, 10, "accented word");
52
-
53
- const std::vector<char16_t> hyphenated = {u'j', u'u', u's', u't', u'-',
54
- u'i', u'n', u'-', u't', u'i',
55
- u'm', u'e'};
56
- ExpectRange(hyphenated, 5, 0, 12, "hyphenated word");
57
- ExpectRange(hyphenated, 4, 0, 12, "hyphen is word char");
58
-
59
- const std::vector<char16_t> apostrophe = {u'l', u'\'', 0x00E9, u't'};
60
- ExpectRange(apostrophe, 1, 0, 4, "apostrophe joins the word");
61
-
62
- const std::vector<char16_t> sentence = {u'a', u' ', u'b', u'.', u'c'};
63
- ExpectRange(sentence, 1, 1, 1, "space yields empty range");
64
- ExpectRange(sentence, 3, 3, 3, "dot yields empty range");
65
-
66
- if (failures > 0) {
67
- std::cerr << failures << " failure(s)" << std::endl;
68
- return 1;
69
- }
70
- std::cout << "papyrus_text_word_test: OK" << std::endl;
71
- return 0;
72
- }