@papyrus-sdk/engine-native 0.2.15 → 0.2.16-beta.0

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,1628 @@
1
+ package com.papyrus.engine;
2
+
3
+ import android.content.Context;
4
+ import android.graphics.Bitmap;
5
+ import android.graphics.Canvas;
6
+ import android.graphics.Color;
7
+ import android.graphics.ColorMatrix;
8
+ import android.graphics.ColorMatrixColorFilter;
9
+ import android.graphics.Paint;
10
+ import android.graphics.Path;
11
+ import android.graphics.Rect;
12
+ import android.os.Handler;
13
+ import android.os.Looper;
14
+ import android.util.AttributeSet;
15
+ import android.util.LruCache;
16
+ import android.util.Log;
17
+ import android.view.MotionEvent;
18
+ import android.view.ScaleGestureDetector;
19
+ import android.view.VelocityTracker;
20
+ import android.view.View;
21
+ import android.widget.OverScroller;
22
+
23
+ import com.facebook.react.bridge.Arguments;
24
+ import com.facebook.react.bridge.ReactContext;
25
+ import com.facebook.react.bridge.WritableArray;
26
+ import com.facebook.react.bridge.WritableMap;
27
+ import com.facebook.react.uimanager.events.RCTEventEmitter;
28
+ import com.shockwave.pdfium.PdfDocument;
29
+
30
+ import java.util.ArrayList;
31
+ import java.util.HashMap;
32
+ import java.util.HashSet;
33
+ import java.util.List;
34
+ import java.util.Map;
35
+ import java.util.Set;
36
+ import java.util.concurrent.ExecutorService;
37
+ import java.util.concurrent.Executors;
38
+
39
+ public class PapyrusPdfViewerView extends View {
40
+ private static final String TAG = "PapyrusPdfViewerView";
41
+ private static final int PAGE_GAP = 28;
42
+ private static final int PAGE_PADDING = 16;
43
+ private static final int RENDER_CACHE_BYTES = 48 * 1024 * 1024;
44
+ private static final ExecutorService RENDER_EXECUTOR = Executors.newFixedThreadPool(2);
45
+ private static final LruCache<String, Bitmap> RENDER_CACHE = new LruCache<String, Bitmap>(RENDER_CACHE_BYTES) {
46
+ @Override
47
+ protected int sizeOf(String key, Bitmap value) {
48
+ return value == null ? 0 : value.getByteCount();
49
+ }
50
+
51
+ @Override
52
+ protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
53
+ if (oldValue != null && oldValue != newValue && !oldValue.isRecycled()) {
54
+ oldValue.recycle();
55
+ }
56
+ }
57
+ };
58
+ private static final ColorMatrixColorFilter SEPIA_FILTER = createSepiaFilter();
59
+ private static final ColorMatrixColorFilter DARK_FILTER = createDarkFilter();
60
+ private static final ColorMatrixColorFilter HIGH_CONTRAST_FILTER = createHighContrastFilter();
61
+
62
+ private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
63
+ private final ScaleGestureDetector scaleDetector;
64
+ private final List<PageFrame> pageFrames = new ArrayList<>();
65
+ private final Set<String> loadingKeys = new HashSet<>();
66
+ private final Map<Integer, Bitmap> lastPageBitmap = new HashMap<>();
67
+ private String engineId;
68
+ private String pageTheme = "normal";
69
+ private String activeTool = "select";
70
+ private String annotationColor = "#111827";
71
+ private float inkStrokeWidth = 0.006f;
72
+ private float annotationOpacity = 0.85f;
73
+ private float zoom = 1.0f;
74
+ private String viewMode = "continuous";
75
+ private float offsetX = 0f;
76
+ private float offsetY = 0f;
77
+ private float contentWidth = 0f;
78
+ private float contentHeight = 0f;
79
+ private float lastTouchX = 0f;
80
+ private float lastTouchY = 0f;
81
+ private boolean layoutDirty = true;
82
+ private int renderGeneration = 0;
83
+ private boolean wasScaling = false;
84
+ private boolean isDrawingInk = false;
85
+ private List<float[]> inkStrokePoints = new ArrayList<>();
86
+ private int inkStrokePageIndex = -1;
87
+ private long touchDownTime = 0;
88
+ private float touchDownX = 0;
89
+ private float touchDownY = 0;
90
+ private static final long TAP_MAX_DURATION_MS = 300;
91
+ private static final float TAP_MAX_DISTANCE_DP = 12;
92
+
93
+ // Text selection state
94
+ private boolean isSelectingText = false;
95
+ private int selectPageIndex = -1;
96
+ private float selectStartX = 0;
97
+ private float selectStartY = 0;
98
+ private float selectEndX = 0;
99
+ private float selectEndY = 0;
100
+ private String selectedText = "";
101
+ private List<NormalizedRect> selectedRects = new ArrayList<>();
102
+ private final ExecutorService SELECT_EXECUTOR = Executors.newSingleThreadExecutor();
103
+ private final Handler mainHandler = new Handler(Looper.getMainLooper());
104
+
105
+ // Double-tap detection for text selection
106
+ private long lastTapTime = 0;
107
+ private float lastTapX = 0;
108
+ private float lastTapY = 0;
109
+ private static final long DOUBLE_TAP_MAX_DELTA_MS = 250;
110
+ private static final float DOUBLE_TAP_MAX_DISTANCE_DP = 20;
111
+ private Runnable pendingSingleTap;
112
+
113
+ // Long-press detection
114
+ private static final long LONG_PRESS_MS = 450;
115
+ private Runnable pendingLongPress;
116
+ private boolean longPressFired = false;
117
+
118
+ // Selection handles
119
+ private static final float HANDLE_RADIUS_DP = 10;
120
+ private static final int HANDLE_COLOR = Color.parseColor("#4285F4");
121
+ private int draggedHandle = 0; // 0 = none, -1 = start handle, 1 = end handle
122
+
123
+ private final ReactContext reactContext;
124
+ private final Handler eventThrottleHandler = new Handler(Looper.getMainLooper());
125
+ private Runnable pendingZoomEvent;
126
+ private Runnable pendingScrollEvent;
127
+ private final OverScroller flingScroller;
128
+ private VelocityTracker velocityTracker;
129
+ private final Runnable flingRunnable = new Runnable() {
130
+ @Override
131
+ public void run() {
132
+ if (flingScroller.computeScrollOffset()) {
133
+ offsetX = flingScroller.getCurrX();
134
+ offsetY = flingScroller.getCurrY();
135
+ clampOffsets();
136
+ emitScrollEvent(offsetY);
137
+ invalidate();
138
+ postOnAnimation(this);
139
+ } else {
140
+ int visiblePage = computeVisiblePage();
141
+ if (visiblePage > 0) {
142
+ emitPageChanged(visiblePage);
143
+ }
144
+ if ("single".equals(viewMode) && visiblePage > 0) {
145
+ snapToPage(visiblePage - 1);
146
+ }
147
+ }
148
+ }
149
+ };
150
+
151
+ public PapyrusPdfViewerView(ReactContext context) {
152
+ super(context);
153
+ this.reactContext = context;
154
+ scaleDetector = createScaleDetector(context);
155
+ flingScroller = new OverScroller(context);
156
+ }
157
+
158
+ public PapyrusPdfViewerView(ReactContext context, AttributeSet attrs) {
159
+ super(context, attrs);
160
+ this.reactContext = context;
161
+ scaleDetector = createScaleDetector(context);
162
+ flingScroller = new OverScroller(context);
163
+ }
164
+
165
+ public void setEngineId(String nextEngineId) {
166
+ if (nextEngineId != null && nextEngineId.equals(engineId)) return;
167
+ engineId = nextEngineId;
168
+ renderGeneration += 1;
169
+ layoutDirty = true;
170
+ invalidate();
171
+ }
172
+
173
+ public void setPageTheme(String nextPageTheme) {
174
+ String normalized = nextPageTheme == null ? "normal" : nextPageTheme;
175
+ if (normalized.equals(pageTheme)) return;
176
+ pageTheme = normalized;
177
+ renderGeneration += 1;
178
+ invalidate();
179
+ }
180
+
181
+ public void setActiveTool(String tool) {
182
+ String normalized = tool == null ? "select" : tool;
183
+ if (normalized.equals(activeTool)) return;
184
+ activeTool = normalized;
185
+ if (isDrawingInk) {
186
+ isDrawingInk = false;
187
+ inkStrokePoints.clear();
188
+ inkStrokePageIndex = -1;
189
+ invalidate();
190
+ }
191
+ if (isSelectingText || !selectedRects.isEmpty()) {
192
+ isSelectingText = false;
193
+ selectPageIndex = -1;
194
+ selectedRects.clear();
195
+ selectedText = "";
196
+ invalidate();
197
+ }
198
+ }
199
+
200
+ public void setAnnotationColor(String color) {
201
+ annotationColor = color == null ? "#111827" : color;
202
+ }
203
+
204
+ public void setInkStrokeWidth(float width) {
205
+ inkStrokeWidth = width;
206
+ }
207
+
208
+ public void setAnnotationOpacity(float opacity) {
209
+ annotationOpacity = opacity;
210
+ }
211
+
212
+ public void setViewMode(String mode) {
213
+ String normalized = mode == null ? "continuous" : mode;
214
+ if (normalized.equals(viewMode)) return;
215
+ viewMode = normalized;
216
+ if ("single".equals(viewMode)) {
217
+ ensureLayout();
218
+ snapToPage(computeVisiblePage() - 1);
219
+ }
220
+ invalidate();
221
+ }
222
+
223
+ public void setSelectionActive(boolean active) {
224
+ if (active) return;
225
+ if (isSelectingText || !selectedRects.isEmpty()) {
226
+ isSelectingText = false;
227
+ selectPageIndex = -1;
228
+ selectStartX = 0;
229
+ selectStartY = 0;
230
+ selectEndX = 0;
231
+ selectEndY = 0;
232
+ selectedRects.clear();
233
+ selectedText = "";
234
+ draggedHandle = 0;
235
+ invalidate();
236
+ }
237
+ }
238
+
239
+ private long extractNativeDocPointer(PdfDocument document) {
240
+ try {
241
+ java.lang.reflect.Field field = PdfDocument.class.getDeclaredField("mNativeDocPtr");
242
+ field.setAccessible(true);
243
+ Object value = field.get(document);
244
+ if (value instanceof Long) {
245
+ return (Long) value;
246
+ }
247
+ } catch (Throwable ignored) {
248
+ }
249
+ return 0;
250
+ }
251
+
252
+ public void setZoom(float nextZoom) {
253
+ float clamped = clamp(nextZoom, 0.5f, 5.0f);
254
+ if (Math.abs(clamped - zoom) < 0.001f) return;
255
+ zoom = clamped;
256
+ renderGeneration += 1;
257
+ layoutDirty = true;
258
+ clampOffsets();
259
+ invalidate();
260
+ }
261
+
262
+ public void setCurrentPage(int page) {
263
+ if (page <= 0 || engineId == null) return;
264
+ ensureLayout();
265
+ if (page > pageFrames.size()) return;
266
+ if (page <= pageFrames.size()) {
267
+ PageFrame frame = pageFrames.get(page - 1);
268
+ float frameTop = frame.top;
269
+ float frameBottom = frame.top + frame.height;
270
+ float viewportTop = offsetY;
271
+ float viewportBottom = offsetY + getHeight();
272
+ boolean isVisible = frameBottom > viewportTop && frameTop < viewportBottom;
273
+ if (isVisible) return;
274
+ }
275
+ offsetY = pageFrames.get(page - 1).top;
276
+ clampOffsets();
277
+ invalidate();
278
+ }
279
+
280
+ @Override
281
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
282
+ super.onSizeChanged(w, h, oldw, oldh);
283
+ renderGeneration += 1;
284
+ layoutDirty = true;
285
+ clampOffsets();
286
+ }
287
+
288
+ @Override
289
+ public boolean onTouchEvent(MotionEvent event) {
290
+ scaleDetector.onTouchEvent(event);
291
+
292
+ if ("ink".equals(activeTool) && event.getPointerCount() == 1) {
293
+ return handleInkTouch(event);
294
+ }
295
+
296
+ if (("text".equals(activeTool) || "comment".equals(activeTool)) && event.getPointerCount() == 1) {
297
+ return handleTextCommentTouch(event);
298
+ }
299
+
300
+ if ("select".equals(activeTool) && event.getPointerCount() == 1) {
301
+ boolean consumed = handleSelectTouch(event);
302
+ if (consumed) return true;
303
+ // Not consumed: let React Native handle the touch (e.g. toolbar buttons)
304
+ return false;
305
+ }
306
+
307
+ switch (event.getActionMasked()) {
308
+ case MotionEvent.ACTION_DOWN:
309
+ if (velocityTracker == null) {
310
+ velocityTracker = VelocityTracker.obtain();
311
+ } else {
312
+ velocityTracker.clear();
313
+ }
314
+ velocityTracker.addMovement(event);
315
+ flingScroller.abortAnimation();
316
+ removeCallbacks(flingRunnable);
317
+ lastTouchX = event.getX();
318
+ lastTouchY = event.getY();
319
+ touchDownTime = System.currentTimeMillis();
320
+ touchDownX = event.getX();
321
+ touchDownY = event.getY();
322
+ return true;
323
+ case MotionEvent.ACTION_MOVE:
324
+ if (velocityTracker != null) {
325
+ velocityTracker.addMovement(event);
326
+ }
327
+ if (!scaleDetector.isInProgress() && event.getPointerCount() == 1) {
328
+ offsetX += lastTouchX - event.getX();
329
+ offsetY += lastTouchY - event.getY();
330
+ clampOffsets();
331
+ emitScrollEvent(offsetY);
332
+ invalidate();
333
+ }
334
+ lastTouchX = event.getX();
335
+ lastTouchY = event.getY();
336
+ return true;
337
+ case MotionEvent.ACTION_UP:
338
+ case MotionEvent.ACTION_CANCEL:
339
+ if (wasScaling && !scaleDetector.isInProgress()) {
340
+ wasScaling = false;
341
+ emitZoomChanged(zoom);
342
+ }
343
+ if (!scaleDetector.isInProgress() && velocityTracker != null) {
344
+ velocityTracker.addMovement(event);
345
+ velocityTracker.computeCurrentVelocity(1000, 8000);
346
+ float velocityX = velocityTracker.getXVelocity();
347
+ float velocityY = velocityTracker.getYVelocity();
348
+ if (Math.abs(velocityX) > 200 || Math.abs(velocityY) > 200) {
349
+ if ("single".equals(viewMode)) {
350
+ int currentPage = computeVisiblePage() - 1;
351
+ int targetPage = currentPage;
352
+ if (velocityY > 400 && currentPage > 0) {
353
+ targetPage = currentPage - 1;
354
+ } else if (velocityY < -400 && currentPage < pageFrames.size() - 1) {
355
+ targetPage = currentPage + 1;
356
+ }
357
+ snapToPage(targetPage);
358
+ } else {
359
+ flingScroller.fling(
360
+ Math.round(offsetX),
361
+ Math.round(offsetY),
362
+ Math.round(-velocityX),
363
+ Math.round(-velocityY),
364
+ 0,
365
+ Math.max(0, Math.round(contentWidth - getWidth())),
366
+ 0,
367
+ Math.max(0, Math.round(contentHeight - getHeight()))
368
+ );
369
+ postOnAnimation(flingRunnable);
370
+ }
371
+ } else {
372
+ int visiblePage = computeVisiblePage();
373
+ if (visiblePage > 0) {
374
+ emitPageChanged(visiblePage);
375
+ }
376
+ if ("single".equals(viewMode) && visiblePage > 0) {
377
+ snapToPage(visiblePage - 1);
378
+ }
379
+ }
380
+ velocityTracker.recycle();
381
+ velocityTracker = null;
382
+ }
383
+ if (event.getActionMasked() == MotionEvent.ACTION_UP) {
384
+ long duration = System.currentTimeMillis() - touchDownTime;
385
+ float dx = event.getX() - touchDownX;
386
+ float dy = event.getY() - touchDownY;
387
+ float distance = (float) Math.hypot(dx, dy);
388
+ float density = getResources().getDisplayMetrics().density;
389
+ if (duration < TAP_MAX_DURATION_MS && distance < TAP_MAX_DISTANCE_DP * density) {
390
+ // Single mode tap zones: left half = prev page, right half = next page
391
+ if ("single".equals(viewMode) && !pageFrames.isEmpty()) {
392
+ int currentPage = computeVisiblePage() - 1;
393
+ if (event.getX() < getWidth() / 2f) {
394
+ if (currentPage > 0) snapToPage(currentPage - 1);
395
+ } else {
396
+ if (currentPage < pageFrames.size() - 1) snapToPage(currentPage + 1);
397
+ }
398
+ return true;
399
+ }
400
+ ensureLayout();
401
+ float docX = event.getX() + offsetX;
402
+ float docY = event.getY() + offsetY;
403
+ int pageIdx = findPageIndexAt(docX, docY);
404
+ if (pageIdx >= 0) {
405
+ PageFrame frame = pageFrames.get(pageIdx);
406
+ float nx = (docX - frame.left) / frame.width;
407
+ float ny = (docY - frame.top) / frame.height;
408
+ Annotation hit = findAnnotationAt(pageIdx, nx, ny);
409
+ if (hit != null) {
410
+ emitAnnotationTap(hit);
411
+ } else {
412
+ emitTap(pageIdx, clamp01(nx), clamp01(ny));
413
+ }
414
+ }
415
+ }
416
+ }
417
+ return true;
418
+ default:
419
+ return true;
420
+ }
421
+ }
422
+
423
+ private boolean handleInkTouch(MotionEvent event) {
424
+ switch (event.getActionMasked()) {
425
+ case MotionEvent.ACTION_DOWN:
426
+ ensureLayout();
427
+ inkStrokePageIndex = findPageIndexAt(event.getX() + offsetX, event.getY() + offsetY);
428
+ if (inkStrokePageIndex < 0) return true;
429
+ isDrawingInk = true;
430
+ inkStrokePoints.clear();
431
+ addInkPoint(event.getX() + offsetX, event.getY() + offsetY);
432
+ invalidate();
433
+ return true;
434
+ case MotionEvent.ACTION_MOVE:
435
+ if (isDrawingInk && inkStrokePageIndex >= 0) {
436
+ addInkPoint(event.getX() + offsetX, event.getY() + offsetY);
437
+ invalidate();
438
+ }
439
+ return true;
440
+ case MotionEvent.ACTION_UP:
441
+ case MotionEvent.ACTION_CANCEL:
442
+ if (isDrawingInk && inkStrokePoints.size() >= 2) {
443
+ emitAnnotationCreated();
444
+ }
445
+ isDrawingInk = false;
446
+ inkStrokePoints.clear();
447
+ inkStrokePageIndex = -1;
448
+ invalidate();
449
+ return true;
450
+ default:
451
+ return true;
452
+ }
453
+ }
454
+
455
+ private boolean handleTextCommentTouch(MotionEvent event) {
456
+ switch (event.getActionMasked()) {
457
+ case MotionEvent.ACTION_DOWN:
458
+ touchDownTime = System.currentTimeMillis();
459
+ touchDownX = event.getX();
460
+ touchDownY = event.getY();
461
+ return true;
462
+ case MotionEvent.ACTION_UP:
463
+ long duration = System.currentTimeMillis() - touchDownTime;
464
+ float dx = event.getX() - touchDownX;
465
+ float dy = event.getY() - touchDownY;
466
+ float distance = (float) Math.hypot(dx, dy);
467
+ float density = getResources().getDisplayMetrics().density;
468
+ if (duration < TAP_MAX_DURATION_MS && distance < TAP_MAX_DISTANCE_DP * density) {
469
+ ensureLayout();
470
+ float docX = event.getX() + offsetX;
471
+ float docY = event.getY() + offsetY;
472
+ int pageIdx = findPageIndexAt(docX, docY);
473
+ if (pageIdx >= 0) {
474
+ PageFrame frame = pageFrames.get(pageIdx);
475
+ float nx = clamp01((docX - frame.left) / frame.width);
476
+ float ny = clamp01((docY - frame.top) / frame.height);
477
+ emitAnnotationCreatedForTool(activeTool, pageIdx, nx, ny);
478
+ }
479
+ }
480
+ return true;
481
+ default:
482
+ return true;
483
+ }
484
+ }
485
+
486
+ private boolean handleSelectTouch(MotionEvent event) {
487
+ float density = getResources().getDisplayMetrics().density;
488
+ switch (event.getActionMasked()) {
489
+ case MotionEvent.ACTION_DOWN:
490
+ touchDownTime = System.currentTimeMillis();
491
+ touchDownX = event.getX();
492
+ touchDownY = event.getY();
493
+ longPressFired = false;
494
+ draggedHandle = 0;
495
+
496
+ // Check if touching a selection handle
497
+ if (isSelectingText && selectPageIndex >= 0 && !selectedRects.isEmpty()) {
498
+ int handleHit = hitTestHandle(event.getX(), event.getY(), density);
499
+ if (handleHit != 0) {
500
+ draggedHandle = handleHit;
501
+ if (velocityTracker != null) {
502
+ velocityTracker.recycle();
503
+ velocityTracker = null;
504
+ }
505
+ return true;
506
+ }
507
+ // If selection is active and touch is NOT on a handle, check if it's on the selection
508
+ if (!hitTestSelection(event.getX(), event.getY())) {
509
+ // Touch outside selection area: let React Native handle it (toolbar buttons)
510
+ return false;
511
+ }
512
+ }
513
+
514
+ if (velocityTracker == null) {
515
+ velocityTracker = VelocityTracker.obtain();
516
+ } else {
517
+ velocityTracker.clear();
518
+ }
519
+ velocityTracker.addMovement(event);
520
+ flingScroller.abortAnimation();
521
+ removeCallbacks(flingRunnable);
522
+ lastTouchX = event.getX();
523
+ lastTouchY = event.getY();
524
+
525
+ // Start long-press timer
526
+ pendingLongPress = () -> {
527
+ pendingLongPress = null;
528
+ longPressFired = true;
529
+ // Long press: select word at this point
530
+ ensureLayout();
531
+ float docX = touchDownX + offsetX;
532
+ float docY = touchDownY + offsetY;
533
+ int pageIdx = findPageIndexAt(docX, docY);
534
+ if (pageIdx >= 0) {
535
+ PageFrame frame = pageFrames.get(pageIdx);
536
+ float nx = clamp01((docX - frame.left) / frame.width);
537
+ float ny = clamp01((docY - frame.top) / frame.height);
538
+ isSelectingText = true;
539
+ selectPageIndex = pageIdx;
540
+ selectStartX = nx;
541
+ selectStartY = ny;
542
+ selectEndX = nx;
543
+ selectEndY = ny;
544
+ performWordSelection();
545
+ }
546
+ };
547
+ mainHandler.postDelayed(pendingLongPress, LONG_PRESS_MS);
548
+ return true;
549
+
550
+ case MotionEvent.ACTION_MOVE:
551
+ if (pendingLongPress != null) {
552
+ float cancelDx = event.getX() - touchDownX;
553
+ float cancelDy = event.getY() - touchDownY;
554
+ if (Math.hypot(cancelDx, cancelDy) > TAP_MAX_DISTANCE_DP * density) {
555
+ mainHandler.removeCallbacks(pendingLongPress);
556
+ pendingLongPress = null;
557
+ }
558
+ }
559
+
560
+ if (draggedHandle != 0 && isSelectingText && selectPageIndex >= 0) {
561
+ ensureLayout();
562
+ float moveDocX = event.getX() + offsetX;
563
+ float moveDocY = event.getY() + offsetY;
564
+ PageFrame moveFrame = null;
565
+ for (PageFrame f : pageFrames) {
566
+ if (f.index == selectPageIndex) {
567
+ moveFrame = f;
568
+ break;
569
+ }
570
+ }
571
+ if (moveFrame != null) {
572
+ float nx = clamp01((moveDocX - moveFrame.left) / moveFrame.width);
573
+ float ny = clamp01((moveDocY - moveFrame.top) / moveFrame.height);
574
+ // Line-based selection: when dragging vertically across lines,
575
+ // snap X to page edge so the entire line gets selected
576
+ float lineHeight = 0.025f;
577
+ if (draggedHandle < 0) {
578
+ // Start handle: if moved to a different line than the end, snap to left edge
579
+ if (Math.abs(ny - selectEndY) > lineHeight * 0.6f) {
580
+ selectStartX = 0f;
581
+ } else {
582
+ selectStartX = nx;
583
+ }
584
+ selectStartY = ny;
585
+ } else {
586
+ // End handle: if moved to a different line than the start, snap to right edge
587
+ if (Math.abs(ny - selectStartY) > lineHeight * 0.6f) {
588
+ selectEndX = 1f;
589
+ } else {
590
+ selectEndX = nx;
591
+ }
592
+ selectEndY = ny;
593
+ }
594
+ performTextSelection();
595
+ }
596
+ return true;
597
+ }
598
+
599
+ if (velocityTracker != null) {
600
+ velocityTracker.addMovement(event);
601
+ }
602
+ float moveDx = event.getX() - touchDownX;
603
+ float moveDy = event.getY() - touchDownY;
604
+ float moveDistance = (float) Math.hypot(moveDx, moveDy);
605
+ if (!isSelectingText && moveDistance > TAP_MAX_DISTANCE_DP * density) {
606
+ if (!scaleDetector.isInProgress() && event.getPointerCount() == 1) {
607
+ offsetX += lastTouchX - event.getX();
608
+ offsetY += lastTouchY - event.getY();
609
+ clampOffsets();
610
+ emitScrollEvent(offsetY);
611
+ invalidate();
612
+ }
613
+ lastTouchX = event.getX();
614
+ lastTouchY = event.getY();
615
+ return true;
616
+ }
617
+ if (isSelectingText && selectPageIndex >= 0) {
618
+ ensureLayout();
619
+ float moveDocX = event.getX() + offsetX;
620
+ float moveDocY = event.getY() + offsetY;
621
+ PageFrame moveFrame = null;
622
+ for (PageFrame f : pageFrames) {
623
+ if (f.index == selectPageIndex) {
624
+ moveFrame = f;
625
+ break;
626
+ }
627
+ }
628
+ if (moveFrame != null) {
629
+ float nx = clamp01((moveDocX - moveFrame.left) / moveFrame.width);
630
+ float ny = clamp01((moveDocY - moveFrame.top) / moveFrame.height);
631
+ // Line-based selection: snap to page edge when crossing lines
632
+ float lineHeight = 0.025f;
633
+ if (Math.abs(ny - selectStartY) > lineHeight * 0.6f) {
634
+ selectEndX = 1f;
635
+ } else {
636
+ selectEndX = nx;
637
+ }
638
+ selectEndY = ny;
639
+ performTextSelection();
640
+ }
641
+ }
642
+ lastTouchX = event.getX();
643
+ lastTouchY = event.getY();
644
+ return true;
645
+
646
+ case MotionEvent.ACTION_UP:
647
+ case MotionEvent.ACTION_CANCEL:
648
+ if (pendingLongPress != null) {
649
+ mainHandler.removeCallbacks(pendingLongPress);
650
+ pendingLongPress = null;
651
+ }
652
+
653
+ draggedHandle = 0;
654
+
655
+ if (!scaleDetector.isInProgress() && velocityTracker != null) {
656
+ velocityTracker.addMovement(event);
657
+ velocityTracker.computeCurrentVelocity(1000, 8000);
658
+ float velocityX = velocityTracker.getXVelocity();
659
+ float velocityY = velocityTracker.getYVelocity();
660
+ if (Math.abs(velocityX) > 200 || Math.abs(velocityY) > 200) {
661
+ if ("single".equals(viewMode)) {
662
+ int currentPage = computeVisiblePage() - 1;
663
+ int targetPage = currentPage;
664
+ if (velocityY > 400 && currentPage > 0) {
665
+ targetPage = currentPage - 1;
666
+ } else if (velocityY < -400 && currentPage < pageFrames.size() - 1) {
667
+ targetPage = currentPage + 1;
668
+ }
669
+ snapToPage(targetPage);
670
+ } else {
671
+ flingScroller.fling(
672
+ Math.round(offsetX),
673
+ Math.round(offsetY),
674
+ Math.round(-velocityX),
675
+ Math.round(-velocityY),
676
+ 0,
677
+ Math.max(0, Math.round(contentWidth - getWidth())),
678
+ 0,
679
+ Math.max(0, Math.round(contentHeight - getHeight()))
680
+ );
681
+ postOnAnimation(flingRunnable);
682
+ }
683
+ } else if ("single".equals(viewMode)) {
684
+ int visiblePage = computeVisiblePage();
685
+ if (visiblePage > 0) {
686
+ snapToPage(visiblePage - 1);
687
+ }
688
+ }
689
+ velocityTracker.recycle();
690
+ velocityTracker = null;
691
+ }
692
+
693
+ long duration = System.currentTimeMillis() - touchDownTime;
694
+ float upDx = event.getX() - touchDownX;
695
+ float upDy = event.getY() - touchDownY;
696
+ float upDistance = (float) Math.hypot(upDx, upDy);
697
+
698
+ if (longPressFired || duration > TAP_MAX_DURATION_MS || upDistance > TAP_MAX_DISTANCE_DP * density) {
699
+ if (isSelectingText && !longPressFired) {
700
+ emitTextSelected();
701
+ }
702
+ return true;
703
+ }
704
+
705
+ long now = System.currentTimeMillis();
706
+ float tapDx = event.getX() - lastTapX;
707
+ float tapDy = event.getY() - lastTapY;
708
+ float tapDistance = (float) Math.hypot(tapDx, tapDy);
709
+ boolean isDoubleTap = (now - lastTapTime) < DOUBLE_TAP_MAX_DELTA_MS && tapDistance < DOUBLE_TAP_MAX_DISTANCE_DP * density;
710
+
711
+ if (pendingSingleTap != null) {
712
+ mainHandler.removeCallbacks(pendingSingleTap);
713
+ pendingSingleTap = null;
714
+ }
715
+
716
+ if (isDoubleTap) {
717
+ lastTapTime = 0;
718
+ ensureLayout();
719
+ float docX = event.getX() + offsetX;
720
+ float docY = event.getY() + offsetY;
721
+ int pageIdx = findPageIndexAt(docX, docY);
722
+ if (pageIdx >= 0) {
723
+ PageFrame frame = pageFrames.get(pageIdx);
724
+ float nx = clamp01((docX - frame.left) / frame.width);
725
+ float ny = clamp01((docY - frame.top) / frame.height);
726
+ isSelectingText = true;
727
+ selectPageIndex = pageIdx;
728
+ selectStartX = nx;
729
+ selectStartY = ny;
730
+ selectEndX = nx;
731
+ selectEndY = ny;
732
+ performTextSelection();
733
+ }
734
+ } else {
735
+ lastTapTime = now;
736
+ lastTapX = event.getX();
737
+ lastTapY = event.getY();
738
+ pendingSingleTap = () -> {
739
+ pendingSingleTap = null;
740
+ if (isSelectingText) {
741
+ isSelectingText = false;
742
+ selectPageIndex = -1;
743
+ selectedRects.clear();
744
+ selectedText = "";
745
+ invalidate();
746
+ }
747
+ };
748
+ mainHandler.postDelayed(pendingSingleTap, DOUBLE_TAP_MAX_DELTA_MS + 50);
749
+ }
750
+ return true;
751
+ default:
752
+ return true;
753
+ }
754
+ }
755
+
756
+ private boolean hitTestSelection(float screenX, float screenY) {
757
+ if (!isSelectingText || selectPageIndex < 0 || selectedRects.isEmpty()) return false;
758
+ PageFrame frame = null;
759
+ for (PageFrame f : pageFrames) {
760
+ if (f.index == selectPageIndex) {
761
+ frame = f;
762
+ break;
763
+ }
764
+ }
765
+ if (frame == null) return false;
766
+
767
+ float nx = clamp01((screenX + offsetX - frame.left) / frame.width);
768
+ float ny = clamp01((screenY + offsetY - frame.top) / frame.height);
769
+
770
+ // Check if point is inside any selected rect
771
+ for (NormalizedRect rect : selectedRects) {
772
+ if (nx >= rect.x && nx <= rect.x + rect.width &&
773
+ ny >= rect.y && ny <= rect.y + rect.height) {
774
+ return true;
775
+ }
776
+ }
777
+ return false;
778
+ }
779
+
780
+ private int hitTestHandle(float screenX, float screenY, float density) {
781
+ if (selectedRects.isEmpty() || selectPageIndex < 0) return 0;
782
+ PageFrame frame = null;
783
+ for (PageFrame f : pageFrames) {
784
+ if (f.index == selectPageIndex) {
785
+ frame = f;
786
+ break;
787
+ }
788
+ }
789
+ if (frame == null) return 0;
790
+
791
+ float radius = HANDLE_RADIUS_DP * density * 1.8f;
792
+
793
+ // Start handle: top-left of first rect
794
+ NormalizedRect first = selectedRects.get(0);
795
+ float startX = Math.round(frame.left - offsetX + first.x * frame.width);
796
+ float startY = Math.round(frame.top - offsetY + first.y * frame.height);
797
+ if (Math.hypot(screenX - startX, screenY - startY) < radius) return -1;
798
+
799
+ // End handle: bottom-right of last rect
800
+ NormalizedRect last = selectedRects.get(selectedRects.size() - 1);
801
+ float endX = Math.round(frame.left - offsetX + (last.x + last.width) * frame.width);
802
+ float endY = Math.round(frame.top - offsetY + (last.y + last.height) * frame.height);
803
+ if (Math.hypot(screenX - endX, screenY - endY) < radius) return 1;
804
+
805
+ return 0;
806
+ }
807
+
808
+ private void performWordSelection() {
809
+ if (selectPageIndex < 0) return;
810
+ PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
811
+ if (state == null || state.document == null) return;
812
+ if (!PapyrusTextSelect.AVAILABLE) return;
813
+
814
+ // Use a larger rect to capture the whole word
815
+ float wordW = 0.05f;
816
+ float wordH = 0.03f;
817
+ float minX = Math.max(0f, selectStartX - wordW / 2f);
818
+ float minY = Math.max(0f, selectStartY - wordH / 2f);
819
+ float maxX = Math.min(1f, selectStartX + wordW / 2f);
820
+ float maxY = Math.min(1f, selectStartY + wordH / 2f);
821
+
822
+ final int pageIdx = selectPageIndex;
823
+ final float selX = minX;
824
+ final float selY = minY;
825
+ final float selW = Math.max(0.001f, maxX - minX);
826
+ final float selH = Math.max(0.001f, maxY - minY);
827
+
828
+ final String sourcePath = state.sourcePath;
829
+ SELECT_EXECUTOR.execute(() -> {
830
+ PapyrusTextSelection selection = null;
831
+ try {
832
+ if (sourcePath != null && !sourcePath.isEmpty()) {
833
+ synchronized (state.pdfiumLock) {
834
+ selection = PapyrusTextSelect.nativeSelectTextFile(sourcePath, pageIdx, selX, selY, selW, selH);
835
+ }
836
+ } else {
837
+ long docPtr;
838
+ synchronized (state.pdfiumLock) {
839
+ docPtr = extractNativeDocPointer(state.document);
840
+ }
841
+ if (docPtr != 0) {
842
+ synchronized (state.pdfiumLock) {
843
+ selection = PapyrusTextSelect.nativeSelectText(docPtr, pageIdx, selX, selY, selW, selH);
844
+ }
845
+ }
846
+ }
847
+ } catch (Throwable ignored) {
848
+ }
849
+
850
+ final PapyrusTextSelection finalSelection = selection;
851
+ mainHandler.post(() -> {
852
+ if (!isSelectingText && selectPageIndex != pageIdx) return;
853
+ selectedRects.clear();
854
+ if (finalSelection != null && finalSelection.rects != null && finalSelection.rects.length >= 4) {
855
+ selectedText = finalSelection.text != null ? finalSelection.text : "";
856
+ for (int i = 0; i + 3 < finalSelection.rects.length; i += 4) {
857
+ selectedRects.add(new NormalizedRect(
858
+ finalSelection.rects[i],
859
+ finalSelection.rects[i + 1],
860
+ finalSelection.rects[i + 2],
861
+ finalSelection.rects[i + 3]
862
+ ));
863
+ }
864
+ // Set selection bounds to cover the word
865
+ if (!selectedRects.isEmpty()) {
866
+ float sx = selectedRects.get(0).x;
867
+ float sy = selectedRects.get(0).y;
868
+ float ex = selectedRects.get(selectedRects.size() - 1).x + selectedRects.get(selectedRects.size() - 1).width;
869
+ float ey = selectedRects.get(selectedRects.size() - 1).y + selectedRects.get(selectedRects.size() - 1).height;
870
+ selectStartX = sx;
871
+ selectStartY = sy;
872
+ selectEndX = ex;
873
+ selectEndY = ey;
874
+ }
875
+ } else {
876
+ selectedText = "";
877
+ }
878
+ invalidate();
879
+ });
880
+ });
881
+ }
882
+
883
+ private void performTextSelection() {
884
+ if (selectPageIndex < 0) return;
885
+ PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
886
+ if (state == null || state.document == null) return;
887
+ if (!PapyrusTextSelect.AVAILABLE) return;
888
+
889
+ float minX = Math.min(selectStartX, selectEndX);
890
+ float minY = Math.min(selectStartY, selectEndY);
891
+ float maxX = Math.max(selectStartX, selectEndX);
892
+ float maxY = Math.max(selectStartY, selectEndY);
893
+ float width = Math.max(0.001f, maxX - minX);
894
+ float height = Math.max(0.001f, maxY - minY);
895
+
896
+ final int pageIdx = selectPageIndex;
897
+ final float selX = minX;
898
+ final float selY = minY;
899
+ final float selW = width;
900
+ final float selH = height;
901
+
902
+ final String sourcePath = state.sourcePath;
903
+ SELECT_EXECUTOR.execute(() -> {
904
+ PapyrusTextSelection selection = null;
905
+ try {
906
+ if (sourcePath != null && !sourcePath.isEmpty()) {
907
+ synchronized (state.pdfiumLock) {
908
+ selection = PapyrusTextSelect.nativeSelectTextFile(sourcePath, pageIdx, selX, selY, selW, selH);
909
+ }
910
+ } else {
911
+ long docPtr;
912
+ synchronized (state.pdfiumLock) {
913
+ docPtr = extractNativeDocPointer(state.document);
914
+ }
915
+ if (docPtr != 0) {
916
+ synchronized (state.pdfiumLock) {
917
+ selection = PapyrusTextSelect.nativeSelectText(docPtr, pageIdx, selX, selY, selW, selH);
918
+ }
919
+ }
920
+ }
921
+ } catch (Throwable ignored) {
922
+ }
923
+
924
+ final PapyrusTextSelection finalSelection = selection;
925
+ mainHandler.post(() -> {
926
+ if (!isSelectingText && selectPageIndex != pageIdx) return;
927
+ selectedRects.clear();
928
+ if (finalSelection != null && finalSelection.rects != null && finalSelection.rects.length >= 4) {
929
+ selectedText = finalSelection.text != null ? finalSelection.text : "";
930
+ for (int i = 0; i + 3 < finalSelection.rects.length; i += 4) {
931
+ selectedRects.add(new NormalizedRect(
932
+ finalSelection.rects[i],
933
+ finalSelection.rects[i + 1],
934
+ finalSelection.rects[i + 2],
935
+ finalSelection.rects[i + 3]
936
+ ));
937
+ }
938
+ } else {
939
+ selectedText = "";
940
+ }
941
+ invalidate();
942
+ });
943
+ });
944
+ }
945
+
946
+ private void emitTextSelected() {
947
+ try {
948
+ if (selectedRects.isEmpty()) return;
949
+ WritableMap event = Arguments.createMap();
950
+ event.putString("text", selectedText);
951
+ event.putInt("pageIndex", selectPageIndex);
952
+ WritableArray rects = Arguments.createArray();
953
+ for (NormalizedRect rect : selectedRects) {
954
+ WritableMap r = Arguments.createMap();
955
+ r.putDouble("x", rect.x);
956
+ r.putDouble("y", rect.y);
957
+ r.putDouble("width", rect.width);
958
+ r.putDouble("height", rect.height);
959
+ rects.pushMap(r);
960
+ }
961
+ event.putArray("rects", rects);
962
+ reactContext.getJSModule(RCTEventEmitter.class)
963
+ .receiveEvent(getId(), "onTextSelected", event);
964
+ } catch (Throwable ignored) {
965
+ }
966
+ }
967
+
968
+ private int findPageIndexAt(float docX, float docY) {
969
+ for (PageFrame frame : pageFrames) {
970
+ if (docX >= frame.left && docX <= frame.left + frame.width &&
971
+ docY >= frame.top && docY <= frame.top + frame.height) {
972
+ return frame.index;
973
+ }
974
+ }
975
+ return -1;
976
+ }
977
+
978
+ private void addInkPoint(float docX, float docY) {
979
+ if (inkStrokePageIndex < 0 || inkStrokePageIndex >= pageFrames.size()) return;
980
+ PageFrame frame = pageFrames.get(inkStrokePageIndex);
981
+ float nx = (docX - frame.left) / frame.width;
982
+ float ny = (docY - frame.top) / frame.height;
983
+ if (nx < 0) nx = 0; else if (nx > 1) nx = 1;
984
+ if (ny < 0) ny = 0; else if (ny > 1) ny = 1;
985
+ if (inkStrokePoints.size() > 0) {
986
+ float[] last = inkStrokePoints.get(inkStrokePoints.size() - 1);
987
+ float dx = nx - last[0];
988
+ float dy = ny - last[1];
989
+ if (dx * dx + dy * dy < 0.00000064f) return;
990
+ }
991
+ inkStrokePoints.add(new float[] { nx, ny });
992
+ }
993
+
994
+ private static float clamp01(float value) {
995
+ return Math.max(0f, Math.min(1f, value));
996
+ }
997
+
998
+ @Override
999
+ protected void onDraw(Canvas canvas) {
1000
+ super.onDraw(canvas);
1001
+ ensureLayout();
1002
+ canvas.drawColor(resolveBackgroundColor(pageTheme));
1003
+ if (pageFrames.isEmpty()) return;
1004
+
1005
+ for (PageFrame frame : pageFrames) {
1006
+ int left = Math.round(frame.left - offsetX);
1007
+ int top = Math.round(frame.top - offsetY);
1008
+ int right = Math.round(left + frame.width);
1009
+ int bottom = Math.round(top + frame.height);
1010
+ if (bottom < 0 || top > getHeight()) continue;
1011
+
1012
+ paint.setColor(resolvePageColor(pageTheme));
1013
+ paint.setColorFilter(null);
1014
+ canvas.drawRect(left, top, right, bottom, paint);
1015
+
1016
+ String key = buildRenderKey(frame);
1017
+ Bitmap bitmap = RENDER_CACHE.get(key);
1018
+ if (bitmap != null && !bitmap.isRecycled()) {
1019
+ try {
1020
+ paint.setColorFilter(resolveThemeFilter(pageTheme));
1021
+ canvas.drawBitmap(bitmap, null, new Rect(left, top, right, bottom), paint);
1022
+ paint.setColorFilter(null);
1023
+ } catch (RuntimeException error) {
1024
+ Log.w(TAG, "Failed to draw dedicated PDF page", error);
1025
+ }
1026
+ } else {
1027
+ Bitmap fallback = lastPageBitmap.get(frame.index);
1028
+ if (fallback != null && !fallback.isRecycled()) {
1029
+ try {
1030
+ paint.setColorFilter(resolveThemeFilter(pageTheme));
1031
+ canvas.drawBitmap(fallback, null, new Rect(left, top, right, bottom), paint);
1032
+ paint.setColorFilter(null);
1033
+ } catch (RuntimeException error) {
1034
+ Log.w(TAG, "Failed to draw fallback PDF page", error);
1035
+ }
1036
+ }
1037
+ requestRender(frame, key);
1038
+ }
1039
+ drawOverlays(canvas, frame, left, top);
1040
+ }
1041
+ }
1042
+
1043
+ private int computeVisiblePage() {
1044
+ if (pageFrames.isEmpty()) return 1;
1045
+ float viewportCenterY = offsetY + getHeight() / 2f;
1046
+ int bestPage = 1;
1047
+ float bestDistance = Float.MAX_VALUE;
1048
+ for (PageFrame frame : pageFrames) {
1049
+ float frameCenterY = frame.top + frame.height / 2f;
1050
+ float distance = Math.abs(frameCenterY - viewportCenterY);
1051
+ if (distance < bestDistance) {
1052
+ bestDistance = distance;
1053
+ bestPage = frame.index + 1;
1054
+ }
1055
+ }
1056
+ return bestPage;
1057
+ }
1058
+
1059
+ private void emitPageChanged(int page) {
1060
+ try {
1061
+ WritableMap event = Arguments.createMap();
1062
+ event.putInt("page", page);
1063
+ reactContext.getJSModule(RCTEventEmitter.class)
1064
+ .receiveEvent(getId(), "onPageChanged", event);
1065
+ } catch (Throwable ignored) {
1066
+ }
1067
+ }
1068
+
1069
+ private void emitZoomChanged(float zoomValue) {
1070
+ try {
1071
+ if (pendingZoomEvent != null) {
1072
+ eventThrottleHandler.removeCallbacks(pendingZoomEvent);
1073
+ }
1074
+ pendingZoomEvent = () -> {
1075
+ WritableMap event = Arguments.createMap();
1076
+ event.putDouble("zoom", zoomValue);
1077
+ reactContext.getJSModule(RCTEventEmitter.class)
1078
+ .receiveEvent(getId(), "onZoomChanged", event);
1079
+ pendingZoomEvent = null;
1080
+ };
1081
+ eventThrottleHandler.postDelayed(pendingZoomEvent, 120);
1082
+ } catch (Throwable ignored) {
1083
+ }
1084
+ }
1085
+
1086
+ private void emitAnnotationCreated() {
1087
+ try {
1088
+ if (inkStrokePageIndex < 0 || inkStrokePoints.size() < 2) return;
1089
+ float minX = 1f, minY = 1f, maxX = 0f, maxY = 0f;
1090
+ for (float[] p : inkStrokePoints) {
1091
+ if (p[0] < minX) minX = p[0];
1092
+ if (p[0] > maxX) maxX = p[0];
1093
+ if (p[1] < minY) minY = p[1];
1094
+ if (p[1] > maxY) maxY = p[1];
1095
+ }
1096
+ float width = Math.max(0.0005f, maxX - minX);
1097
+ float height = Math.max(0.0005f, maxY - minY);
1098
+
1099
+ WritableMap event = Arguments.createMap();
1100
+ event.putString("id", java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 7));
1101
+ event.putInt("pageIndex", inkStrokePageIndex);
1102
+ event.putString("type", "ink");
1103
+ event.putString("color", annotationColor);
1104
+
1105
+ WritableMap rect = Arguments.createMap();
1106
+ rect.putDouble("x", minX);
1107
+ rect.putDouble("y", minY);
1108
+ rect.putDouble("width", width);
1109
+ rect.putDouble("height", height);
1110
+ event.putMap("rect", rect);
1111
+
1112
+ WritableArray path = Arguments.createArray();
1113
+ for (float[] p : inkStrokePoints) {
1114
+ WritableMap point = Arguments.createMap();
1115
+ point.putDouble("x", p[0]);
1116
+ point.putDouble("y", p[1]);
1117
+ path.pushMap(point);
1118
+ }
1119
+ event.putArray("path", path);
1120
+ event.putDouble("opacity", annotationOpacity);
1121
+ event.putDouble("strokeWidth", inkStrokeWidth);
1122
+ event.putDouble("createdAt", System.currentTimeMillis());
1123
+
1124
+ reactContext.getJSModule(RCTEventEmitter.class)
1125
+ .receiveEvent(getId(), "onAnnotationCreated", event);
1126
+ } catch (Throwable ignored) {
1127
+ }
1128
+ }
1129
+
1130
+ private void emitTap(int pageIndex, float x, float y) {
1131
+ try {
1132
+ WritableMap event = Arguments.createMap();
1133
+ event.putInt("pageIndex", pageIndex);
1134
+ event.putDouble("x", x);
1135
+ event.putDouble("y", y);
1136
+ reactContext.getJSModule(RCTEventEmitter.class)
1137
+ .receiveEvent(getId(), "onTap", event);
1138
+ } catch (Throwable ignored) {
1139
+ }
1140
+ }
1141
+
1142
+ private void emitAnnotationCreatedForTool(String tool, int pageIndex, float nx, float ny) {
1143
+ try {
1144
+ WritableMap event = Arguments.createMap();
1145
+ event.putString("id", java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 7));
1146
+ event.putInt("pageIndex", pageIndex);
1147
+ event.putString("type", tool);
1148
+ event.putString("color", annotationColor);
1149
+
1150
+ WritableMap rect = Arguments.createMap();
1151
+ rect.putDouble("x", nx);
1152
+ rect.putDouble("y", ny);
1153
+ rect.putDouble("width", 0.05);
1154
+ rect.putDouble("height", 0.02);
1155
+ event.putMap("rect", rect);
1156
+
1157
+ event.putString("content", "");
1158
+ event.putDouble("createdAt", System.currentTimeMillis());
1159
+
1160
+ reactContext.getJSModule(RCTEventEmitter.class)
1161
+ .receiveEvent(getId(), "onAnnotationCreated", event);
1162
+ } catch (Throwable ignored) {
1163
+ }
1164
+ }
1165
+
1166
+ private Annotation findAnnotationAt(int pageIndex, float nx, float ny) {
1167
+ for (Annotation annotation : annotations) {
1168
+ if (annotation.pageIndex != pageIndex) continue;
1169
+ if (annotation.rects == null || annotation.rects.isEmpty()) continue;
1170
+ for (NormalizedRect rect : annotation.rects) {
1171
+ if (nx >= rect.x && nx <= rect.x + rect.width &&
1172
+ ny >= rect.y && ny <= rect.y + rect.height) {
1173
+ return annotation;
1174
+ }
1175
+ }
1176
+ }
1177
+ return null;
1178
+ }
1179
+
1180
+ private void emitAnnotationTap(Annotation annotation) {
1181
+ try {
1182
+ WritableMap event = Arguments.createMap();
1183
+ event.putString("id", annotation.id);
1184
+ event.putInt("pageIndex", annotation.pageIndex);
1185
+ event.putString("type", annotation.type);
1186
+ event.putString("color", annotation.color);
1187
+ reactContext.getJSModule(RCTEventEmitter.class)
1188
+ .receiveEvent(getId(), "onAnnotationTap", event);
1189
+ } catch (Throwable ignored) {
1190
+ }
1191
+ }
1192
+
1193
+ private ScaleGestureDetector createScaleDetector(Context context) {
1194
+ return new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
1195
+ @Override
1196
+ public boolean onScaleBegin(ScaleGestureDetector detector) {
1197
+ wasScaling = true;
1198
+ return true;
1199
+ }
1200
+
1201
+ @Override
1202
+ public boolean onScale(ScaleGestureDetector detector) {
1203
+ float oldContentWidth = Math.max(1f, contentWidth);
1204
+ float oldContentHeight = Math.max(1f, contentHeight);
1205
+ float focusRatioX = (offsetX + detector.getFocusX()) / oldContentWidth;
1206
+ float focusRatioY = (offsetY + detector.getFocusY()) / oldContentHeight;
1207
+ zoom = clamp(zoom * detector.getScaleFactor(), 0.5f, 5.0f);
1208
+ layoutDirty = true;
1209
+ ensureLayout();
1210
+ offsetX = focusRatioX * contentWidth - detector.getFocusX();
1211
+ offsetY = focusRatioY * contentHeight - detector.getFocusY();
1212
+ clampOffsets();
1213
+ invalidate();
1214
+ return true;
1215
+ }
1216
+ });
1217
+ }
1218
+
1219
+ private void ensureLayout() {
1220
+ if (!layoutDirty) return;
1221
+ pageFrames.clear();
1222
+ PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
1223
+ if (state == null || state.document == null || getWidth() <= 0) {
1224
+ contentWidth = getWidth();
1225
+ contentHeight = getHeight();
1226
+ layoutDirty = false;
1227
+ return;
1228
+ }
1229
+
1230
+ try {
1231
+ synchronized (state.pdfiumLock) {
1232
+ PdfDocument document = state.document;
1233
+ int pageCount = state.pdfium.getPageCount(document);
1234
+ float maxWidth = getWidth();
1235
+ int availableWidth = Math.max(1, getWidth() - PAGE_PADDING * 2);
1236
+
1237
+ if ("single".equals(viewMode)) {
1238
+ float cellHeight = getHeight();
1239
+ for (int i = 0; i < pageCount; i += 1) {
1240
+ state.pdfium.openPage(document, i);
1241
+ int pageWidth = Math.max(1, state.pdfium.getPageWidthPoint(document, i));
1242
+ int pageHeight = Math.max(1, state.pdfium.getPageHeightPoint(document, i));
1243
+ float baseScale = availableWidth / (float) pageWidth;
1244
+ float width = pageWidth * baseScale * zoom;
1245
+ float height = pageHeight * baseScale * zoom;
1246
+ maxWidth = Math.max(maxWidth, width + PAGE_PADDING * 2);
1247
+ float left = Math.max(PAGE_PADDING, (maxWidth - width) / 2f);
1248
+ float top = i * cellHeight + (cellHeight - height) / 2f;
1249
+ pageFrames.add(new PageFrame(i, left, top, width, height));
1250
+ }
1251
+ contentWidth = maxWidth;
1252
+ contentHeight = Math.max(getHeight(), pageCount * cellHeight);
1253
+ } else {
1254
+ float y = PAGE_PADDING;
1255
+ for (int i = 0; i < pageCount; i += 1) {
1256
+ state.pdfium.openPage(document, i);
1257
+ int pageWidth = Math.max(1, state.pdfium.getPageWidthPoint(document, i));
1258
+ int pageHeight = Math.max(1, state.pdfium.getPageHeightPoint(document, i));
1259
+ float baseScale = availableWidth / (float) pageWidth;
1260
+ float width = pageWidth * baseScale * zoom;
1261
+ float height = pageHeight * baseScale * zoom;
1262
+ maxWidth = Math.max(maxWidth, width + PAGE_PADDING * 2);
1263
+ float left = Math.max(PAGE_PADDING, (maxWidth - width) / 2f);
1264
+ pageFrames.add(new PageFrame(i, left, y, width, height));
1265
+ y += height + PAGE_GAP;
1266
+ }
1267
+ contentWidth = maxWidth;
1268
+ contentHeight = Math.max(getHeight(), y + PAGE_PADDING);
1269
+ }
1270
+ }
1271
+ } catch (Throwable error) {
1272
+ Log.w(TAG, "Failed to layout dedicated PDF viewer", error);
1273
+ contentWidth = getWidth();
1274
+ contentHeight = getHeight();
1275
+ }
1276
+ layoutDirty = false;
1277
+ clampOffsets();
1278
+ }
1279
+
1280
+ private void requestRender(PageFrame frame, String key) {
1281
+ if (loadingKeys.contains(key)) return;
1282
+ PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
1283
+ if (state == null || state.document == null || state.isSearching) return;
1284
+ loadingKeys.add(key);
1285
+ final int generationAtStart = renderGeneration;
1286
+ int[] renderSize = PapyrusRenderMath.constrainRenderSize(
1287
+ Math.max(1, Math.round(frame.width)),
1288
+ Math.max(1, Math.round(frame.height))
1289
+ );
1290
+ int renderWidth = renderSize[0];
1291
+ int renderHeight = renderSize[1];
1292
+
1293
+ RENDER_EXECUTOR.execute(() -> {
1294
+ Bitmap rendered = null;
1295
+ try {
1296
+ synchronized (state.pdfiumLock) {
1297
+ if (state.document == null) return;
1298
+ state.pdfium.openPage(state.document, frame.index);
1299
+ rendered = Bitmap.createBitmap(renderWidth, renderHeight, Bitmap.Config.ARGB_8888);
1300
+ state.pdfium.renderPageBitmap(state.document, rendered, frame.index, 0, 0, renderWidth, renderHeight, true);
1301
+ }
1302
+ Bitmap finalRendered = rendered;
1303
+ post(() -> {
1304
+ loadingKeys.remove(key);
1305
+ if (finalRendered != null && !finalRendered.isRecycled()) {
1306
+ RENDER_CACHE.put(key, finalRendered);
1307
+ lastPageBitmap.put(frame.index, finalRendered);
1308
+ }
1309
+ if (generationAtStart == renderGeneration) {
1310
+ invalidate();
1311
+ }
1312
+ });
1313
+ } catch (Throwable error) {
1314
+ Bitmap failed = rendered;
1315
+ post(() -> {
1316
+ loadingKeys.remove(key);
1317
+ if (failed != null && !failed.isRecycled()) failed.recycle();
1318
+ Log.w(TAG, "Failed to render dedicated PDF page", error);
1319
+ });
1320
+ }
1321
+ });
1322
+ }
1323
+
1324
+ private String buildRenderKey(PageFrame frame) {
1325
+ PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
1326
+ int docIdentity = state == null || state.document == null ? 0 : System.identityHashCode(state.document);
1327
+ String source = state == null || state.sourcePath == null ? "" : state.sourcePath;
1328
+ return source + ":" + docIdentity + ":" + frame.index + ":" + Math.round(frame.width) + "x" + Math.round(frame.height);
1329
+ }
1330
+
1331
+ private void clampOffsets() {
1332
+ offsetX = clamp(offsetX, 0f, Math.max(0f, contentWidth - getWidth()));
1333
+ float maxY = Math.max(0f, contentHeight - getHeight());
1334
+ if ("single".equals(viewMode) && !pageFrames.isEmpty()) {
1335
+ offsetY = clamp(offsetY, 0f, maxY);
1336
+ } else {
1337
+ offsetY = clamp(offsetY, 0f, maxY);
1338
+ }
1339
+ }
1340
+
1341
+ private void snapToPage(int pageIndex) {
1342
+ if (pageFrames.isEmpty() || pageIndex < 0 || pageIndex >= pageFrames.size()) return;
1343
+ if ("single".equals(viewMode)) {
1344
+ float targetY = pageIndex * getHeight();
1345
+ float maxY = Math.max(0f, contentHeight - getHeight());
1346
+ targetY = clamp(targetY, 0f, maxY);
1347
+ offsetY = targetY;
1348
+ } else {
1349
+ PageFrame frame = pageFrames.get(pageIndex);
1350
+ float targetY = frame.top - PAGE_PADDING;
1351
+ float maxY = Math.max(0f, contentHeight - getHeight());
1352
+ targetY = clamp(targetY, 0f, maxY);
1353
+ offsetY = targetY;
1354
+ }
1355
+ clampOffsets();
1356
+ invalidate();
1357
+ emitPageChanged(pageIndex + 1);
1358
+ }
1359
+
1360
+ private void emitScrollEvent(float offsetYValue) {
1361
+ try {
1362
+ if (pendingScrollEvent != null) {
1363
+ eventThrottleHandler.removeCallbacks(pendingScrollEvent);
1364
+ }
1365
+ pendingScrollEvent = () -> {
1366
+ WritableMap event = Arguments.createMap();
1367
+ event.putDouble("offsetY", offsetYValue);
1368
+ reactContext.getJSModule(RCTEventEmitter.class)
1369
+ .receiveEvent(getId(), "onScroll", event);
1370
+ pendingScrollEvent = null;
1371
+ };
1372
+ eventThrottleHandler.postDelayed(pendingScrollEvent, 16);
1373
+ } catch (Throwable ignored) {
1374
+ }
1375
+ }
1376
+
1377
+ private static float clamp(float value, float min, float max) {
1378
+ return Math.max(min, Math.min(max, value));
1379
+ }
1380
+
1381
+ private static int resolveBackgroundColor(String theme) {
1382
+ if ("dark".equals(theme) || "high-contrast".equals(theme)) return Color.rgb(15, 17, 21);
1383
+ if ("sepia".equals(theme)) return Color.rgb(232, 220, 196);
1384
+ return Color.rgb(233, 236, 239);
1385
+ }
1386
+
1387
+ private static int resolvePageColor(String theme) {
1388
+ if ("dark".equals(theme) || "high-contrast".equals(theme)) return Color.rgb(24, 24, 27);
1389
+ if ("sepia".equals(theme)) return Color.rgb(245, 236, 214);
1390
+ return Color.WHITE;
1391
+ }
1392
+
1393
+ private static ColorMatrixColorFilter resolveThemeFilter(String theme) {
1394
+ if ("sepia".equals(theme)) return SEPIA_FILTER;
1395
+ if ("dark".equals(theme)) return DARK_FILTER;
1396
+ if ("high-contrast".equals(theme)) return HIGH_CONTRAST_FILTER;
1397
+ return null;
1398
+ }
1399
+
1400
+ private static ColorMatrixColorFilter createSepiaFilter() {
1401
+ ColorMatrix matrix = new ColorMatrix();
1402
+ matrix.set(new float[] {
1403
+ 0.393f, 0.769f, 0.189f, 0, 0,
1404
+ 0.349f, 0.686f, 0.168f, 0, 0,
1405
+ 0.272f, 0.534f, 0.131f, 0, 0,
1406
+ 0, 0, 0, 1, 0
1407
+ });
1408
+ return new ColorMatrixColorFilter(matrix);
1409
+ }
1410
+
1411
+ private static ColorMatrixColorFilter createDarkFilter() {
1412
+ ColorMatrix invert = new ColorMatrix(new float[] {
1413
+ -1, 0, 0, 0, 255,
1414
+ 0, -1, 0, 0, 255,
1415
+ 0, 0, -1, 0, 255,
1416
+ 0, 0, 0, 1, 0
1417
+ });
1418
+ return new ColorMatrixColorFilter(invert);
1419
+ }
1420
+
1421
+ private static ColorMatrixColorFilter createHighContrastFilter() {
1422
+ return createDarkFilter();
1423
+ }
1424
+
1425
+ private final Paint overlayPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
1426
+ private List<SearchResult> searchResults = new ArrayList<>();
1427
+ private List<Annotation> annotations = new ArrayList<>();
1428
+
1429
+ public void setSearchResults(List<SearchResult> results) {
1430
+ searchResults = results != null ? results : new ArrayList<>();
1431
+ invalidate();
1432
+ }
1433
+
1434
+ public void setAnnotations(List<Annotation> items) {
1435
+ annotations = items != null ? items : new ArrayList<>();
1436
+ invalidate();
1437
+ }
1438
+
1439
+ private void drawOverlays(Canvas canvas, PageFrame frame, int left, int top) {
1440
+ float scaleX = frame.width;
1441
+ float scaleY = frame.height;
1442
+
1443
+ for (SearchResult result : searchResults) {
1444
+ if (result.pageIndex != frame.index) continue;
1445
+ overlayPaint.setColor(Color.argb(128, 255, 220, 50));
1446
+ for (NormalizedRect rect : result.rects) {
1447
+ float rLeft = left + rect.x * scaleX;
1448
+ float rTop = top + rect.y * scaleY;
1449
+ float rRight = rLeft + rect.width * scaleX;
1450
+ float rBottom = rTop + rect.height * scaleY;
1451
+ canvas.drawRect(rLeft, rTop, rRight, rBottom, overlayPaint);
1452
+ }
1453
+ }
1454
+
1455
+ if (selectPageIndex == frame.index && !selectedRects.isEmpty()) {
1456
+ overlayPaint.setColor(Color.argb(120, 66, 133, 244));
1457
+ for (NormalizedRect rect : selectedRects) {
1458
+ float rLeft = left + rect.x * scaleX;
1459
+ float rTop = top + rect.y * scaleY;
1460
+ float rRight = rLeft + rect.width * scaleX;
1461
+ float rBottom = rTop + rect.height * scaleY;
1462
+ canvas.drawRect(rLeft, rTop, rRight, rBottom, overlayPaint);
1463
+ }
1464
+ // Draw selection handles
1465
+ float density = getResources().getDisplayMetrics().density;
1466
+ float radius = HANDLE_RADIUS_DP * density;
1467
+ overlayPaint.setColor(HANDLE_COLOR);
1468
+ overlayPaint.setStyle(Paint.Style.FILL);
1469
+ // Start handle (top-left of first rect)
1470
+ NormalizedRect firstRect = selectedRects.get(0);
1471
+ float hStartCx = left + firstRect.x * scaleX;
1472
+ float hStartCy = top + firstRect.y * scaleY;
1473
+ canvas.drawCircle(hStartCx, hStartCy, radius, overlayPaint);
1474
+ // End handle (bottom-right of last rect)
1475
+ NormalizedRect lastRect = selectedRects.get(selectedRects.size() - 1);
1476
+ float hEndCx = left + (lastRect.x + lastRect.width) * scaleX;
1477
+ float hEndCy = top + (lastRect.y + lastRect.height) * scaleY;
1478
+ canvas.drawCircle(hEndCx, hEndCy, radius, overlayPaint);
1479
+ overlayPaint.setStyle(Paint.Style.FILL);
1480
+ }
1481
+
1482
+ for (Annotation annotation : annotations) {
1483
+ if (annotation.pageIndex != frame.index) continue;
1484
+ int color = parseColor(annotation.color, Color.YELLOW);
1485
+ if ("ink".equals(annotation.type) && annotation.path != null && annotation.path.size() >= 2) {
1486
+ overlayPaint.setColor(color);
1487
+ overlayPaint.setAlpha(Math.round(annotation.opacity * 255));
1488
+ overlayPaint.setStyle(Paint.Style.STROKE);
1489
+ overlayPaint.setStrokeCap(Paint.Cap.ROUND);
1490
+ overlayPaint.setStrokeJoin(Paint.Join.ROUND);
1491
+ float minScale = Math.min(scaleX, scaleY);
1492
+ overlayPaint.setStrokeWidth(annotation.strokeWidth * minScale);
1493
+ Path inkPath = new Path();
1494
+ boolean first = true;
1495
+ for (NormalizedPoint p : annotation.path) {
1496
+ float px = left + p.x * scaleX;
1497
+ float py = top + p.y * scaleY;
1498
+ if (first) {
1499
+ inkPath.moveTo(px, py);
1500
+ first = false;
1501
+ } else {
1502
+ inkPath.lineTo(px, py);
1503
+ }
1504
+ }
1505
+ canvas.drawPath(inkPath, overlayPaint);
1506
+ overlayPaint.setAlpha(255);
1507
+ overlayPaint.setStyle(Paint.Style.FILL);
1508
+ continue;
1509
+ }
1510
+ overlayPaint.setColor(Color.argb(140, Color.red(color), Color.green(color), Color.blue(color)));
1511
+ for (NormalizedRect rect : annotation.rects) {
1512
+ float rLeft = left + rect.x * scaleX;
1513
+ float rTop = top + rect.y * scaleY;
1514
+ float rRight = rLeft + rect.width * scaleX;
1515
+ float rBottom = rTop + rect.height * scaleY;
1516
+ if ("underline".equals(annotation.type)) {
1517
+ overlayPaint.setStyle(Paint.Style.STROKE);
1518
+ overlayPaint.setStrokeWidth(Math.max(2f, scaleY * 0.008f));
1519
+ canvas.drawLine(rLeft, rBottom - 2, rRight, rBottom - 2, overlayPaint);
1520
+ overlayPaint.setStyle(Paint.Style.FILL);
1521
+ } else if ("strikeout".equals(annotation.type)) {
1522
+ overlayPaint.setStyle(Paint.Style.STROKE);
1523
+ overlayPaint.setStrokeWidth(Math.max(2f, scaleY * 0.008f));
1524
+ canvas.drawLine(rLeft, (rTop + rBottom) / 2f, rRight, (rTop + rBottom) / 2f, overlayPaint);
1525
+ overlayPaint.setStyle(Paint.Style.FILL);
1526
+ } else {
1527
+ canvas.drawRect(rLeft, rTop, rRight, rBottom, overlayPaint);
1528
+ }
1529
+ }
1530
+ }
1531
+
1532
+ if (isDrawingInk && inkStrokePageIndex == frame.index && inkStrokePoints.size() >= 2) {
1533
+ overlayPaint.setColor(parseColor(annotationColor, Color.BLACK));
1534
+ overlayPaint.setAlpha(Math.round(annotationOpacity * 255));
1535
+ overlayPaint.setStyle(Paint.Style.STROKE);
1536
+ overlayPaint.setStrokeCap(Paint.Cap.ROUND);
1537
+ overlayPaint.setStrokeJoin(Paint.Join.ROUND);
1538
+ float minScale = Math.min(scaleX, scaleY);
1539
+ overlayPaint.setStrokeWidth(inkStrokeWidth * minScale);
1540
+ Path activePath = new Path();
1541
+ boolean first = true;
1542
+ for (float[] p : inkStrokePoints) {
1543
+ float px = left + p[0] * scaleX;
1544
+ float py = top + p[1] * scaleY;
1545
+ if (first) {
1546
+ activePath.moveTo(px, py);
1547
+ first = false;
1548
+ } else {
1549
+ activePath.lineTo(px, py);
1550
+ }
1551
+ }
1552
+ canvas.drawPath(activePath, overlayPaint);
1553
+ overlayPaint.setAlpha(255);
1554
+ overlayPaint.setStyle(Paint.Style.FILL);
1555
+ }
1556
+ }
1557
+
1558
+ private static int parseColor(String colorString, int fallback) {
1559
+ try {
1560
+ return Color.parseColor(colorString);
1561
+ } catch (IllegalArgumentException ignored) {
1562
+ return fallback;
1563
+ }
1564
+ }
1565
+
1566
+ static final class NormalizedRect {
1567
+ final float x, y, width, height;
1568
+ NormalizedRect(float x, float y, float width, float height) {
1569
+ this.x = x; this.y = y; this.width = width; this.height = height;
1570
+ }
1571
+ }
1572
+
1573
+ static final class SearchResult {
1574
+ final int pageIndex;
1575
+ final List<NormalizedRect> rects;
1576
+ SearchResult(int pageIndex, List<NormalizedRect> rects) {
1577
+ this.pageIndex = pageIndex;
1578
+ this.rects = rects;
1579
+ }
1580
+ }
1581
+
1582
+ static final class Annotation {
1583
+ final String id;
1584
+ final int pageIndex;
1585
+ final String type;
1586
+ final String color;
1587
+ final List<NormalizedRect> rects;
1588
+ final List<NormalizedPoint> path;
1589
+ final float strokeWidth;
1590
+ final float opacity;
1591
+ Annotation(String id, int pageIndex, String type, String color, List<NormalizedRect> rects) {
1592
+ this(id, pageIndex, type, color, rects, null, 0.006f, 0.85f);
1593
+ }
1594
+ Annotation(String id, int pageIndex, String type, String color, List<NormalizedRect> rects, List<NormalizedPoint> path, float strokeWidth, float opacity) {
1595
+ this.id = id;
1596
+ this.pageIndex = pageIndex;
1597
+ this.type = type;
1598
+ this.color = color;
1599
+ this.rects = rects;
1600
+ this.path = path;
1601
+ this.strokeWidth = strokeWidth;
1602
+ this.opacity = opacity;
1603
+ }
1604
+ }
1605
+
1606
+ static final class NormalizedPoint {
1607
+ final float x, y;
1608
+ NormalizedPoint(float x, float y) {
1609
+ this.x = x; this.y = y;
1610
+ }
1611
+ }
1612
+
1613
+ private static final class PageFrame {
1614
+ final int index;
1615
+ final float left;
1616
+ final float top;
1617
+ final float width;
1618
+ final float height;
1619
+
1620
+ PageFrame(int index, float left, float top, float width, float height) {
1621
+ this.index = index;
1622
+ this.left = left;
1623
+ this.top = top;
1624
+ this.width = width;
1625
+ this.height = height;
1626
+ }
1627
+ }
1628
+ }