@papyrus-sdk/engine-native 0.2.17 → 0.2.19

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.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Papyrus Engine Native
2
2
 
3
3
  React Native native engine for PDF rendering (PDFKit on iOS, PDFium on Android),
4
- plus a WebView runtime for EPUB/TXT via `MobileDocumentEngine`.
4
+ plus a WebView runtime for EPUB/TXT/CBZ via `MobileDocumentEngine`.
5
5
 
6
6
  ## Install
7
7
 
@@ -11,12 +11,20 @@ npm install @papyrus-sdk/engine-native @papyrus-sdk/core @papyrus-sdk/types
11
11
 
12
12
  `@papyrus-sdk/core` and `@papyrus-sdk/types` are required peer dependencies.
13
13
 
14
- For EPUB/TXT on mobile, also install:
14
+ For EPUB/TXT/CBZ on mobile, also install:
15
15
 
16
16
  ```bash
17
17
  npm install react-native-webview
18
18
  ```
19
19
 
20
+ CBZ files use the same WebView dependency and are loaded with
21
+ `{ type: 'comic', source: { uri: 'file:///.../book.cbz' } }`. CBR is not part
22
+ of the base mobile runtime because its libarchive worker/WASM payload is
23
+ optional and substantially larger.
24
+
25
+ For CBR, install `@papyrus-sdk/engine-cbr-mobile` and pass its three runtime
26
+ asset URLs through `webViewRuntimeConfig` as shown in that package's README.
27
+
20
28
  ## Usage
21
29
 
