diff --git a/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt b/android/src/main/java/com/reactnativecommunity/imageeditor/ImageEditorModuleImpl.kt index 53a92f3..b3fd5da 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,28 +57,58 @@ 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. 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) { @@ -153,6 +182,14 @@ 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() @@ -179,15 +216,32 @@ 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) } - promise.resolve(getResultMap(tempFile, cropped, mimeType, includeBase64)) - } catch (e: Exception) { - promise.reject(e) + // 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: 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) } } } } @@ -422,6 +476,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 =