From 1a62ac92756182a55e9492baf7d23e8eca2bccb8 Mon Sep 17 00:00:00 2001 From: Aziz Becha Date: Sun, 11 Oct 2026 16:57:10 +0100 Subject: [PATCH] perf: keep document work off the UI thread and cap the iOS brush map getStrokes serialized every point to JSON on the UI thread on both platforms, and setStrokes built a stroke per point there too. Both now run on a worker thread and answer back on the UI thread, the way the image export already did. The Android export executor is shared, so the document commands queue behind it instead of building a second thread. The iOS brush map grew for the whole session and was never pruned, because clear and undo leave entries that undo itself still needs. Keeping the most recent 1000 bounds the memory while leaving undo intact. --- .../java/me/sectiontn/inkpad/InkpadView.kt | 54 +++++++++++----- ios/INKPadView.mm | 63 +++++++++++++++---- 2 files changed, 90 insertions(+), 27 deletions(-) diff --git a/android/src/main/java/me/sectiontn/inkpad/InkpadView.kt b/android/src/main/java/me/sectiontn/inkpad/InkpadView.kt index 2d1ce01..8bc63f8 100644 --- a/android/src/main/java/me/sectiontn/inkpad/InkpadView.kt +++ b/android/src/main/java/me/sectiontn/inkpad/InkpadView.kt @@ -201,21 +201,45 @@ class InkpadView(private val reactContext: ThemedReactContext) : FrameLayout(rea } internal fun getStrokes(requestId: Int) { - val doc = Doc(width / density, height / density, strokes.map(InkConverter::fromInk)) - emitResult(requestId, DocumentJson.write(doc)) + val snapshot = strokes.toList() + val canvasWidth = width / density + val canvasHeight = height / density + // A long drawing serializes to a large JSON string, so it belongs off the UI thread like the export. + WORKER.execute { + val result = runCatching { + DocumentJson.write(Doc(canvasWidth, canvasHeight, snapshot.map(InkConverter::fromInk))) + } + post { + result.fold( + onSuccess = { emitResult(requestId, it) }, + onFailure = { error -> + emitError(requestId, ErrorCodes.NATIVE, error.message ?: "could not read the strokes") + }, + ) + } + } } internal fun setStrokes(requestId: Int, json: String?) { - try { - val metrics = resources.displayMetrics - val unitLengthCm = InkConverter.strokeUnitLengthCm(density, metrics.xdpi, metrics.ydpi) - val next = DocumentJson.parse(json ?: "").strokes.map { InkConverter.toInk(it, unitLengthCm) } - replaceAll(next) - emitResult(requestId, "") - } catch (e: InkpadException) { - emitError(requestId, e.code, e.message ?: "") - } catch (e: IllegalArgumentException) { - emitError(requestId, ErrorCodes.NATIVE, e.message ?: "Ink rejected the strokes") + val metrics = resources.displayMetrics + val unitLengthCm = InkConverter.strokeUnitLengthCm(density, metrics.xdpi, metrics.ydpi) + // Loading a saved drawing builds an ink stroke per point, which is as heavy as reading one back. + WORKER.execute { + val result = runCatching { + DocumentJson.parse(json ?: "").strokes.map { InkConverter.toInk(it, unitLengthCm) } + } + post { + result.fold( + onSuccess = { next -> + replaceAll(next) + emitResult(requestId, "") + }, + onFailure = { error -> + val code = if (error is InkpadException) error.code else ErrorCodes.NATIVE + emitError(requestId, code, error.message ?: "Ink rejected the strokes") + }, + ) + } } } @@ -225,7 +249,7 @@ class InkpadView(private val reactContext: ThemedReactContext) : FrameLayout(rea val canvasWidth = width / density val canvasHeight = height / density val color = canvasColor - EXPORTER.execute { + WORKER.execute { val result = runCatching { ImageExporter.export(reactContext, snapshot, canvasWidth, canvasHeight, color, options) } @@ -287,6 +311,8 @@ class InkpadView(private val reactContext: ThemedReactContext) : FrameLayout(rea companion object { private const val ERASER_RADIUS = 10f - private val EXPORTER = Executors.newSingleThreadExecutor() + + // Commands that read or build the whole document share one thread, so they never touch ink at once. + private val WORKER = Executors.newSingleThreadExecutor() } } diff --git a/ios/INKPadView.mm b/ios/INKPadView.mm index 93b6192..9f80529 100644 --- a/ios/INKPadView.mm +++ b/ios/INKPadView.mm @@ -17,6 +17,9 @@ using namespace facebook::react; +// Brushes outlive the strokes they belong to, because undo can bring those strokes back. +static const NSUInteger INKBrushLimit = 1000; + @interface INKPadView () @end @@ -39,6 +42,7 @@ @implementation INKPadView { CGFloat _brushSize; BOOL _erasing; NSMutableDictionary *_brushes; + NSMutableArray *_brushOrder; } + (ComponentDescriptorProvider)componentDescriptorProvider @@ -62,6 +66,7 @@ - (instancetype)initWithFrame:(CGRect)frame _brushColor = UIColor.blackColor; _brushSize = 3; _brushes = [NSMutableDictionary new]; + _brushOrder = [NSMutableArray new]; _canvas = [[INKCanvasView alloc] initWithFrame:frame]; _canvas.delegate = self; @@ -181,22 +186,40 @@ - (void)replaceDrawing:(PKDrawing *)drawing - (void)getStrokes:(NSInteger)requestId { - NSString *json = [INKStrokeCodec encodeDrawing:_canvas.drawing size:self.bounds.size brushes:_brushes]; - [self emitResult:requestId ok:YES payload:json errorCode:@"" message:@""]; + PKDrawing *drawing = _canvas.drawing; + NSDictionary *brushes = [_brushes copy]; + CGSize size = self.bounds.size; + __weak INKPadView *weakSelf = self; + // A long drawing serializes to a large JSON string, and exporting already renders off the main thread. + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSString *json = [INKStrokeCodec encodeDrawing:drawing size:size brushes:brushes]; + dispatch_async(dispatch_get_main_queue(), ^{ + [weakSelf emitResult:requestId ok:YES payload:json errorCode:@"" message:@""]; + }); + }); } - (void)setStrokes:(NSInteger)requestId json:(NSString *)json { - NSString *errorCode = nil; - NSString *message = nil; - INKDecodedDrawing *decoded = [INKStrokeCodec decode:json errorCode:&errorCode message:&message]; - if (decoded == nil) { - [self emitResult:requestId ok:NO payload:@"" errorCode:errorCode message:message]; - return; - } - [_brushes addEntriesFromDictionary:decoded.brushes]; - [self replaceDrawing:decoded.drawing]; - [self emitResult:requestId ok:YES payload:@"" errorCode:@"" message:@""]; + __weak INKPadView *weakSelf = self; + // Loading a saved drawing builds a stroke path per point, which is as heavy as encoding one. + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSString *errorCode = nil; + NSString *message = nil; + INKDecodedDrawing *decoded = [INKStrokeCodec decode:json errorCode:&errorCode message:&message]; + dispatch_async(dispatch_get_main_queue(), ^{ + INKPadView *view = weakSelf; + if (decoded == nil) { + [view emitResult:requestId ok:NO payload:@"" errorCode:errorCode message:message]; + return; + } + [decoded.brushes enumerateKeysAndObjectsUsingBlock:^(NSDate *created, INKBrushInfo *info, BOOL *stop) { + [view rememberBrush:info forDate:created]; + }]; + [view replaceDrawing:decoded.drawing]; + [view emitResult:requestId ok:YES payload:@"" errorCode:@"" message:@""]; + }); + }); } - (void)exportImage:(NSInteger)requestId optionsJson:(NSString *)optionsJson @@ -276,7 +299,21 @@ - (void)rememberNewStrokes info.color = INKHexFromColor(_brushColor); info.size = _brushSize; info.input = INKInputName(_canvas.lastTouchType); - _brushes[created] = info; + [self rememberBrush:info forDate:created]; + } +} + +// Undo can bring back any stroke that is still in the drawing, so the brushes stay in a bounded window +// instead of growing for the whole session. +- (void)rememberBrush:(INKBrushInfo *)info forDate:(NSDate *)date +{ + if (![_brushOrder.lastObject isEqualToDate:date]) { + [_brushOrder addObject:date]; + } + _brushes[date] = info; + while (_brushOrder.count > INKBrushLimit) { + [_brushes removeObjectForKey:_brushOrder.firstObject]; + [_brushOrder removeObjectAtIndex:0]; } }