22
30
  ```ts
@@ -0,0 +1,9 @@
1
+ package com.papyrus.engine;
2
+
3
+ final class PapyrusBitmapOwnership {
4
+ private PapyrusBitmapOwnership() {}
5
+
6
+ static boolean shouldRecycleEvictedBitmap(boolean cached, int activeReferences) {
7
+ return !cached && activeReferences == 0;
8
+ }
9
+ }
@@ -39,6 +39,18 @@ final class PapyrusEngineStore {
39
39
  return ENGINES.get(engineId);
40
40
  }
41
41
 
42
+ static int engineCount() {
43
+ return ENGINES.size();
44
+ }
45
+
46
+ static int loadedDocumentCount() {
47
+ int count = 0;
48
+ for (EngineState state : ENGINES.values()) {
49
+ if (state.document != null) count++;
50
+ }
51
+ return count;
52
+ }
53
+
42
54
  static void destroyEngine(String engineId) {
43
55
  EngineState state = ENGINES.remove(engineId);
44
56
  if (state == null) return;
@@ -4,6 +4,7 @@ import android.content.ContentResolver;
4
4
  import android.content.Context;
5
5
  import android.net.Uri;
6
6
  import android.os.ParcelFileDescriptor;
7
+ import android.util.Base64;
7
8
  import android.view.View;
8
9
 
9
10
  import com.facebook.react.bridge.Arguments;
@@ -22,6 +23,7 @@ import com.facebook.react.uimanager.UIManagerModule;
22
23
  import com.shockwave.pdfium.PdfDocument;
23
24
 
24
25
  import java.io.File;
26
+ import java.io.FileInputStream;
25
27
  import java.io.FileOutputStream;
26
28
  import java.io.IOException;
27
29
  import java.io.InputStream;
@@ -33,6 +35,7 @@ import java.util.concurrent.Executors;
33
35
  public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
34
36
  private final ReactApplicationContext reactContext;
35
37
  private final ExecutorService executor = Executors.newSingleThreadExecutor();
38
+ private long renderRequestCounter = 0;
36
39
 
37
40
  public PapyrusNativeEngineModule(ReactApplicationContext reactContext) {
38
41
  super(reactContext);
@@ -54,6 +57,61 @@ public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
54
57
  PapyrusEngineStore.destroyEngine(engineId);
55
58
  }
56
59
 
60
+ @ReactMethod
61
+ public void readFileChunk(String uriValue, double offsetValue, int length, Promise promise) {
62
+ executor.execute(() -> {
63
+ try {
64
+ if (length <= 0 || length > 4 * 1024 * 1024) {
65
+ throw new IOException("Invalid file chunk length");
66
+ }
67
+
68
+ Uri uri = Uri.parse(uriValue);
69
+ InputStream inputStream;
70
+ if ("file".equalsIgnoreCase(uri.getScheme())) {
71
+ inputStream = new FileInputStream(new File(uri.getPath()));
72
+ } else if ("content".equalsIgnoreCase(uri.getScheme())) {
73
+ ContentResolver resolver = reactContext.getContentResolver();
74
+ inputStream = resolver.openInputStream(uri);
75
+ if (inputStream == null) throw new IOException("Unable to read content URI");
76
+ } else if ("android.resource".equalsIgnoreCase(uri.getScheme())) {
77
+ ContentResolver resolver = reactContext.getContentResolver();
78
+ inputStream = resolver.openInputStream(uri);
79
+ if (inputStream == null) throw new IOException("Unable to read Android resource URI");
80
+ } else {
81
+ throw new IOException("Unsupported local file URI");
82
+ }
83
+
84
+ try (InputStream stream = inputStream) {
85
+ long remaining = Math.max(0L, (long) offsetValue);
86
+ while (remaining > 0) {
87
+ long skipped = stream.skip(remaining);
88
+ if (skipped <= 0) {
89
+ if (stream.read() < 0) break;
90
+ skipped = 1;
91
+ }
92
+ remaining -= skipped;
93
+ }
94
+
95
+ byte[] buffer = new byte[length];
96
+ int read = 0;
97
+ while (read < length) {
98
+ int count = stream.read(buffer, read, length - read);
99
+ if (count < 0) break;
100
+ if (count == 0) continue;
101
+ read += count;
102
+ }
103
+
104
+ WritableMap result = Arguments.createMap();
105
+ result.putString("data", Base64.encodeToString(buffer, 0, read, Base64.NO_WRAP));
106
+ result.putBoolean("done", read < length);
107
+ promise.resolve(result);
108
+ }
109
+ } catch (Throwable error) {
110
+ promise.reject("papyrus_file_chunk_failed", error);
111
+ }
112
+ });
113
+ }
114
+
57
115
  @ReactMethod
58
116
  public void load(final String engineId, final ReadableMap source, final Promise promise) {
59
117
  executor.execute(() -> {
@@ -91,24 +149,79 @@ public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
91
149
  return state.pdfium.getPageCount(state.document);
92
150
  }
93
151
 
152
+ @ReactMethod(isBlockingSynchronousMethod = true)
153
+ public WritableMap getLifecycleStats() {
154
+ WritableMap result = Arguments.createMap();
155
+ result.putInt("engineStates", PapyrusEngineStore.engineCount());
156
+ result.putInt("loadedDocuments", PapyrusEngineStore.loadedDocumentCount());
157
+ for (java.util.Map.Entry<String, Integer> entry : PapyrusPageView.lifecycleStats().entrySet()) {
158
+ result.putInt(entry.getKey(), entry.getValue());
159
+ }
160
+ return result;
161
+ }
162
+
94
163
  @ReactMethod
95
- public void renderPage(final String engineId, final int pageIndex, final int target, final float scale, final float zoom, final int rotation) {
164
+ public void renderPage(final String engineId, final int pageIndex, final int target, final float scale, final float zoom, final int rotation, final String requestId, final ReadableMap telemetryContext, final Promise promise) {
96
165
  final PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
97
- if (state == null) return;
166
+ if (state == null) {
167
+ promise.reject("papyrus_no_engine", "Engine not found");
168
+ return;
169
+ }
98
170
  UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
99
- if (uiManager == null) return;
171
+ if (uiManager == null) {
172
+ promise.reject("papyrus_render_error", "UI manager unavailable");
173
+ return;
174
+ }
100
175
 
176
+ final String resolvedRequestId = requestId == null || requestId.isEmpty()
177
+ ? "native-render-" + (++renderRequestCounter)
178
+ : requestId;
179
+ final PapyrusNativeRenderTelemetry telemetry = PapyrusNativeRenderTelemetry.from(
180
+ telemetryContext,
181
+ resolvedRequestId,
182
+ null,
183
+ pageIndex,
184
+ target,
185
+ 0
186
+ );
187
+ telemetry.emit("native.render.request");
188
+ final PapyrusRenderCompletion completion = new PapyrusRenderCompletion(
189
+ status -> resolveRenderPromise(promise, resolvedRequestId, status),
190
+ error -> promise.reject("papyrus_render_error", error)
191
+ );
192
+
193
+ telemetry.emit("native.render.uiblock.enqueue");
101
194
  uiManager.addUIBlock(new UIBlock() {
102
195
  @Override
103
196
  public void execute(com.facebook.react.uimanager.NativeViewHierarchyManager nativeViewHierarchyManager) {
104
- View view = nativeViewHierarchyManager.resolveView(target);
105
- if (view instanceof PapyrusPageView) {
106
- ((PapyrusPageView) view).render(state, pageIndex, scale, zoom, rotation);
197
+ telemetry.traceBegin("PapyrusRenderUiBlock");
198
+ try {
199
+ telemetry.emit("native.render.uiblock.start");
200
+ View view = nativeViewHierarchyManager.resolveView(target);
201
+ if (view instanceof PapyrusPageView) {
202
+ telemetry.emit("native.render.uiblock.surface.resolved");
203
+ ((PapyrusPageView) view).render(state, pageIndex, scale, zoom, rotation, completion, telemetry);
204
+ } else {
205
+ telemetry.emit("native.render.stale");
206
+ completion.complete(PapyrusRenderCompletion.Status.STALE);
207
+ }
208
+ } finally {
209
+ telemetry.traceEnd();
107
210
  }
108
211
  }
109
212
  });
110
213
  }
111
214
 
215
+ private void resolveRenderPromise(Promise promise, String requestId, PapyrusRenderCompletion.Status status) {
216
+ WritableMap result = Arguments.createMap();
217
+ String value = status == PapyrusRenderCompletion.Status.READY
218
+ ? "ready"
219
+ : status == PapyrusRenderCompletion.Status.STALE ? "stale" : "cancelled";
220
+ result.putString("status", value);
221
+ result.putString("requestId", requestId);
222
+ promise.resolve(result);
223
+ }
224
+
112
225
  @ReactMethod
113
226
  public void renderTextLayer(String engineId, int pageIndex, int target, float scale, float zoom, int rotation) {
114
227
  }
@@ -11,7 +11,9 @@ import expo.modules.kotlin.Promise
11
11
  import expo.modules.kotlin.modules.Module
12
12
  import expo.modules.kotlin.modules.ModuleDefinition
13
13
  import expo.modules.kotlin.typedarray.Uint8Array
14
+ import android.util.Base64
14
15
  import java.io.File
16
+ import java.io.FileInputStream
15
17
  import java.io.FileOutputStream
16
18
  import java.io.IOException
17
19
  import java.io.InputStream
@@ -36,6 +38,54 @@ class PapyrusNativeEngineModule : Module() {
36
38
  PapyrusEngineStore.destroyEngine(engineId)
37
39
  }
38
40
 
41
+ AsyncFunction("readFileChunk") { uriValue: String, offsetValue: Double, length: Int ->
42
+ if (length <= 0 || length > 4 * 1024 * 1024) {
43
+ throw IOException("Invalid file chunk length")
44
+ }
45
+
46
+ val uri = Uri.parse(uriValue)
47
+ val inputStream: InputStream = when (uri.scheme?.lowercase()) {
48
+ "file" -> FileInputStream(File(uri.path ?: throw IOException("Invalid file URI")))
49
+ "content" -> {
50
+ val context = appContext.reactContext ?: throw IOException("React context missing")
51
+ context.contentResolver.openInputStream(uri)
52
+ ?: throw IOException("Unable to read content URI")
53
+ }
54
+ "android.resource" -> {
55
+ val context = appContext.reactContext ?: throw IOException("React context missing")
56
+ context.contentResolver.openInputStream(uri)
57
+ ?: throw IOException("Unable to read Android resource URI")
58
+ }
59
+ else -> throw IOException("Unsupported local file URI")
60
+ }
61
+
62
+ inputStream.use { stream ->
63
+ var remaining = maxOf(0L, offsetValue.toLong())
64
+ while (remaining > 0) {
65
+ val skipped = stream.skip(remaining)
66
+ if (skipped <= 0L) {
67
+ if (stream.read() < 0) break
68
+ remaining -= 1
69
+ } else {
70
+ remaining -= skipped
71
+ }
72
+ }
73
+
74
+ val buffer = ByteArray(length)
75
+ var read = 0
76
+ while (read < length) {
77
+ val count = stream.read(buffer, read, length - read)
78
+ if (count < 0) break
79
+ if (count > 0) read += count
80
+ }
81
+
82
+ mapOf(
83
+ "data" to Base64.encodeToString(buffer, 0, read, Base64.NO_WRAP),
84
+ "done" to (read < length),
85
+ )
86
+ }
87
+ }
88
+
39
89
  AsyncFunction("load") { engineId: String, source: Map<String, Any?>, promise: Promise ->
40
90
  executor.execute {
41
91
  try {
@@ -70,6 +120,15 @@ class PapyrusNativeEngineModule : Module() {
70
120
  state.pdfium.getPageCount(state.document)
71
121
  }
72
122
 
123
+ Function("getLifecycleStats") {
124
+ val stats = mutableMapOf<String, Any?>(
125
+ "engineStates" to PapyrusEngineStore.engineCount(),
126
+ "loadedDocuments" to PapyrusEngineStore.loadedDocumentCount(),
127
+ )
128
+ PapyrusPageView.lifecycleStats().forEach { (key, value) -> stats[key] = value }
129
+ stats
130
+ }
131
+
73
132
  AsyncFunction("renderPage") { engineId: String, pageIndex: Int, target: Int, scale: Double, zoom: Double, rotation: Int ->
74
133
  val state = PapyrusEngineStore.getEngine(engineId) ?: return@AsyncFunction
75
134
  UiThreadUtil.runOnUiThread {
@@ -0,0 +1,118 @@
1
+ package com.papyrus.engine;
2
+
3
+ import android.os.SystemClock;
4
+ import android.util.Log;
5
+
6
+ import com.facebook.react.bridge.ReadableMap;
7
+
8
+ import java.util.HashMap;
9
+ import java.util.Map;
10
+ import java.util.concurrent.atomic.AtomicBoolean;
11
+
12
+ final class PapyrusNativeRenderTelemetry {
13
+ private static final String TAG = "PapyrusNativePerf";
14
+ private final boolean enabled;
15
+ private final Map<String, Object> context;
16
+ private final AtomicBoolean drawEmitted = new AtomicBoolean(false);
17
+ private final AtomicBoolean drawEnded = new AtomicBoolean(false);
18
+
19
+ private PapyrusNativeRenderTelemetry(boolean enabled, Map<String, Object> context) {
20
+ this.enabled = enabled;
21
+ this.context = context;
22
+ }
23
+
24
+ static PapyrusNativeRenderTelemetry from(
25
+ ReadableMap input,
26
+ String renderRequestId,
27
+ String surfaceId,
28
+ int pageIndex,
29
+ int target,
30
+ int generation) {
31
+ Map<String, Object> context = new HashMap<>();
32
+ context.put("renderRequestId", renderRequestId);
33
+ context.put("surfaceId", surfaceId);
34
+ context.put("pageIndex", pageIndex);
35
+ context.put("target", target);
36
+ context.put("generation", generation);
37
+ boolean enabled = false;
38
+ if (input != null) {
39
+ enabled = input.hasKey("enabled") && !input.isNull("enabled") && input.getBoolean("enabled");
40
+ copyString(input, context, "runId");
41
+ copyString(input, context, "sampleId");
42
+ copyString(input, context, "documentLoadId");
43
+ copyString(input, context, "fixture");
44
+ if (input.hasKey("generation") && !input.isNull("generation")) {
45
+ context.put("generation", input.getInt("generation"));
46
+ }
47
+ if (input.hasKey("pageIndex") && !input.isNull("pageIndex")) {
48
+ context.put("pageIndex", input.getInt("pageIndex"));
49
+ }
50
+ if (input.hasKey("surfaceId") && !input.isNull("surfaceId")) {
51
+ context.put("surfaceId", input.getString("surfaceId"));
52
+ }
53
+ }
54
+ return new PapyrusNativeRenderTelemetry(enabled, context);
55
+ }
56
+
57
+ private static void copyString(ReadableMap input, Map<String, Object> output, String key) {
58
+ if (input.hasKey(key) && !input.isNull(key)) {
59
+ output.put(key, input.getString(key));
60
+ }
61
+ }
62
+
63
+ boolean isEnabled() {
64
+ return enabled;
65
+ }
66
+
67
+ void emit(String name) {
68
+ if (!enabled) return;
69
+ Log.i(TAG, "[Papyrus Native Perf] " + buildEventJson(name, SystemClock.elapsedRealtimeNanos(), context));
70
+ }
71
+
72
+ void traceBegin(String section) {
73
+ if (enabled) android.os.Trace.beginSection(section);
74
+ }
75
+
76
+ void traceEnd() {
77
+ if (enabled) android.os.Trace.endSection();
78
+ }
79
+
80
+ void emitDrawOnce() {
81
+ if (drawEmitted.compareAndSet(false, true)) {
82
+ emit("native.draw.start");
83
+ }
84
+ }
85
+
86
+ void emitDrawEnd() {
87
+ if (enabled && drawEmitted.get() && drawEnded.compareAndSet(false, true)) {
88
+ emit("native.draw.end");
89
+ }
90
+ }
91
+
92
+ void emitCachePut() {
93
+ emit("native.render.cache.put");
94
+ }
95
+
96
+ void emitCacheEvict() {
97
+ emit("native.render.cache.evict");
98
+ }
99
+
100
+ static String buildEventJson(String name, long timestampNs, Map<String, Object> context) {
101
+ StringBuilder json = new StringBuilder("{\"name\":");
102
+ json.append(jsonValue(name));
103
+ json.append(",\"timestampNs\":").append(timestampNs);
104
+ for (Map.Entry<String, Object> entry : context.entrySet()) {
105
+ if (entry.getValue() != null) {
106
+ json.append(',').append(jsonValue(entry.getKey())).append(':').append(jsonValue(entry.getValue()));
107
+ }
108
+ }
109
+ return json.append('}').toString();
110
+ }
111
+
112
+ private static String jsonValue(Object value) {
113
+ if (value instanceof Number || value instanceof Boolean) return String.valueOf(value);
114
+ String text = String.valueOf(value);
115
+ return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"")
116
+ .replace("\n", "\\n").replace("\r", "\\r") + "\"";
117
+ }
118
+ }