@papyrus-sdk/engine-native 0.2.18 → 0.2.20

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,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;
@@ -35,6 +35,7 @@ import java.util.concurrent.Executors;
35
35
  public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
36
36
  private final ReactApplicationContext reactContext;
37
37
  private final ExecutorService executor = Executors.newSingleThreadExecutor();
38
+ private long renderRequestCounter = 0;
38
39
 
39
40
  public PapyrusNativeEngineModule(ReactApplicationContext reactContext) {
40
41
  super(reactContext);
@@ -72,6 +73,10 @@ public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
72
73
  ContentResolver resolver = reactContext.getContentResolver();
73
74
  inputStream = resolver.openInputStream(uri);
74
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");
75
80
  } else {
76
81
  throw new IOException("Unsupported local file URI");
77
82
  }
@@ -144,24 +149,79 @@ public class PapyrusNativeEngineModule extends ReactContextBaseJavaModule {
144
149
  return state.pdfium.getPageCount(state.document);
145
150
  }
146
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
+
147
163
  @ReactMethod
148
- 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) {
149
165
  final PapyrusEngineStore.EngineState state = PapyrusEngineStore.getEngine(engineId);
150
- if (state == null) return;
166
+ if (state == null) {
167
+ promise.reject("papyrus_no_engine", "Engine not found");
168
+ return;
169
+ }
151
170
  UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
152
- if (uiManager == null) return;
171
+ if (uiManager == null) {
172
+ promise.reject("papyrus_render_error", "UI manager unavailable");
173
+ return;
174
+ }
153
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");
154
194
  uiManager.addUIBlock(new UIBlock() {
155
195
  @Override
156
196
  public void execute(com.facebook.react.uimanager.NativeViewHierarchyManager nativeViewHierarchyManager) {
157
- View view = nativeViewHierarchyManager.resolveView(target);
158
- if (view instanceof PapyrusPageView) {
159
- ((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();
160
210
  }
161
211
  }
162
212
  });
163
213
  }
164
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
+
165
225
  @ReactMethod
166
226
  public void renderTextLayer(String engineId, int pageIndex, int target, float scale, float zoom, int rotation) {
167
227
  }
@@ -51,6 +51,11 @@ class PapyrusNativeEngineModule : Module() {
51
51
  context.contentResolver.openInputStream(uri)
52
52
  ?: throw IOException("Unable to read content URI")
53
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
+ }
54
59
  else -> throw IOException("Unsupported local file URI")
55
60
  }
56
61
 
@@ -115,6 +120,15 @@ class PapyrusNativeEngineModule : Module() {
115
120
  state.pdfium.getPageCount(state.document)
116
121
  }
117
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
+
118
132
  AsyncFunction("renderPage") { engineId: String, pageIndex: Int, target: Int, scale: Double, zoom: Double, rotation: Int ->
119
133
  val state = PapyrusEngineStore.getEngine(engineId) ?: return@AsyncFunction
120
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
+ }