From 5043bf975976103485d27f747744373fd79f1380 Mon Sep 17 00:00:00 2001 From: D N <4661784+retyui@users.noreply.github.com> Date: Wed, 2 Dec 2026 15:29:45 +0100 Subject: [PATCH 1/3] fix(android): actually clean the crop cache on shutdown, and settle crops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `invalidate()` cancelled `moduleCoroutineScope` and then called `cleanTask()`, which launched on that same scope — the job was queued on a job that had just been cancelled, so the cache cleanup the doc comment promised never ran, and cropped files only ever got removed at the next launch. Move the cleanup out of the coroutine and run it before cancelling, and track the promises of crops that have not finished: `invalidate()` now rejects them instead of cancelling the scope under them, which used to leave those promises unsettled forever (a caller awaiting `cropImage` would hang for the rest of the app's life). Requests that arrive after invalidation are rejected outright, since the scope they would run on is gone. --- .../imageeditor/ImageEditorModuleImpl.kt | 69 +++++++++++++++---- 1 file changed, 55 insertions(+), 14 deletions(-) diff --git a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt index 53a92f3..f24050a 100644 --- a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt +++ b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt @@ -46,7 +46,6 @@ import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel -import kotlinx.coroutines.isActive import kotlinx.coroutines.launch object MimeType { @@ -58,27 +57,55 @@ object MimeType { class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { private val moduleCoroutineScope = CoroutineScope(Dispatchers.Default) + /** + * Crops whose promise has not settled yet, so invalidation can reject them. [isInvalidated] + * and the set are only touched under [pendingLock], which is never held while a promise is + * settled. + */ + private val pendingPromises = mutableSetOf() + + private val pendingLock = Any() + + private var isInvalidated = false + init { - cleanTask() + moduleCoroutineScope.launch { cleanTask() } } fun invalidate() { - if (moduleCoroutineScope.isActive) { - moduleCoroutineScope.cancel() - } + val pending = + synchronized(pendingLock) { + isInvalidated = true + pendingPromises.toList().also { pendingPromises.clear() } + } + // Clean up before cancelling: `cleanTask` used to run on the scope cancelled here, so it + // was dispatched onto a dead job and never happened at all. cleanTask() + moduleCoroutineScope.cancel() + // Settle the crops that scope will never get to finish, otherwise their promises would + // hang forever. + for (promise in pending) { + promise.reject(JSApplicationIllegalArgumentException(INVALIDATED_MESSAGE)) + } } /** - * Asynchronous task that cleans up cache dirs (internal and, if available, external) of cropped - * image files. This is run when the module is invalidated (i.e. app is shutting down) and when - * the module is instantiated, to handle the case where the app crashed. + * Cleans up the cache dirs (internal and, if available, external) of cropped image files. This + * is run when the module is invalidated (i.e. app is shutting down) and when the module is + * instantiated, to handle the case where the app crashed. Not dispatched through + * [moduleCoroutineScope], since it has to outlive that scope being cancelled. */ private fun cleanTask() { - moduleCoroutineScope.launch { - cleanDirectory(reactContext.cacheDir) - val externalCacheDir = reactContext.externalCacheDir - externalCacheDir?.let { cleanDirectory(it) } + cleanDirectory(reactContext.cacheDir) + val externalCacheDir = reactContext.externalCacheDir + externalCacheDir?.let { cleanDirectory(it) } + } + + /** Settle [promise] unless invalidation already claimed it. */ + private fun settleOnce(promise: Promise, settle: (Promise) -> Unit) { + val claimed = synchronized(pendingLock) { pendingPromises.remove(promise) } + if (claimed) { + settle(promise) } } @@ -153,6 +180,16 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { Pair(targetSize.getDouble("width").toInt(), targetSize.getDouble("height").toInt()) } else Pair(0, 0) + val accepted = + synchronized(pendingLock) { + if (isInvalidated) false else pendingPromises.add(promise) + } + if (!accepted) { + // `moduleCoroutineScope` is cancelled, so the job below would never start and the + // promise would hang. + promise.reject(JSApplicationIllegalArgumentException(INVALIDATED_MESSAGE)) + return + } moduleCoroutineScope.launch { try { val outOptions = BitmapFactory.Options() @@ -185,9 +222,11 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { if (mimeType == MimeType.JPEG) { copyExif(reactContext, Uri.parse(uri), tempFile) } - promise.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) + settleOnce(promise) { + it.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) + } } catch (e: Exception) { - promise.reject(e) + settleOnce(promise) { it.reject(e) } } } } @@ -422,6 +461,8 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { ContentResolver.SCHEME_ANDROID_RESOURCE ) private const val TEMP_FILE_PREFIX = "ReactNative_cropped_image_" + private const val INVALIDATED_MESSAGE = + "Cannot crop an image after the image editor module was invalidated" @SuppressLint("InlinedApi") private val EXIF_ATTRIBUTES = From dfddbbed0e964056be4f9c7cac17dba2ef18a9a5 Mon Sep 17 00:00:00 2001 From: D N <4661784+retyui@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:34:47 +0100 Subject: [PATCH 2/3] style(android): apply spotless formatting --- .../imageeditor/ImageEditorModuleImpl.kt | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt index f24050a..012e991 100644 --- a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt +++ b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt @@ -58,9 +58,8 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { private val moduleCoroutineScope = CoroutineScope(Dispatchers.Default) /** - * Crops whose promise has not settled yet, so invalidation can reject them. [isInvalidated] - * and the set are only touched under [pendingLock], which is never held while a promise is - * settled. + * Crops whose promise has not settled yet, so invalidation can reject them. [isInvalidated] and + * the set are only touched under [pendingLock], which is never held while a promise is settled. */ private val pendingPromises = mutableSetOf() @@ -181,9 +180,7 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { } else Pair(0, 0) val accepted = - synchronized(pendingLock) { - if (isInvalidated) false else pendingPromises.add(promise) - } + synchronized(pendingLock) { if (isInvalidated) false else pendingPromises.add(promise) } if (!accepted) { // `moduleCoroutineScope` is cancelled, so the job below would never start and the // promise would hang. From ede52a6e1a40a952a9a49af7050b217118e4f095 Mon Sep 17 00:00:00 2001 From: D N <4661784+retyui@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:50:46 +0100 Subject: [PATCH 3/3] fix(android): settle crops on Errors and don't leave files behind after invalidate A crop job never suspends, so cancelling the scope in `invalidate()` doesn't stop it: it went on to write its file after the cache cleanup had run, and that file stayed until the next launch. Skip writing once invalidated, and delete the file if invalidation claimed the promise while it was written. Build the result map before claiming the promise, so a failure there (e.g. reading the file back for `includeBase64`) is still rejected instead of leaving the promise unsettled. Catch `Throwable` rather than `Exception`: an `Error` (OutOfMemoryError, or the `throw Error` on a null decoder) escaped `settleOnce` and left the promise pending. This overlaps #224, which makes the same change. --- .../imageeditor/ImageEditorModuleImpl.kt | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt index 012e991..b3fd5da 100644 --- a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt +++ b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt @@ -100,12 +100,15 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { externalCacheDir?.let { cleanDirectory(it) } } - /** Settle [promise] unless invalidation already claimed it. */ - private fun settleOnce(promise: Promise, settle: (Promise) -> Unit) { + /** + * Settle [promise] unless invalidation already claimed it. Returns whether [settle] was called. + */ + private fun settleOnce(promise: Promise, settle: (Promise) -> Unit): Boolean { val claimed = synchronized(pendingLock) { pendingPromises.remove(promise) } if (claimed) { settle(promise) } + return claimed } private fun cleanDirectory(directory: File) { @@ -213,16 +216,31 @@ class ImageEditorModuleImpl(private val reactContext: ReactApplicationContext) { if (cropped == null) { throw IOException("Cannot decode bitmap: $uri") } + // The job doesn't suspend, so cancelling the scope doesn't stop it. Once + // invalidated, the promise is already rejected and the cache cleaned: don't write + // a new file. + if (synchronized(pendingLock) { isInvalidated }) { + return@launch + } val mimeType = getMimeType(outOptions, format) val tempFile = createTempFile(reactContext, mimeType) writeCompressedBitmapToFile(cropped, mimeType, tempFile, quality) if (mimeType == MimeType.JPEG) { copyExif(reactContext, Uri.parse(uri), tempFile) } - settleOnce(promise) { - it.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) + // Built before claiming the promise: if this throws, the catch below must still + // be able to reject it. + val result = getResultMap(tempFile, cropped, mimeType, includeBase64) + val resolved = settleOnce(promise) { it.resolve(result) } + if (!resolved) { + // Invalidated while writing: the cleanup already ran, so nothing else would + // remove this file until the next launch. + tempFile.delete() } - } catch (e: Exception) { + } catch (e: Throwable) { + // Errors (e.g. OutOfMemoryError while decoding) must be turned into a rejection + // too: they don't extend Exception and would otherwise escape the coroutine and + // crash the app, leaving the promise unsettled. settleOnce(promise) { it.reject(e) } } }