Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
Add image editor deps and port ImageToolbox cropper, gesture, free-corners crop
Chethan6162a3bd33ea55a
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 9a1f99c..a1853af 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -160,4 +160,11 @@ dependencies {implementation(libs.coil.compose)implementation(libs.acccompanist.permissions)implementation("androidx.documentfile:documentfile:1.0.1")++ // Image editor: GPUImage (T8RIN fork, ~0.2 MB) for GL adjustments/filters, EXIF read/strip,+ // and ML Kit subject segmentation for auto background removal (API 24+, gated at runtime;+ // isolated behind BackgroundRemover so a FOSS flavor can swap it out).+ implementation(libs.toolbox.gpuimage)+ implementation(libs.androidx.exifinterface)+ implementation(libs.mlkit.subject.segmentation)}diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 029aede..9a4d180 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -13,6 +13,9 @@<!-- Legacy write access for pre-scoped-storage devices only. --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" /><uses-feature android:name="android.hardware.camera" android:required="false" />+ <!-- ML Kit subject segmentation (image editor → auto background removal) declares minSdk 24.+ The app stays on 23; BackgroundRemover gates the call at runtime (API < 24 → unavailable). -->+ <uses-sdk tools:overrideLibrary="com.google.mlkit.vision.segmentation.subject" /><applicationandroid:allowBackup="true"@@ -145,6 +148,13 @@android:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" /></provider>++ <!-- Ask Google Play services to fetch the subject-segmentation model ahead of time so the+ image editor's "Remove background" works on first use. The download is done by Play+ services itself; the app declares no network permission. -->+ <meta-data+ android:name="com.google.mlkit.vision.DEPENDENCIES"+ android:value="subject_segment" /></application></manifest>diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/CropModifier.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/CropModifier.ktnew file mode 100644index 0000000..847feaa--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/CropModifier.kt@@ -0,0 +1,337 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateCentroid+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.composed+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChanged+import androidx.compose.ui.platform.debugInspectorInfo+import androidx.compose.ui.util.fastAny+import androidx.compose.ui.util.fastForEach+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropData+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.CropState+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.cropData+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.ZoomLevel+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.getNextZoomLevel+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.update+import com.chethan616.clearpdf.imageeditor.thirdparty.gesture.detectMotionEventsAsList+import com.chethan616.clearpdf.imageeditor.thirdparty.gesture.detectTransformGestures+import kotlinx.coroutines.launch++/**+ * Modifier that zooms in or out of Composable set to. This zoom modifier has option+ * to move back to bounds with an animation or option to have fling gesture when user removes+ * from screen while velocity is higher than threshold to have smooth touch effect.+ *+ * @param keys are used for [Modifier.pointerInput] to restart closure when any keys assigned+ * change+ * empty space on sides or edges of parent.+ * @param cropState State of the zoom that contains option to set initial, min, max zoom,+ * enabling rotation, pan or zoom and contains current [CropData]+ * event propagations. Also contains [Rect] of visible area based on pan, zoom and rotation+ * @param zoomOnDoubleTap lambda that returns current [ZoomLevel] and based on current level+ * enables developer to define zoom on double tap gesture+ * @param onGestureStart callback to to notify gesture has started and return current+ * [CropData] of this modifier+ * @param onGesture callback to notify about ongoing gesture and return current+ * [CropData] of this modifier+ * @param onGestureEnd callback to notify that gesture finished return current+ * [CropData] of this modifier+ */+fun Modifier.crop(+ vararg keys: Any?,+ cropState: CropState,+ enableOneFingerZoom: Boolean = true,+ zoomOnDoubleTap: (ZoomLevel) -> Float = cropState.DefaultOnDoubleTap,+ onDown: ((CropData) -> Unit)? = null,+ onMove: ((CropData) -> Unit)? = null,+ onUp: ((CropData) -> Unit)? = null,+ onGestureStart: ((CropData) -> Unit)? = null,+ onGesture: ((CropData) -> Unit)? = null,+ onGestureEnd: ((CropData) -> Unit)? = null+) = composed(++ factory = {++ LaunchedEffect(key1 = cropState) {+ cropState.init()+ }++ val coroutineScope = rememberCoroutineScope()++ // Current Zoom level+ var zoomLevel by remember { mutableStateOf(ZoomLevel.Min) }++ val transformModifier = Modifier.pointerInput(*keys) {+ detectTransformGestures(+ consume = false,+ onGestureStart = {+ onGestureStart?.invoke(cropState.cropData)+ },+ onGestureEnd = {+ coroutineScope.launch {+ cropState.onGestureEnd {+ onGestureEnd?.invoke(cropState.cropData)+ }+ }+ },+ onGesture = { centroid, pan, zoom, rotate, mainPointer, pointerList ->++ coroutineScope.launch {+ cropState.onGesture(+ centroid = centroid,+ panChange = pan,+ zoomChange = zoom,+ rotationChange = rotate,+ mainPointer = mainPointer,+ changes = pointerList+ )+ }+ onGesture?.invoke(cropState.cropData)+ mainPointer.consume()+ }+ )+ }++ val tapModifier = Modifier.pointerInput(*keys, enableOneFingerZoom) {+ fun onDoubleTap(offset: Offset) {+ coroutineScope.launch {+ zoomLevel = getNextZoomLevel(zoomLevel)+ val newZoom = zoomOnDoubleTap(zoomLevel)+ cropState.onDoubleTap(+ offset = offset,+ zoom = newZoom+ ) {+ onGestureEnd?.invoke(cropState.cropData)+ }+ }+ }++ if (enableOneFingerZoom) {+ detectOneFingerZoomGestures(+ onDoubleTap = ::onDoubleTap,+ onGestureStart = {+ onGestureStart?.invoke(cropState.cropData)+ },+ onGestureEnd = {+ coroutineScope.launch {+ cropState.onGestureEnd {+ onGestureEnd?.invoke(cropState.cropData)+ }+ }+ },+ onZoom = { centroid, zoom, mainPointer, pointerList ->+ coroutineScope.launch {+ cropState.onGesture(+ centroid = centroid,+ panChange = Offset.Zero,+ zoomChange = zoom,+ rotationChange = 0f,+ mainPointer = mainPointer,+ changes = pointerList+ )+ }+ onGesture?.invoke(cropState.cropData)+ }+ )+ } else {+ detectTapGestures(onDoubleTap = ::onDoubleTap)+ }+ }++ val touchModifier = Modifier.pointerInput(*keys) {+ detectMotionEventsAsList(+ onDown = {+ coroutineScope.launch {+ cropState.onDown(it)+ onDown?.invoke(cropState.cropData)+ }+ },+ onMove = {+ coroutineScope.launch {+ cropState.onMove(it)+ onMove?.invoke(cropState.cropData)+ }+ },+ onUp = {+ coroutineScope.launch {+ cropState.onUp(it)+ onUp?.invoke(cropState.cropData)+ }+ }+ )+ }++ val graphicsModifier = Modifier.graphicsLayer {+ this.update(cropState)+ }++ this.then(+ Modifier+ .clipToBounds()+ .then(tapModifier)+ .then(transformModifier)+ .then(touchModifier)+ .then(graphicsModifier)+ )+ },+ inspectorInfo = debugInspectorInfo {+ name = "crop"+ // add name and value of each argument+ properties["keys"] = keys+ properties["onDown"] = onGestureStart+ properties["onMove"] = onGesture+ properties["onUp"] = onGestureEnd+ properties["enableOneFingerZoom"] = enableOneFingerZoom+ }+)++internal val CropState.DefaultOnDoubleTap: (ZoomLevel) -> Float+ get() = { zoomLevel: ZoomLevel ->+ when (zoomLevel) {+ ZoomLevel.Min -> 1f+ ZoomLevel.Mid -> 3f.coerceIn(zoomMin, zoomMax)+ ZoomLevel.Max -> 5f.coerceAtLeast(zoomMax)+ }+ }++private suspend fun PointerInputScope.detectOneFingerZoomGestures(+ onDoubleTap: (Offset) -> Unit,+ onGestureStart: () -> Unit,+ onZoom: (+ centroid: Offset,+ zoom: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ ) -> Unit,+ onGestureEnd: () -> Unit+) = awaitEachGesture {+ val firstDown = awaitFirstDown(requireUnconsumed = false)+ var firstUp = firstDown+ var hasMoved = false+ var isMultiTouch = false+ var isCanceled = false++ do {+ val event = awaitPointerEvent()+ if (event.changes.fastAny { it.isConsumed }) {+ isCanceled = true+ break+ }+ if (event.changes.fastAny { it.positionChanged() }) {+ hasMoved = true+ }+ if (event.changes.size > 1) {+ isMultiTouch = true+ }+ firstUp = event.changes.first()+ } while (event.changes.fastAny { it.pressed })++ val isTap = !hasMoved &&+ !isMultiTouch &&+ !isCanceled &&+ firstUp.uptimeMillis - firstDown.uptimeMillis <= viewConfiguration.longPressTimeoutMillis++ if (isTap) {+ val secondDown = awaitSecondDown(firstUp)+ if (secondDown != null) {+ var secondUp: PointerInputChange = secondDown+ var isZooming = false+ var isSecondMultiTouch = false+ var isSecondCanceled = false++ do {+ val event = awaitPointerEvent(PointerEventPass.Initial)+ if (event.changes.fastAny { it.isConsumed }) {+ isSecondCanceled = true+ break+ }++ if (event.changes.size > 1) {+ isSecondMultiTouch = true+ }++ val panChange = event.calculatePan()+ if (panChange != Offset.Zero) {+ if (!isZooming) {+ onGestureStart()+ }+ isZooming = true+ val zoomChange = 1f + panChange.y * 0.004f+ if (zoomChange != 1f) {+ onZoom(+ event.calculateCentroid(useCurrent = true),+ zoomChange,+ event.changes.first(),+ event.changes+ )+ event.changes.fastForEach {+ if (it.positionChanged()) {+ it.consume()+ }+ }+ }+ }+ secondUp = event.changes.first()+ } while (event.changes.fastAny { it.pressed })++ if (isZooming && !isSecondMultiTouch && !isSecondCanceled) {+ onGestureEnd()+ } else if (!isSecondMultiTouch &&+ !isSecondCanceled &&+ secondUp.uptimeMillis - secondDown.uptimeMillis <=+ viewConfiguration.longPressTimeoutMillis+ ) {+ onDoubleTap(secondUp.position)+ }+ }+ }+}++private suspend fun AwaitPointerEventScope.awaitSecondDown(+ firstUp: PointerInputChange+): PointerInputChange? =+ withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) {+ val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis+ var change: PointerInputChange+ do {+ change = awaitFirstDown()+ } while (change.uptimeMillis < minUptime)+ change+ }diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropper.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropper.ktnew file mode 100644index 0000000..1121435--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropper.kt@@ -0,0 +1,534 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper++import android.net.Uri+import androidx.compose.animation.core.Animatable+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.draw.DrawingOverlay+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.draw.ImageDrawCanvas+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.image.ImageWithConstraints+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.image.getScaledImageBitmap+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropOutline+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropDefaults+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropProperties+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropStyle+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropType+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.CropState+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.DynamicCropState+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.cropSnapshot+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.rememberCropState+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.restoreCropSnapshot+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++@Composable+fun ImageCropper(+ modifier: Modifier = Modifier,+ imageBitmap: ImageBitmap,+ sourceImageUri: Uri? = null,+ sourceImageSize: IntSize = IntSize(imageBitmap.width, imageBitmap.height),+ contentDescription: String? = null,+ cropStyle: CropStyle = CropDefaults.style(),+ cropProperties: CropProperties,+ state: ImageCropperState = rememberImageCropperState(),+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+ crop: Boolean = false,+ enableOneFingerZoom: Boolean = true,+ isOverlayDraggable: Boolean = true,+ onCropStart: () -> Unit,+ onZoomChange: (Float) -> Unit,+ onCropSuccess: (Rect) -> Unit,+ onTransformationCommitted: () -> Unit = {},+ backgroundModifier: Modifier = Modifier+) {+ val minCropDimension = with(LocalDensity.current) {+ MinCropDimension.roundToPx()+ }+ val resolvedCropProperties = remember(cropProperties, minCropDimension) {+ if (cropProperties.minDimension == null) {+ cropProperties.copy(+ minDimension = IntSize(minCropDimension, minCropDimension)+ )+ } else {+ cropProperties+ }+ }++ ImageWithConstraints(+ modifier = modifier.clipToBounds(),+ contentScale = resolvedCropProperties.contentScale,+ contentDescription = contentDescription,+ filterQuality = filterQuality,+ imageBitmap = imageBitmap,+ drawImage = false+ ) {++ // No crop operation is applied by ScalableImage so rect points to bounds of original+ // bitmap+ val scaledImageBitmap = getScaledImageBitmap(+ imageWidth = imageWidth,+ imageHeight = imageHeight,+ rect = rect,+ bitmap = imageBitmap,+ contentScale = resolvedCropProperties.contentScale,+ )++ val imageKey = sourceImageUri ?: imageBitmap++ // Container Dimensions+ val measuredContainerSize = IntSize(constraints.maxWidth, constraints.maxHeight)+ val containerSize = state.preferredContainerSize(imageKey, measuredContainerSize)+ val containerWidthPx = containerSize.width+ val containerHeightPx = containerSize.height++ val containerWidth: Dp+ val containerHeight: Dp++ // Bitmap Dimensions+ val bitmapWidth = scaledImageBitmap.width+ val bitmapHeight = scaledImageBitmap.height++ // Dimensions of Composable that displays Bitmap+ val imageWidthPx: Int+ val imageHeightPx: Int++ with(LocalDensity.current) {+ imageWidthPx = imageWidth.roundToPx()+ imageHeightPx = imageHeight.roundToPx()+ containerWidth = containerWidthPx.toDp()+ containerHeight = containerHeightPx.toDp()+ }++ val cropType = resolvedCropProperties.cropType+ val contentScale = resolvedCropProperties.contentScale+ val fixedAspectRatio = resolvedCropProperties.fixedAspectRatio+ val cropOutline = resolvedCropProperties.cropOutlineProperty.cropOutline++ // these keys are for resetting cropper when image width/height, contentScale or+ // overlay aspect ratio changes+ val resetKeys =+ getResetKeys(+ scaledImageBitmap,+ imageWidthPx,+ imageHeightPx,+ contentScale,+ cropType,+ fixedAspectRatio,+ state.resetVersion+ )++ val cropState = rememberCropState(+ imageSize = IntSize(bitmapWidth, bitmapHeight),+ containerSize = IntSize(containerWidthPx, containerHeightPx),+ drawAreaSize = IntSize(imageWidthPx, imageHeightPx),+ cropProperties = resolvedCropProperties,+ isOverlayDraggable = isOverlayDraggable,+ keys = resetKeys+ )+ val scope = rememberCoroutineScope()+ val currentOnTransformationCommitted by rememberUpdatedState(onTransformationCommitted)+ var finishTransformationJob by remember(cropState) {+ mutableStateOf<Job?>(null)+ }+ var restoreSnapshotJob by remember(cropState) {+ mutableStateOf<Job?>(null)+ }+ val attachmentKey = remember(cropState) { Any() }+ val layoutKey = ImageCropperLayoutKey(+ containerSize = cropState.containerSize,+ drawAreaSize = IntSize(imageWidthPx, imageHeightPx)+ )+ val configurationKey = ImageCropperConfigurationKey(+ contentScale = contentScale,+ cropType = cropType,+ fixedAspectRatio = fixedAspectRatio,+ aspectRatio = resolvedCropProperties.aspectRatio,+ overlayRatio = resolvedCropProperties.overlayRatio,+ resetVersion = state.resetVersion+ )+ var previousCropState by remember(state) { mutableStateOf<CropState?>(null) }+ var previousAttachmentKey by remember(state) { mutableStateOf<Any?>(null) }+ var previousImageKey by remember(state) { mutableStateOf<Any?>(null) }+ var previousConfigurationKey by remember(state) {+ mutableStateOf<ImageCropperConfigurationKey?>(null)+ }+ val isRestoring = state.isRestoring || state.needsRestoreForLayout(+ attachmentKey = attachmentKey,+ imageKey = imageKey,+ layoutKey = layoutKey,+ configurationKey = configurationKey+ )++ fun attachState() {+ state.attach(+ attachmentKey = attachmentKey,+ imageKey = imageKey,+ layoutKey = layoutKey,+ configurationKey = configurationKey,+ captureSnapshot = {+ cropState.cropSnapshot+ },+ restoreSnapshot = { snapshot ->+ finishTransformationJob?.cancel()+ restoreSnapshotJob?.cancel()+ val restoreGeneration = state.beginRestore()+ restoreSnapshotJob = scope.launch {+ try {+ cropState.restoreCropSnapshot(snapshot)+ } finally {+ state.restoreCompleted(restoreGeneration)+ }+ }+ }+ )+ }++ fun beginTransformation() {+ finishTransformationJob?.cancel()+ attachState()+ state.beginTransformation()+ }++ fun endTransformation() {+ finishTransformationJob?.cancel()+ finishTransformationJob = scope.launch {+ delay(300)+ if (state.endTransformation()) {+ currentOnTransformationCommitted()+ }+ }+ }++ SideEffect {+ if (+ previousCropState != null &&+ previousCropState !== cropState &&+ previousImageKey == imageKey &&+ previousConfigurationKey == configurationKey+ ) {+ state.captureLayoutSnapshot(+ attachmentKey = previousAttachmentKey,+ snapshot = previousCropState?.cropSnapshot+ )+ }+ previousCropState = cropState+ previousAttachmentKey = attachmentKey+ previousImageKey = imageKey+ previousConfigurationKey = configurationKey+ }+ SideEffect {+ attachState()+ }+ LaunchedEffect(cropState, state, resolvedCropProperties) {+ cropState.awaitInitialization()+ cropState.updateProperties(+ cropProperties = resolvedCropProperties,+ animate = false+ )+ attachState()+ state.onCropperReady()+ restoreSnapshotJob?.join()+ state.syncSnapshot()+ }+ DisposableEffect(state, attachmentKey) {+ onDispose {+ finishTransformationJob?.cancel()+ restoreSnapshotJob?.cancel()+ state.prepareForReattachment(attachmentKey)+ state.detach(attachmentKey)+ }+ }++ LaunchedEffect(cropState, isOverlayDraggable) {+ if (cropState is DynamicCropState) {+ cropState.isOverlayDraggable = isOverlayDraggable+ }+ }++ if (!isRestoring) {+ onZoomChange(cropState.zoom)+ }++ val selectedHandle = if (cropState is DynamicCropState) {+ cropState.pressedHandle+ } else {+ TouchRegion.None+ }+ var animatedHandle by remember(cropState) {+ mutableStateOf(TouchRegion.None)+ }+ val selectedHandleScale = remember(cropState) {+ Animatable(1f)+ }+ LaunchedEffect(selectedHandle) {+ if (handlesTouched(selectedHandle)) {+ animatedHandle = selectedHandle+ selectedHandleScale.animateTo(1.4f)+ } else {+ selectedHandleScale.animateTo(1f)+ animatedHandle = TouchRegion.None+ }+ }++ // Crops image when user invokes crop operation+ Crop(+ crop = crop,+ sourceImageVisibleRect = rect,+ previewImageSize = IntSize(imageBitmap.width, imageBitmap.height),+ cropRect = cropState.cropRect,+ onCropStart = onCropStart,+ onCropSuccess = onCropSuccess+ )++ val imageModifier = Modifier+ .size(containerWidth, containerHeight)+ .crop(+ keys = resetKeys,+ cropState = cropState,+ enableOneFingerZoom = enableOneFingerZoom,+ onDown = { beginTransformation() },+ onUp = { endTransformation() },+ onGestureStart = { beginTransformation() },+ onGestureEnd = { endTransformation() }+ )++ ImageCropper(+ modifier = imageModifier,+ imageBitmap = imageBitmap,+ containerWidth = containerWidth,+ containerHeight = containerHeight,+ imageWidthPx = imageWidthPx,+ imageHeightPx = imageHeightPx,+ middleHandleSize = resolvedCropProperties.middleHandleSize,+ selectedHandle = animatedHandle,+ selectedHandleScale = selectedHandleScale.value,+ overlayRect = cropState.overlayRect,+ cropType = cropType,+ cropOutline = cropOutline,+ cropStyle = cropStyle,+ transparentColor = cropStyle.backgroundColor,+ backgroundModifier = backgroundModifier+ )+ }+}++@Composable+private fun ImageCropper(+ modifier: Modifier,+ imageBitmap: ImageBitmap,+ containerWidth: Dp,+ containerHeight: Dp,+ imageWidthPx: Int,+ imageHeightPx: Int,+ middleHandleSize: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ cropType: CropType,+ cropOutline: CropOutline,+ cropStyle: CropStyle,+ overlayRect: Rect,+ transparentColor: Color,+ backgroundModifier: Modifier+) {+ Box(+ modifier = Modifier+ .fillMaxSize()+ .then(backgroundModifier)+ .clipToBounds()+ ) {++ Box {+ ImageCropperImpl(+ modifier = modifier,+ imageBitmap = imageBitmap,+ containerWidth = containerWidth,+ containerHeight = containerHeight,+ imageWidthPx = imageWidthPx,+ imageHeightPx = imageHeightPx,+ cropType = cropType,+ cropOutline = cropOutline,+ middleHandleSize = middleHandleSize,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ cropStyle = cropStyle,+ rectOverlay = overlayRect,+ transparentColor = transparentColor+ )+ }+ }+}++@Composable+private fun ImageCropperImpl(+ modifier: Modifier,+ imageBitmap: ImageBitmap,+ containerWidth: Dp,+ containerHeight: Dp,+ imageWidthPx: Int,+ imageHeightPx: Int,+ cropType: CropType,+ cropOutline: CropOutline,+ middleHandleSize: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ cropStyle: CropStyle,+ transparentColor: Color,+ rectOverlay: Rect+) {++ Box(contentAlignment = Alignment.Center) {++ // Draw Image+ ImageDrawCanvas(+ modifier = modifier,+ imageBitmap = imageBitmap,+ imageWidth = imageWidthPx,+ imageHeight = imageHeightPx+ )++ val drawOverlay = cropStyle.drawOverlay++ val drawGrid = cropStyle.drawGrid+ val overlayColor = cropStyle.overlayColor+ val handleColor = cropStyle.handleColor+ val drawHandles = cropType == CropType.Dynamic+ val strokeWidth = cropStyle.strokeWidth++ DrawingOverlay(+ modifier = Modifier.size(containerWidth, containerHeight),+ drawOverlay = drawOverlay,+ rect = rectOverlay,+ cropOutline = cropOutline,+ drawGrid = drawGrid,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidth,+ drawHandles = drawHandles,+ middleHandleSize = middleHandleSize,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ transparentColor = transparentColor,+ )++ }+}++/**+ * ClearPDF: instead of cropping to a cache file, report the crop rectangle normalised to 0..1 of+ * the full [imageBitmap] so the editor can replay it at any resolution.+ */+@Composable+private fun Crop(+ crop: Boolean,+ sourceImageVisibleRect: IntRect,+ previewImageSize: IntSize,+ cropRect: Rect,+ onCropStart: () -> Unit,+ onCropSuccess: (Rect) -> Unit+) {+ LaunchedEffect(crop) {+ if (crop) {+ onCropStart()+ val w = previewImageSize.width.coerceAtLeast(1).toFloat()+ val h = previewImageSize.height.coerceAtLeast(1).toFloat()+ onCropSuccess(+ Rect(+ left = ((sourceImageVisibleRect.left + cropRect.left) / w).coerceIn(0f, 1f),+ top = ((sourceImageVisibleRect.top + cropRect.top) / h).coerceIn(0f, 1f),+ right = ((sourceImageVisibleRect.left + cropRect.right) / w).coerceIn(0f, 1f),+ bottom = ((sourceImageVisibleRect.top + cropRect.bottom) / h).coerceIn(0f, 1f)+ )+ )+ }+ }+}++@Composable+private fun getResetKeys(+ scaledImageBitmap: ImageBitmap,+ imageWidthPx: Int,+ imageHeightPx: Int,+ contentScale: ContentScale,+ cropType: CropType,+ fixedAspectRatio: Boolean,+ resetVersion: Int,+) = remember(+ scaledImageBitmap,+ imageWidthPx,+ imageHeightPx,+ contentScale,+ cropType,+ fixedAspectRatio,+ resetVersion,+) {+ arrayOf(+ scaledImageBitmap,+ imageWidthPx,+ imageHeightPx,+ contentScale,+ cropType,+ fixedAspectRatio,+ resetVersion,+ )+}++private val MinCropDimension = 100.dp++private data class ImageCropperLayoutKey(+ val containerSize: IntSize,+ val drawAreaSize: IntSize+)++private data class ImageCropperConfigurationKey(+ val contentScale: ContentScale,+ val cropType: CropType,+ val fixedAspectRatio: Boolean,+ val aspectRatio: AspectRatio,+ val overlayRatio: Float,+ val resetVersion: Int+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropperState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropperState.ktnew file mode 100644index 0000000..6c28ae6--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/ImageCropperState.kt@@ -0,0 +1,336 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.unit.IntSize++private const val MaxHistorySize = 50++@Stable+class ImageCropperState {+ var canUndo: Boolean by mutableStateOf(false)+ private set++ var canRedo: Boolean by mutableStateOf(false)+ private set++ internal var resetVersion: Int by mutableIntStateOf(0)+ private set++ private var imageKey: Any? = null+ private var attachmentKey: Any? = null+ private var layoutKey: Any? = null+ private var configurationKey: Any? = null+ private var captureSnapshot: (() -> ImageCropSnapshot?)? = null+ private var restoreSnapshot: ((ImageCropSnapshot) -> Unit)? = null+ private var pendingSnapshot: ImageCropSnapshot? = null+ private var pendingLayoutSnapshot: ImageCropSnapshot? = null+ private var currentSnapshot: ImageCropSnapshot? = null+ private var restoreCurrentSnapshotOnCropperReady = false+ private var skipSnapshotSyncForAttachment: Any? = null+ private var restoredAttachmentKey: Any? = null+ private var restoreGeneration = 0+ internal var isRestoring by mutableStateOf(false)+ private set+ private val undoHistory = ArrayDeque<ImageCropSnapshot>()+ private val redoHistory = ArrayDeque<ImageCropSnapshot>()++ fun undo() {+ endTransformation()+ val current = currentSnapshot ?: captureSnapshot?.invoke() ?: return+ val previous = undoHistory.removeLastOrNull() ?: return++ redoHistory.addLast(current)+ redoHistory.trimToMaxSize()+ currentSnapshot = previous+ restoreSnapshot?.invoke(previous)+ updateAvailability()+ }++ fun redo() {+ endTransformation()+ val current = currentSnapshot ?: captureSnapshot?.invoke() ?: return+ val next = redoHistory.removeLastOrNull() ?: return++ undoHistory.addLast(current)+ undoHistory.trimToMaxSize()+ currentSnapshot = next+ restoreSnapshot?.invoke(next)+ updateAvailability()+ }++ fun beginTransformation() {+ restoreCurrentSnapshotOnCropperReady = false+ if (restoredAttachmentKey === attachmentKey) {+ restoredAttachmentKey = null+ }+ if (pendingSnapshot == null) {+ pendingSnapshot = captureSnapshot?.invoke()+ }+ }++ fun endTransformation(): Boolean {+ val before = pendingSnapshot ?: return false+ pendingSnapshot = null+ val after = captureSnapshot?.invoke() ?: return false+ currentSnapshot = after++ if (before != after) {+ undoHistory.addLast(before)+ undoHistory.trimToMaxSize()+ redoHistory.clear()+ updateAvailability()+ return true+ }+ return false+ }++ fun discardPendingTransformation() {+ pendingSnapshot = null+ }++ fun prepareForReattachment(attachmentKey: Any? = null) {+ if (attachmentKey != null && this.attachmentKey !== attachmentKey) return+ if (restoreCurrentSnapshotOnCropperReady) return++ if (pendingSnapshot != null || currentSnapshot == null) {+ captureSnapshot?.invoke()?.let { currentSnapshot = it }+ }+ restoreCurrentSnapshotOnCropperReady = currentSnapshot != null+ }++ fun finishReattachment() {+ restoreCurrentSnapshotOnCropperReady = false+ }++ internal fun attach(+ attachmentKey: Any,+ imageKey: Any?,+ layoutKey: Any? = null,+ configurationKey: Any? = null,+ captureSnapshot: () -> ImageCropSnapshot?,+ restoreSnapshot: (ImageCropSnapshot) -> Unit+ ) {+ val imageChanged = this.imageKey != imageKey+ val attachmentChanged = this.attachmentKey != null &&+ this.attachmentKey !== attachmentKey+ val layoutChanged = !imageChanged &&+ this.layoutKey != null &&+ layoutKey != null &&+ this.layoutKey != layoutKey+ val canRestorePreviousLayout = !imageChanged &&+ this.configurationKey == configurationKey &&+ (attachmentChanged || layoutChanged)+ if (canRestorePreviousLayout) {+ pendingLayoutSnapshot?.let { currentSnapshot = it }+ // A pending transformation belongs to the outgoing CropState, so capture its live+ // geometry. Otherwise keep the committed snapshot: the old layout can already be in+ // a temporary measure state while the replacement CropState is being attached.+ if (pendingLayoutSnapshot == null && (pendingSnapshot != null || currentSnapshot == null)) {+ this.captureSnapshot?.invoke()?.let { currentSnapshot = it }+ }+ restoreCurrentSnapshotOnCropperReady = currentSnapshot != null+ isRestoring = restoreCurrentSnapshotOnCropperReady+ pendingSnapshot = null+ pendingLayoutSnapshot = null+ }+ val configurationChanged = !imageChanged &&+ this.configurationKey != null &&+ this.configurationKey != configurationKey+ if (imageChanged) {+ this.imageKey = imageKey+ pendingSnapshot = null+ pendingLayoutSnapshot = null+ currentSnapshot = null+ restoreCurrentSnapshotOnCropperReady = false+ skipSnapshotSyncForAttachment = null+ restoredAttachmentKey = null+ isRestoring = false+ undoHistory.clear()+ redoHistory.clear()+ updateAvailability()+ } else if (configurationChanged) {+ pendingSnapshot = null+ pendingLayoutSnapshot = null+ currentSnapshot = null+ restoreCurrentSnapshotOnCropperReady = false+ skipSnapshotSyncForAttachment = null+ restoredAttachmentKey = null+ isRestoring = false+ }+ this.attachmentKey = attachmentKey+ this.layoutKey = layoutKey+ this.configurationKey = configurationKey+ this.captureSnapshot = captureSnapshot+ this.restoreSnapshot = restoreSnapshot+ }++ internal fun detach(attachmentKey: Any) {+ if (this.attachmentKey !== attachmentKey) return+ if (skipSnapshotSyncForAttachment === attachmentKey) {+ skipSnapshotSyncForAttachment = null+ }+ this.attachmentKey = null+ captureSnapshot = null+ restoreSnapshot = null+ pendingSnapshot = null+ }++ /**+ * Stores geometry from the outgoing CropState before Compose replaces it for a new viewport.+ * Unlike a callback captured during attachment, this state still uses the old immutable+ * container and draw-area sizes, so it cannot contain a partially measured frame.+ */+ internal fun captureLayoutSnapshot(+ attachmentKey: Any?,+ snapshot: ImageCropSnapshot?+ ) {+ if (attachmentKey != null && restoredAttachmentKey === attachmentKey) return+ if (snapshot != null) {+ pendingLayoutSnapshot = snapshot+ }+ }++ internal fun onCropperReady() {+ if (restoreCurrentSnapshotOnCropperReady) {+ currentSnapshot?.let { restoreSnapshot?.invoke(it) }+ restoreCurrentSnapshotOnCropperReady = false+ skipSnapshotSyncForAttachment = attachmentKey+ restoredAttachmentKey = attachmentKey+ } else if (currentSnapshot == null) {+ currentSnapshot = captureSnapshot?.invoke()+ }+ }++ /**+ * Refreshes the reattachment snapshot after a non-gesture geometry change, such as choosing+ * another aspect ratio. Without this, a later configuration change restores the frame that+ * existed before the aspect-ratio change.+ */+ internal fun syncSnapshot() {+ if (skipSnapshotSyncForAttachment === attachmentKey) {+ skipSnapshotSyncForAttachment = null+ return+ }+ if (pendingSnapshot == null && !restoreCurrentSnapshotOnCropperReady) {+ currentSnapshot = captureSnapshot?.invoke() ?: currentSnapshot+ }+ }++ internal fun beginRestore(): Int {+ restoreGeneration+++ isRestoring = true+ return restoreGeneration+ }++ internal fun restoreCompleted(generation: Int) {+ if (restoreGeneration == generation) {+ isRestoring = false+ }+ }++ fun clearHistory() {+ pendingSnapshot = null+ pendingLayoutSnapshot = null+ currentSnapshot = captureSnapshot?.invoke()+ restoreCurrentSnapshotOnCropperReady = false+ skipSnapshotSyncForAttachment = null+ restoredAttachmentKey = null+ isRestoring = false+ undoHistory.clear()+ redoHistory.clear()+ updateAvailability()+ }++ fun reset() {+ attachmentKey = null+ layoutKey = null+ configurationKey = null+ pendingSnapshot = null+ pendingLayoutSnapshot = null+ currentSnapshot = null+ restoreCurrentSnapshotOnCropperReady = false+ skipSnapshotSyncForAttachment = null+ restoredAttachmentKey = null+ isRestoring = false+ undoHistory.clear()+ redoHistory.clear()+ resetVersion+++ updateAvailability()+ }++ internal fun needsRestoreForLayout(+ attachmentKey: Any,+ imageKey: Any?,+ layoutKey: Any?,+ configurationKey: Any?+ ): Boolean {+ if (this.imageKey != imageKey || this.configurationKey != configurationKey) return false+ if (currentSnapshot == null) return false++ val attachmentChanged = this.attachmentKey != null && this.attachmentKey !== attachmentKey+ val layoutChanged =+ this.layoutKey != null && layoutKey != null && this.layoutKey != layoutKey+ return restoreCurrentSnapshotOnCropperReady || attachmentChanged || layoutChanged+ }++ internal fun preferredContainerSize(+ imageKey: Any?,+ measuredSize: IntSize+ ): IntSize {+ // An adaptive parent can report a taller max constraint after an orientation round trip+ // while the visible viewport keeps its old size. Reuse that viewport only when its width+ // still matches; a real orientation change must use the newly measured dimensions.+ val snapshotSize = currentSnapshot?.containerSize ?: return measuredSize+ if (this.imageKey != imageKey || snapshotSize.height <= 0) return measuredSize++ return if (snapshotSize.width == measuredSize.width) snapshotSize else measuredSize+ }++ private fun updateAvailability() {+ canUndo = undoHistory.isNotEmpty()+ canRedo = redoHistory.isNotEmpty()+ }++ private fun ArrayDeque<ImageCropSnapshot>.trimToMaxSize() {+ while (size > MaxHistorySize) removeFirst()+ }+}++@Composable+fun rememberImageCropperState(): ImageCropperState = remember {+ ImageCropperState()+}++internal data class ImageCropSnapshot(+ val normalizedCropRect: Rect,+ val normalizedOverlayCenter: Offset = Offset(0.5f, 0.5f),+ val overlaySizeFraction: Float = 0.8f,+ val containerSize: IntSize = IntSize.Zero,+ val rotation: Float+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/TouchRegion.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/TouchRegion.ktnew file mode 100644index 0000000..a3f3302--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/TouchRegion.kt@@ -0,0 +1,31 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper++/**+ * Enum for detecting which section of Composable user has initially touched+ */+enum class TouchRegion {+ TopLeft, TopRight, BottomLeft, BottomRight,+ TopCenter, CenterRight, BottomCenter, CenterLeft,+ Inside, None+}++fun handlesTouched(touchRegion: TouchRegion) =+ touchRegion != TouchRegion.None && touchRegion != TouchRegion.Insidediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/crop/CropAgent.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/crop/CropAgent.ktnew file mode 100644index 0000000..b9affe9--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/crop/CropAgent.kt@@ -0,0 +1,201 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.crop++import android.graphics.Bitmap+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Paint+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.addOutline+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.asAndroidPath+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.nativeCanvas+import androidx.compose.ui.graphics.toComposeRect+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.toSize+import androidx.core.graphics.scale+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropImageMask+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropOutline+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropPath+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropShape+import kotlin.math.roundToInt+++/**+ * Crops imageBitmap based on path that is passed in [crop] function+ */+/** ClearPDF: made public and stripped of the URI/cache path — the editor replays crops itself. */+class CropAgent {++ private val imagePaint = Paint().apply {+ blendMode = BlendMode.SrcIn+ }++ private val paint = Paint()+++ fun crop(+ imageBitmap: ImageBitmap,+ cropRect: Rect,+ cropOutline: CropOutline,+ layoutDirection: LayoutDirection,+ density: Density,+ ): ImageBitmap {+ return runCatching {+ val roundedCropRect = cropRect.roundedInBounds(+ width = imageBitmap.width,+ height = imageBitmap.height+ )+ val croppedBitmap: Bitmap = Bitmap.createBitmap(+ imageBitmap.asAndroidBitmap(),+ roundedCropRect.left,+ roundedCropRect.top,+ roundedCropRect.width,+ roundedCropRect.height,+ )++ val imageToCrop = croppedBitmap+ .copy(Bitmap.Config.ARGB_8888, true)+ .apply { setHasAlpha(true) }+ .asImageBitmap()++ drawCroppedImage(+ cropOutline = cropOutline,+ cropSize = roundedCropRect.size,+ layoutDirection = layoutDirection,+ density = density,+ imageToCrop = imageToCrop+ )++ imageToCrop+ }.getOrNull() ?: imageBitmap+ }++ private fun drawCroppedImage(+ cropOutline: CropOutline,+ cropSize: IntSize,+ layoutDirection: LayoutDirection,+ density: Density,+ imageToCrop: ImageBitmap,+ ) {++ when (cropOutline) {+ is CropShape -> {++ val path = Path().apply {+ val outline =+ cropOutline.shape.createOutline(cropSize.toSize(), layoutDirection, density)+ addOutline(outline)+ }++ Canvas(image = imageToCrop).run {+ saveLayer(nativeCanvas.clipBounds.toComposeRect(), imagePaint)++ // Destination+ drawPath(path, paint)++ // Source+ drawImage(+ image = imageToCrop,+ topLeftOffset = Offset.Zero,+ paint = imagePaint+ )+ restore()+ }+ }++ is CropPath -> {++ val path = Path().apply {++ addPath(cropOutline.path)++ val pathSize = getBounds().size+ val rectSize = cropSize.toSize()++ val matrix = android.graphics.Matrix()+ matrix.postScale(+ rectSize.width / pathSize.width,+ rectSize.height / pathSize.height+ )+ this.asAndroidPath().transform(matrix)++ val left = getBounds().left+ val top = getBounds().top++ translate(Offset(-left, -top))+ }++ Canvas(image = imageToCrop).run {+ saveLayer(nativeCanvas.clipBounds.toComposeRect(), imagePaint)++ // Destination+ drawPath(path, paint)++ // Source+ drawImage(image = imageToCrop, topLeftOffset = Offset.Zero, imagePaint)+ restore()+ }+ }++ is CropImageMask -> {++ val imageMask = cropOutline.image.asAndroidBitmap()+ .scale(cropSize.width, cropSize.height).asImageBitmap()++ Canvas(image = imageToCrop).run {+ saveLayer(nativeCanvas.clipBounds.toComposeRect(), imagePaint)++ // Destination+ drawImage(imageMask, topLeftOffset = Offset.Zero, paint)++ // Source+ drawImage(image = imageToCrop, topLeftOffset = Offset.Zero, imagePaint)++ restore()+ }+ }+ }+ }+}++internal fun Rect.roundedInBounds(+ width: Int,+ height: Int+): IntRect {+ val roundedWidth = this.width.roundToInt().coerceIn(1, width)+ val roundedHeight = this.height.roundToInt().coerceIn(1, height)+ val roundedLeft = left.roundToInt().coerceIn(0, width - roundedWidth)+ val roundedTop = top.roundToInt().coerceIn(0, height - roundedHeight)++ return IntRect(+ left = roundedLeft,+ top = roundedTop,+ right = roundedLeft + roundedWidth,+ bottom = roundedTop + roundedHeight+ )+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/ImageDrawCanvas.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/ImageDrawCanvas.ktnew file mode 100644index 0000000..9b93fe0--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/ImageDrawCanvas.kt@@ -0,0 +1,54 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.draw++import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import kotlin.math.roundToInt++/**+ * Draw image to be cropped+ */+@Composable+internal fun ImageDrawCanvas(+ modifier: Modifier,+ imageBitmap: ImageBitmap,+ imageWidth: Int,+ imageHeight: Int+) {+ Canvas(modifier = modifier) {++ val canvasWidth = size.width.roundToInt()+ val canvasHeight = size.height.roundToInt()++ drawImage(+ image = imageBitmap,+ srcSize = IntSize(imageBitmap.width, imageBitmap.height),+ dstSize = IntSize(imageWidth, imageHeight),+ dstOffset = IntOffset(+ x = (canvasWidth - imageWidth) / 2,+ y = (canvasHeight - imageHeight) / 2+ )+ )+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/Overlay.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/Overlay.ktnew file mode 100644index 0000000..60ee47f--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/draw/Overlay.kt@@ -0,0 +1,591 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.draw++import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.StrokeJoin+import androidx.compose.ui.graphics.drawOutline+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.platform.LocalLayoutDirection+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.LayoutDirection+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.TouchRegion+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropImageMask+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropOutline+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropPath+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropShape+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.drawGrid+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.drawWithLayer+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.scaleAndTranslatePath+import androidx.compose.ui.graphics.compositeOver++/**+ * Draw overlay composed of 9 rectangles. When [drawHandles]+ * is set draw handles for changing drawing rectangle+ */+@Composable+internal fun DrawingOverlay(+ modifier: Modifier,+ drawOverlay: Boolean,+ rect: Rect,+ cropOutline: CropOutline,+ drawGrid: Boolean,+ transparentColor: Color,+ overlayColor: Color,+ handleColor: Color,+ strokeWidth: Dp,+ drawHandles: Boolean,+ middleHandleSize: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+) {+ val density = LocalDensity.current+ val layoutDirection: LayoutDirection = LocalLayoutDirection.current++ val strokeWidthPx = LocalDensity.current.run { strokeWidth.toPx() }+ val handleSizePx = with(density) { CornerHandleSize.toPx() }+ val middleHandleSizePx = with(density) { middleHandleSize.dp.toPx() }+ val handleStrokeWidthPx = with(density) { CornerHandleStrokeWidth.toPx() }+ val middleHandleStrokeWidthPx = with(density) { MiddleHandleStrokeWidth.toPx() }++ val pathHandles = remember {+ Path()+ }++ val middlePathHandles = remember {+ Path()+ }++ val selectedPathHandle = remember {+ Path()+ }++ when (cropOutline) {+ is CropShape -> {++ val outline = remember(rect, cropOutline) {+ cropOutline.shape.createOutline(rect.size, layoutDirection, density)+ }++ DrawingOverlayImpl(+ modifier = modifier,+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidthPx,+ drawHandles = drawHandles,+ handleSize = handleSizePx,+ middleHandleSize = middleHandleSizePx,+ handleStrokeWidth = handleStrokeWidthPx,+ middleHandleStrokeWidth = middleHandleStrokeWidthPx,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle,+ outline = outline+ )+ }++ is CropPath -> {+ val path = remember(rect, cropOutline) {+ Path().apply {+ addPath(cropOutline.path)+ scaleAndTranslatePath(rect.width, rect.height)+ }+ }+++ DrawingOverlayImpl(+ modifier = modifier,+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidthPx,+ drawHandles = drawHandles,+ handleSize = handleSizePx,+ middleHandleSize = middleHandleSizePx,+ handleStrokeWidth = handleStrokeWidthPx,+ middleHandleStrokeWidth = middleHandleStrokeWidthPx,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle,+ path = path+ )+ }++ is CropImageMask -> {+ val imageBitmap = cropOutline.image++ DrawingOverlayImpl(+ modifier = modifier,+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidthPx,+ drawHandles = drawHandles,+ handleSize = handleSizePx,+ middleHandleSize = middleHandleSizePx,+ handleStrokeWidth = handleStrokeWidthPx,+ middleHandleStrokeWidth = middleHandleStrokeWidthPx,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle,+ image = imageBitmap+ )+ }+ }+}++@Composable+private fun DrawingOverlayImpl(+ modifier: Modifier,+ drawOverlay: Boolean,+ rect: Rect,+ drawGrid: Boolean,+ transparentColor: Color,+ overlayColor: Color,+ handleColor: Color,+ strokeWidth: Float,+ drawHandles: Boolean,+ handleSize: Float,+ middleHandleSize: Float,+ handleStrokeWidth: Float,+ middleHandleStrokeWidth: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ pathHandles: Path,+ middlePathHandles: Path,+ selectedPathHandle: Path,+ outline: Outline,+) {+ Canvas(modifier = modifier) {+ drawOverlay(+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidth,+ drawHandles = drawHandles,+ handleSize = handleSize,+ middleHandleSize = middleHandleSize,+ handleStrokeWidth = handleStrokeWidth,+ middleHandleStrokeWidth = middleHandleStrokeWidth,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle+ ) {+ drawCropOutline(outline = outline)+ }+ }+}++@Composable+private fun DrawingOverlayImpl(+ modifier: Modifier,+ drawOverlay: Boolean,+ rect: Rect,+ drawGrid: Boolean,+ transparentColor: Color,+ overlayColor: Color,+ handleColor: Color,+ strokeWidth: Float,+ drawHandles: Boolean,+ handleSize: Float,+ middleHandleSize: Float,+ handleStrokeWidth: Float,+ middleHandleStrokeWidth: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ pathHandles: Path,+ middlePathHandles: Path,+ selectedPathHandle: Path,+ path: Path,+) {+ Canvas(modifier = modifier) {+ drawOverlay(+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidth,+ drawHandles = drawHandles,+ handleSize = handleSize,+ middleHandleSize = middleHandleSize,+ handleStrokeWidth = handleStrokeWidth,+ middleHandleStrokeWidth = middleHandleStrokeWidth,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle+ ) {+ drawCropPath(path)+ }+ }+}++@Composable+private fun DrawingOverlayImpl(+ modifier: Modifier,+ drawOverlay: Boolean,+ rect: Rect,+ drawGrid: Boolean,+ transparentColor: Color,+ overlayColor: Color,+ handleColor: Color,+ strokeWidth: Float,+ drawHandles: Boolean,+ handleSize: Float,+ middleHandleSize: Float,+ handleStrokeWidth: Float,+ middleHandleStrokeWidth: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ pathHandles: Path,+ middlePathHandles: Path,+ selectedPathHandle: Path,+ image: ImageBitmap,+) {+ Canvas(modifier = modifier) {+ drawOverlay(+ drawOverlay = drawOverlay,+ rect = rect,+ drawGrid = drawGrid,+ transparentColor = transparentColor,+ overlayColor = overlayColor,+ handleColor = handleColor,+ strokeWidth = strokeWidth,+ drawHandles = drawHandles,+ handleSize = handleSize,+ middleHandleSize = middleHandleSize,+ handleStrokeWidth = handleStrokeWidth,+ middleHandleStrokeWidth = middleHandleStrokeWidth,+ selectedHandle = selectedHandle,+ selectedHandleScale = selectedHandleScale,+ pathHandles = pathHandles,+ middlePathHandles = middlePathHandles,+ selectedPathHandle = selectedPathHandle+ ) {+ drawCropImage(rect, image)+ }+ }+}++private fun DrawScope.drawOverlay(+ drawOverlay: Boolean,+ rect: Rect,+ drawGrid: Boolean,+ transparentColor: Color,+ overlayColor: Color,+ handleColor: Color,+ strokeWidth: Float,+ drawHandles: Boolean,+ handleSize: Float,+ middleHandleSize: Float,+ handleStrokeWidth: Float,+ middleHandleStrokeWidth: Float,+ selectedHandle: TouchRegion,+ selectedHandleScale: Float,+ pathHandles: Path,+ middlePathHandles: Path,+ selectedPathHandle: Path,+ drawBlock: DrawScope.() -> Unit+) {+ drawWithLayer {++ // Destination+ drawRect(transparentColor)++ // Source+ translate(left = rect.left, top = rect.top) {+ drawBlock()+ }++ if (drawGrid) {+ drawGrid(+ rect = rect,+ strokeWidth = strokeWidth,+ color = overlayColor+ )+ }+ }++ if (drawOverlay) {+ drawRect(+ topLeft = rect.topLeft,+ size = rect.size,+ color = overlayColor,+ style = Stroke(width = strokeWidth)+ )++ if (drawHandles) {+ pathHandles.apply {+ reset()+ updateHandlePath(rect, handleSize)+ }++ middlePathHandles.apply {+ reset()+ updateMiddleHandlePath(rect, middleHandleSize)+ }++ drawPath(+ path = middlePathHandles,+ color = handleColor.copy(0.9f).compositeOver(Color.Black),+ style = Stroke(+ width = middleHandleStrokeWidth,+ cap = StrokeCap.Round,+ join = StrokeJoin.Round+ )+ )++ drawPath(+ path = pathHandles,+ color = handleColor,+ style = Stroke(+ width = handleStrokeWidth,+ cap = StrokeCap.Round,+ join = StrokeJoin.Round+ )+ )++ val selectedHandleSize = when (selectedHandle) {+ TouchRegion.TopCenter,+ TouchRegion.CenterRight,+ TouchRegion.BottomCenter,+ TouchRegion.CenterLeft -> middleHandleSize++ else -> handleSize+ }+ selectedPathHandle.apply {+ reset()+ updateSelectedHandlePath(+ rect = rect,+ handleSize = selectedHandleSize * selectedHandleScale,+ selectedHandle = selectedHandle+ )+ }++ if (!selectedPathHandle.isEmpty) {+ val middleHandleSelected = selectedHandle == TouchRegion.TopCenter ||+ selectedHandle == TouchRegion.CenterRight ||+ selectedHandle == TouchRegion.BottomCenter ||+ selectedHandle == TouchRegion.CenterLeft+ drawPath(+ path = selectedPathHandle,+ color = if (middleHandleSelected) {+ handleColor.copy(0.9f).compositeOver(Color.Black)+ } else {+ handleColor+ },+ style = Stroke(+ width = (if (middleHandleSelected) {+ middleHandleStrokeWidth+ } else {+ handleStrokeWidth+ }) * selectedHandleScale,+ cap = StrokeCap.Round,+ join = StrokeJoin.Round+ )+ )+ }+ }+ }+}++private fun DrawScope.drawCropImage(+ rect: Rect,+ imageBitmap: ImageBitmap,+ blendMode: BlendMode = BlendMode.DstOut+) {+ drawImage(+ image = imageBitmap,+ dstSize = IntSize(rect.size.width.toInt(), rect.size.height.toInt()),+ blendMode = blendMode+ )+}++private fun DrawScope.drawCropOutline(+ outline: Outline,+ blendMode: BlendMode = BlendMode.SrcOut+) {+ drawOutline(+ outline = outline,+ color = Color.Transparent,+ blendMode = blendMode+ )+}++private fun DrawScope.drawCropPath(+ path: Path,+ blendMode: BlendMode = BlendMode.SrcOut+) {+ drawPath(+ path = path,+ color = Color.Transparent,+ blendMode = blendMode+ )+}++private fun Path.updateHandlePath(+ rect: Rect,+ handleSize: Float+) {+ if (rect != Rect.Zero) {+ // Top left lines+ moveTo(rect.topLeft.x, rect.topLeft.y + handleSize)+ lineTo(rect.topLeft.x, rect.topLeft.y)+ lineTo(rect.topLeft.x + handleSize, rect.topLeft.y)++ // Top right lines+ moveTo(rect.topRight.x - handleSize, rect.topRight.y)+ lineTo(rect.topRight.x, rect.topRight.y)+ lineTo(rect.topRight.x, rect.topRight.y + handleSize)++ // Bottom right lines+ moveTo(rect.bottomRight.x, rect.bottomRight.y - handleSize)+ lineTo(rect.bottomRight.x, rect.bottomRight.y)+ lineTo(rect.bottomRight.x - handleSize, rect.bottomRight.y)++ // Bottom left lines+ moveTo(rect.bottomLeft.x + handleSize, rect.bottomLeft.y)+ lineTo(rect.bottomLeft.x, rect.bottomLeft.y)+ lineTo(rect.bottomLeft.x, rect.bottomLeft.y - handleSize)+ }+}+++private fun Path.updateMiddleHandlePath(+ rect: Rect,+ handleSize: Float+) {+ if (rect != Rect.Zero) {+ // Top middle lines+ moveTo(rect.topCenter.x - handleSize / 2, rect.topCenter.y)+ lineTo(rect.topCenter.x + handleSize / 2, rect.topCenter.y)++ // Right middle lines+ moveTo(rect.centerRight.x, rect.centerRight.y - handleSize / 2)+ lineTo(rect.centerRight.x, rect.centerRight.y + handleSize / 2)++ // Bottom middle lines+ moveTo(rect.bottomCenter.x - handleSize / 2, rect.bottomCenter.y)+ lineTo(rect.bottomCenter.x + handleSize / 2, rect.bottomCenter.y)++ // Left middle lines+ moveTo(rect.centerLeft.x, rect.centerLeft.y - handleSize / 2)+ lineTo(rect.centerLeft.x, rect.centerLeft.y + handleSize / 2)+ }+}++private fun Path.updateSelectedHandlePath(+ rect: Rect,+ handleSize: Float,+ selectedHandle: TouchRegion+) {+ if (rect == Rect.Zero) return++ when (selectedHandle) {+ TouchRegion.TopLeft -> {+ moveTo(rect.left, rect.top + handleSize)+ lineTo(rect.left, rect.top)+ lineTo(rect.left + handleSize, rect.top)+ }++ TouchRegion.TopRight -> {+ moveTo(rect.right - handleSize, rect.top)+ lineTo(rect.right, rect.top)+ lineTo(rect.right, rect.top + handleSize)+ }++ TouchRegion.BottomRight -> {+ moveTo(rect.right, rect.bottom - handleSize)+ lineTo(rect.right, rect.bottom)+ lineTo(rect.right - handleSize, rect.bottom)+ }++ TouchRegion.BottomLeft -> {+ moveTo(rect.left + handleSize, rect.bottom)+ lineTo(rect.left, rect.bottom)+ lineTo(rect.left, rect.bottom - handleSize)+ }++ TouchRegion.TopCenter -> {+ moveTo(rect.topCenter.x - handleSize / 2, rect.top)+ lineTo(rect.topCenter.x + handleSize / 2, rect.top)+ }++ TouchRegion.CenterRight -> {+ moveTo(rect.right, rect.centerRight.y - handleSize / 2)+ lineTo(rect.right, rect.centerRight.y + handleSize / 2)+ }++ TouchRegion.BottomCenter -> {+ moveTo(rect.bottomCenter.x - handleSize / 2, rect.bottom)+ lineTo(rect.bottomCenter.x + handleSize / 2, rect.bottom)+ }++ TouchRegion.CenterLeft -> {+ moveTo(rect.left, rect.centerLeft.y - handleSize / 2)+ lineTo(rect.left, rect.centerLeft.y + handleSize / 2)+ }++ TouchRegion.Inside,+ TouchRegion.None -> Unit+ }+}++private val CornerHandleSize = 20.dp+private val CornerHandleStrokeWidth = 4.dp+private val MiddleHandleStrokeWidth = 3.5.dp\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageScope.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageScope.ktnew file mode 100644index 0000000..dd0cb35--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageScope.kt@@ -0,0 +1,146 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.image++import android.graphics.Bitmap+import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.remember+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntRect+++/**+ * Receiver scope being used by the children parameter of [ImageWithConstraints]+ */+@Stable+interface ImageScope {+ /**+ * The constraints given by the parent layout in pixels.+ *+ * Use [minWidth], [maxWidth], [minHeight] or [maxHeight] if you need value in [Dp].+ */+ val constraints: Constraints++ /**+ * The minimum width in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val minWidth: Dp++ /**+ * The maximum width in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val maxWidth: Dp++ /**+ * The minimum height in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val minHeight: Dp++ /**+ * The maximum height in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val maxHeight: Dp++ /**+ * Width of area inside BoxWithConstraints that is scaled based on [ContentScale]+ * This is width of the [Canvas] draw [ImageBitmap]+ */+ val imageWidth: Dp++ /**+ * Height of area inside BoxWithConstraints that is scaled based on [ContentScale]+ * This is height of the [Canvas] draw [ImageBitmap]+ */+ val imageHeight: Dp++ /**+ * [IntRect] that covers boundaries of [ImageBitmap]+ */+ val rect: IntRect+}++internal data class ImageScopeImpl(+ private val density: Density,+ override val constraints: Constraints,+ override val imageWidth: Dp,+ override val imageHeight: Dp,+ override val rect: IntRect,+) : ImageScope {++ override val minWidth: Dp get() = with(density) { constraints.minWidth.toDp() }++ override val maxWidth: Dp+ get() = with(density) {+ if (constraints.hasBoundedWidth) constraints.maxWidth.toDp() else Dp.Infinity+ }++ override val minHeight: Dp get() = with(density) { constraints.minHeight.toDp() }++ override val maxHeight: Dp+ get() = with(density) {+ if (constraints.hasBoundedHeight) constraints.maxHeight.toDp() else Dp.Infinity+ }+}++@Composable+internal fun getScaledImageBitmap(+ imageWidth: Dp,+ imageHeight: Dp,+ rect: IntRect,+ bitmap: ImageBitmap,+ contentScale: ContentScale+): ImageBitmap {++ val scaledBitmap =+ remember(bitmap, rect, imageWidth, imageHeight, contentScale) {+ // This bitmap is needed when we crop original bitmap due to scaling mode+ // and aspect ratio result of cropping+ // We might have center section of the image after cropping, and+ // because of that thumbLayout either should have rectangle and some+ // complex calculation for srcOffset and srcSide along side with touch offset+ // or we can create a new bitmap that only contains area bounded by rectangle+ runCatching {+ Bitmap.createBitmap(+ bitmap.asAndroidBitmap(),+ rect.left,+ rect.top,+ rect.width,+ rect.height+ ).asImageBitmap()+ }.getOrNull() ?: bitmap+ }+ return scaledBitmap+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageWithConstraints.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageWithConstraints.ktnew file mode 100644index 0000000..d41f21f--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/image/ImageWithConstraints.kt@@ -0,0 +1,251 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.image++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.DefaultAlpha+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.getParentSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.getScaledBitmapRect+++/**+ * A composable that lays out and draws a given [ImageBitmap]. This will attempt to+ * size the composable according to the [ImageBitmap]'s given width and height. However, an+ * optional [Modifier] parameter can be provided to adjust sizing or draw additional content (ex.+ * background). Any unspecified dimension will leverage the [ImageBitmap]'s size as a minimum+ * constraint.+ *+ * [ImageScope] returns constraints, width and height of the drawing area based on [contentScale]+ * and rectangle of [imageBitmap] drawn. When a bitmap is displayed scaled to fit area of Composable+ * space used for drawing image is represented with [ImageScope.imageWidth] and+ * [ImageScope.imageHeight].+ *+ * When we display a bitmap 1000x1000px with [ContentScale.Crop] if it's cropped to 500x500px+ * [ImageScope.rect] returns `IntRect(250,250,750,750)`.+ *+ * @param alignment determines where image will be aligned inside [BoxWithConstraints]+ * This is observable when bitmap image/width ratio differs from [Canvas] that draws [ImageBitmap]+ * @param contentDescription text used by accessibility services to describe what this image+ * represents. This should always be provided unless this image is used for decorative purposes,+ * and does not represent a meaningful action that a user can take. This text should be+ * localized, such as by using [androidx.compose.ui.res.stringResource] or similar+ * @param contentScale how image should be scaled inside Canvas to match parent dimensions.+ * [ContentScale.Fit] for instance maintains src ratio and scales image to fit inside the parent.+ * @param alpha Opacity to be applied to [imageBitmap] from 0.0f to 1.0f representing+ * fully transparent to fully opaque respectively+ * @param colorFilter ColorFilter to apply to the [imageBitmap] when drawn into the destination+ * @param filterQuality Sampling algorithm applied to the [imageBitmap] when it is scaled and drawn+ * into the destination. The default is [FilterQuality.Low] which scales using a bilinear+ * sampling algorithm+ * @param content is a Composable that can be matched at exact position where [imageBitmap] is drawn.+ * This is useful for drawing thumbs, cropping or another layout that should match position+ * with the image that is scaled is drawn+ * @param drawImage flag to draw image on canvas. Some Composables might only require+ * the calculation and rectangle bounds of image after scaling but not drawing.+ * Composables like image cropper that scales or+ * rotates image. Drawing here again have 2 drawings overlap each other.+ */+@Composable+internal fun ImageWithConstraints(+ modifier: Modifier = Modifier,+ imageBitmap: ImageBitmap,+ alignment: Alignment = Alignment.Center,+ contentScale: ContentScale = ContentScale.Fit,+ contentDescription: String? = null,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+ drawImage: Boolean = true,+ content: @Composable ImageScope.() -> Unit = {}+) {++ val semantics = if (contentDescription != null) {+ Modifier.semantics {+ this.contentDescription = contentDescription+ this.role = Role.Image+ }+ } else {+ Modifier+ }++ BoxWithConstraints(+ modifier = modifier+ .then(semantics),+ contentAlignment = alignment,+ ) {++ val bitmapWidth = imageBitmap.width+ val bitmapHeight = imageBitmap.height++ val (boxWidth: Int, boxHeight: Int) = getParentSize(bitmapWidth, bitmapHeight)++ // Src is Bitmap, Dst is the container(Image) that Bitmap will be displayed+ val srcSize = Size(bitmapWidth.toFloat(), bitmapHeight.toFloat())+ val dstSize = Size(boxWidth.toFloat(), boxHeight.toFloat())++ val scaleFactor = contentScale.computeScaleFactor(srcSize, dstSize)++ // Image is the container for bitmap that is located inside Box+ // image bounds can be smaller or bigger than its parent based on how it's scaled+ val imageWidth = bitmapWidth * scaleFactor.scaleX+ val imageHeight = bitmapHeight * scaleFactor.scaleY++ val bitmapRect = getScaledBitmapRect(+ boxWidth = boxWidth,+ boxHeight = boxHeight,+ imageWidth = imageWidth,+ imageHeight = imageHeight,+ bitmapWidth = bitmapWidth,+ bitmapHeight = bitmapHeight+ )++ ImageLayout(+ constraints = constraints,+ imageBitmap = imageBitmap,+ bitmapRect = bitmapRect,+ imageWidth = imageWidth,+ imageHeight = imageHeight,+ boxWidth = boxWidth,+ boxHeight = boxHeight,+ alpha = alpha,+ colorFilter = colorFilter,+ filterQuality = filterQuality,+ drawImage = drawImage,+ content = content+ )+ }+}++@Composable+private fun ImageLayout(+ constraints: Constraints,+ imageBitmap: ImageBitmap,+ bitmapRect: IntRect,+ imageWidth: Float,+ imageHeight: Float,+ boxWidth: Int,+ boxHeight: Int,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+ drawImage: Boolean = true,+ content: @Composable ImageScope.() -> Unit+) {+ val density = LocalDensity.current++ // Dimensions of canvas that will draw this Bitmap+ val canvasWidthInDp: Dp+ val canvasHeightInDp: Dp++ with(density) {+ canvasWidthInDp = imageWidth.coerceAtMost(boxWidth.toFloat()).toDp()+ canvasHeightInDp = imageHeight.coerceAtMost(boxHeight.toFloat()).toDp()+ }++ // Send rectangle of Bitmap drawn to Canvas as bitmapRect, content scale modes like+ // crop might crop image from center so Rect can be such as IntRect(250,250,500,500)++ // canvasWidthInDp, and canvasHeightInDp are Canvas dimensions coerced to Box size+ // that covers Canvas+ val imageScopeImpl = ImageScopeImpl(+ density = density,+ constraints = constraints,+ imageWidth = canvasWidthInDp,+ imageHeight = canvasHeightInDp,+ rect = bitmapRect+ )++ // width and height params for translating draw position if scaled Image dimensions are+ // bigger than Canvas dimensions+ if (drawImage) {+ ImageImpl(+ modifier = Modifier.size(canvasWidthInDp, canvasHeightInDp),+ imageBitmap = imageBitmap,+ alpha = alpha,+ width = imageWidth.toInt(),+ height = imageHeight.toInt(),+ colorFilter = colorFilter,+ filterQuality = filterQuality+ )+ }++ imageScopeImpl.content()+}++@Composable+private fun ImageImpl(+ modifier: Modifier,+ imageBitmap: ImageBitmap,+ width: Int,+ height: Int,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+) {+ val bitmapWidth = imageBitmap.width+ val bitmapHeight = imageBitmap.height++ Canvas(modifier = modifier.clipToBounds()) {++ val canvasWidth = size.width.toInt()+ val canvasHeight = size.height.toInt()++ // Translate to left or down when Image size is bigger than this canvas.+ // ImageSize is bigger when scale modes like Crop is used which enlarges image+ // For instance 1000x1000 image can be 1000x2000 for a Canvas with 1000x1000+ // so top is translated -500 to draw center of ImageBitmap+ translate(+ top = (-height + canvasHeight) / 2f,+ left = (-width + canvasWidth) / 2f,++ ) {+ drawImage(+ imageBitmap,+ srcSize = IntSize(bitmapWidth, bitmapHeight),+ dstSize = IntSize(width, height),+ alpha = alpha,+ colorFilter = colorFilter,+ filterQuality = filterQuality+ )+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/AspectRatios.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/AspectRatios.ktnew file mode 100644index 0000000..9e13589--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/AspectRatios.kt@@ -0,0 +1,72 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.createRectShape++/**+ * Aspect ratio list with pre-defined aspect ratios+ */+val aspectRatios = listOf(+ CropAspectRatio(+ title = "9:16",+ shape = createRectShape(AspectRatio(9 / 16f)),+ aspectRatio = AspectRatio(9 / 16f)+ ),+ CropAspectRatio(+ title = "2:3",+ shape = createRectShape(AspectRatio(2 / 3f)),+ aspectRatio = AspectRatio(2 / 3f)+ ),+ CropAspectRatio(+ title = "Original",+ shape = createRectShape(AspectRatio.Original),+ aspectRatio = AspectRatio.Original+ ),+ CropAspectRatio(+ title = "1:1",+ shape = createRectShape(AspectRatio(1 / 1f)),+ aspectRatio = AspectRatio(1 / 1f)+ ),+ CropAspectRatio(+ title = "16:9",+ shape = createRectShape(AspectRatio(16 / 9f)),+ aspectRatio = AspectRatio(16 / 9f)+ ),+ CropAspectRatio(+ title = "1.91:1",+ shape = createRectShape(AspectRatio(1.91f / 1f)),+ aspectRatio = AspectRatio(1.91f / 1f)+ ),+ CropAspectRatio(+ title = "3:2",+ shape = createRectShape(AspectRatio(3 / 2f)),+ aspectRatio = AspectRatio(3 / 2f)+ ),+ CropAspectRatio(+ title = "3:4",+ shape = createRectShape(AspectRatio(3 / 4f)),+ aspectRatio = AspectRatio(3 / 4f)+ ),+ CropAspectRatio(+ title = "3:5",+ shape = createRectShape(AspectRatio(3 / 5f)),+ aspectRatio = AspectRatio(3 / 5f)+ )+)\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropAspectRatio.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropAspectRatio.ktnew file mode 100644index 0000000..01a3a9d--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropAspectRatio.kt@@ -0,0 +1,45 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++import androidx.compose.runtime.Immutable+import androidx.compose.ui.graphics.Shape++/**+ * Model for drawing title with shape for crop selection menu. Aspect ratio is used+ * for setting overlay in state and UI+ */+@Immutable+data class CropAspectRatio(+ val title: String,+ val shape: Shape,+ val aspectRatio: AspectRatio = AspectRatio.Original,+ val icons: List<Int> = listOf()+)++/**+ * Value class for containing aspect ratio+ * and [AspectRatio.Original] for comparing+ */+@Immutable+data class AspectRatio(val value: Float) {+ companion object {+ val Original = AspectRatio(-1f)+ }+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropData.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropData.ktnew file mode 100644index 0000000..a51cf2c--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropData.kt@@ -0,0 +1,39 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++import androidx.compose.runtime.Immutable+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+++/**+ * Class that contains information about+ * current zoom, pan and rotation, and rectangle of zoomed and panned area for cropping [cropRect],+ * and area of overlay as[overlayRect]+ *+ */+@Immutable+data class CropData(+ val zoom: Float = 1f,+ val pan: Offset = Offset.Zero,+ val rotation: Float = 0f,+ val overlayRect: Rect,+ val cropRect: Rect+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutline.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutline.ktnew file mode 100644index 0000000..da8cdf4--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutline.kt@@ -0,0 +1,152 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.CutCornerShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Immutable+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.RectangleShape+import androidx.compose.ui.graphics.Shape+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util.createPolygonShape++/**+ * Common ancestor for list of shapes, paths or images to crop inside [CropOutlineContainer]+ */+interface CropOutline {+ val id: Int+ val title: String+}++/**+ * Crop outline that contains a [Shape] like [RectangleShape] to draw frame for cropping+ */+interface CropShape : CropOutline {+ val shape: Shape+}++/**+ * Crop outline that contains a [Path] to draw frame for cropping+ */+interface CropPath : CropOutline {+ val path: Path+}++/**+ * Crop outline that contains a [ImageBitmap] to draw frame for cropping. And blend modes+ * to draw+ */+interface CropImageMask : CropOutline {+ val image: ImageBitmap+}++/**+ * Wrapper class that implements [CropOutline] and is a shape+ * wrapper that contains [RectangleShape]+ */+@Immutable+data class RectCropShape(+ override val id: Int,+ override val title: String,+) : CropShape {+ override val shape: Shape = RectangleShape+}++/**+ * Wrapper class that implements [CropOutline] and is a shape+ * wrapper that contains [RoundedCornerShape]+ */+@Immutable+data class RoundedCornerCropShape(+ override val id: Int,+ override val title: String,+ val cornerRadius: CornerRadiusProperties = CornerRadiusProperties(),+ override val shape: RoundedCornerShape = RoundedCornerShape(+ topStartPercent = cornerRadius.topStartPercent,+ topEndPercent = cornerRadius.topEndPercent,+ bottomEndPercent = cornerRadius.bottomEndPercent,+ bottomStartPercent = cornerRadius.bottomStartPercent+ )+) : CropShape++/**+ * Wrapper class that implements [CropOutline] and is a shape+ * wrapper that contains [CutCornerShape]+ */+@Immutable+data class CutCornerCropShape(+ override val id: Int,+ override val title: String,+ val cornerRadius: CornerRadiusProperties = CornerRadiusProperties(),+ override val shape: CutCornerShape = CutCornerShape(+ topStartPercent = cornerRadius.topStartPercent,+ topEndPercent = cornerRadius.topEndPercent,+ bottomEndPercent = cornerRadius.bottomEndPercent,+ bottomStartPercent = cornerRadius.bottomStartPercent+ )+) : CropShape++/**+ * Wrapper class that implements [CropOutline] and is a shape+ * wrapper that contains [CircleShape]+ */+@Immutable+data class OvalCropShape(+ override val id: Int,+ override val title: String,+ val ovalProperties: OvalProperties = OvalProperties(),+ override val shape: Shape = CircleShape+) : CropShape+++/**+ * Wrapper class that implements [CropOutline] and is a shape+ * wrapper that contains [CircleShape]+ */+@Immutable+data class PolygonCropShape(+ override val id: Int,+ override val title: String,+ val polygonProperties: PolygonProperties = PolygonProperties(),+ override val shape: Shape = createPolygonShape(polygonProperties.sides, polygonProperties.angle)+) : CropShape++/**+ * Wrapper class that implements [CropOutline] and is a [Path] wrapper to crop using drawable+ * files converted fom svg or Vector Drawable to [Path]+ */+@Immutable+data class CustomPathOutline(+ override val id: Int,+ override val title: String,+ override val path: Path+) : CropPath++/**+ * Wrapper class that implements [CropOutline] and is a [ImageBitmap] wrapper to crop+ * using a reference png and blend modes to crop+ */+@Immutable+data class ImageMaskOutline(+ override val id: Int,+ override val title: String,+ override val image: ImageBitmap,+) : CropImageMaskdiff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineContainer.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineContainer.ktnew file mode 100644index 0000000..74f73fc--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineContainer.kt@@ -0,0 +1,88 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++/**+ * Interface for containing multiple [CropOutline]s, currently selected item and index+ * for displaying on settings UI+ */+interface CropOutlineContainer<O : CropOutline> {+ var selectedIndex: Int+ val outlines: List<O>+ val selectedItem: O+ get() = outlines[selectedIndex]+ val size: Int+ get() = outlines.size+}++/**+ * Container for [RectCropShape]+ */+data class RectOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<RectCropShape>+) : CropOutlineContainer<RectCropShape>++/**+ * Container for [RoundedCornerCropShape]s+ */+data class RoundedRectOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<RoundedCornerCropShape>+) : CropOutlineContainer<RoundedCornerCropShape>++/**+ * Container for [CutCornerCropShape]s+ */+data class CutCornerRectOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<CutCornerCropShape>+) : CropOutlineContainer<CutCornerCropShape>++/**+ * Container for [OvalCropShape]s+ */+data class OvalOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<OvalCropShape>+) : CropOutlineContainer<OvalCropShape>++/**+ * Container for [PolygonCropShape]s+ */+data class PolygonOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<PolygonCropShape>+) : CropOutlineContainer<PolygonCropShape>++/**+ * Container for [CustomPathOutline]s+ */+data class CustomOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<CustomPathOutline>+) : CropOutlineContainer<CustomPathOutline>++/**+ * Container for [ImageMaskOutline]s+ */+data class ImageMaskOutlineContainer(+ override var selectedIndex: Int = 0,+ override val outlines: List<ImageMaskOutline>+) : CropOutlineContainer<ImageMaskOutline>diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineProperties.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineProperties.ktnew file mode 100644index 0000000..e6e17d4--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/CropOutlineProperties.kt@@ -0,0 +1,44 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++import androidx.compose.runtime.Immutable+import androidx.compose.ui.geometry.Offset++@Immutable+data class CornerRadiusProperties(+ val topStartPercent: Int = 20,+ val topEndPercent: Int = 20,+ val bottomStartPercent: Int = 20,+ val bottomEndPercent: Int = 20+)++@Immutable+data class PolygonProperties(+ val sides: Int = 6,+ val angle: Float = 0f,+ val offset: Offset = Offset.Zero+)++@Immutable+data class OvalProperties(+ val startAngle: Float = 0f,+ val sweepAngle: Float = 360f,+ val offset: Offset = Offset.Zero+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/OutlineType.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/OutlineType.ktnew file mode 100644index 0000000..fb66fb7--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/model/OutlineType.kt@@ -0,0 +1,23 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model++enum class OutlineType {+ Rect, RoundedRect, CutCorner, Oval, Polygon, Custom, ImageMask+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropDefaults.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropDefaults.ktnew file mode 100644index 0000000..d12338a--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropDefaults.kt@@ -0,0 +1,159 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings++import androidx.compose.runtime.Immutable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.ImageCropper+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.crop+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropOutline+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.OutlineType+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.aspectRatios+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.CropState++/**+ * Contains the default values used by [ImageCropper]+ */+object CropDefaults {++ /**+ * Properties effect crop behavior that should be passed to [CropState]+ */+ fun properties(+ cropType: CropType = CropType.Dynamic,+ handleSize: Float = 60f,+ middleHandleSize: Float = 24f,+ maxZoom: Float = 10f,+ contentScale: ContentScale = ContentScale.Fit,+ cropOutlineProperty: CropOutlineProperty,+ aspectRatio: AspectRatio = aspectRatios[2].aspectRatio,+ overlayRatio: Float = .9f,+ pannable: Boolean = true,+ fling: Boolean = false,+ zoomable: Boolean = true,+ rotatable: Boolean = false,+ minDimension: IntSize? = null,+ fixedAspectRatio: Boolean = false,+ ): CropProperties {+ return CropProperties(+ cropType = cropType,+ handleSize = handleSize,+ middleHandleSize = middleHandleSize,+ contentScale = contentScale,+ cropOutlineProperty = cropOutlineProperty,+ maxZoom = maxZoom,+ aspectRatio = aspectRatio,+ overlayRatio = overlayRatio,+ pannable = pannable,+ fling = fling,+ zoomable = zoomable,+ rotatable = rotatable,+ minDimension = minDimension,+ fixedAspectRatio = fixedAspectRatio,+ )+ }++ /**+ * Style is cosmetic changes that don't effect how [CropState] behaves because of that+ * none of these properties are passed to [CropState]+ */+ fun style(+ drawOverlay: Boolean = true,+ drawGrid: Boolean = true,+ strokeWidth: Dp = 1.dp,+ overlayColor: Color = DefaultOverlayColor,+ handleColor: Color = DefaultHandleColor,+ backgroundColor: Color = DefaultBackgroundColor+ ): CropStyle {+ return CropStyle(+ drawOverlay = drawOverlay,+ drawGrid = drawGrid,+ strokeWidth = strokeWidth,+ overlayColor = overlayColor,+ handleColor = handleColor,+ backgroundColor = backgroundColor+ )+ }+}++/**+ * Data class for selecting cropper properties. Fields of this class control inner work+ * of [CropState] while some such as [cropType], [aspectRatio], [handleSize]+ * is shared between ui and state.+ */+@Immutable+data class CropProperties(+ val cropType: CropType,+ val handleSize: Float,+ val middleHandleSize: Float,+ val contentScale: ContentScale,+ val cropOutlineProperty: CropOutlineProperty,+ val aspectRatio: AspectRatio,+ val overlayRatio: Float,+ val pannable: Boolean,+ val fling: Boolean,+ val rotatable: Boolean,+ val zoomable: Boolean,+ val maxZoom: Float,+ val minDimension: IntSize? = null,+ val fixedAspectRatio: Boolean = false,+)++/**+ * Data class for cropper styling only. None of the properties of this class is used+ * by [CropState] or [Modifier.crop]+ */+@Immutable+data class CropStyle(+ val drawOverlay: Boolean,+ val drawGrid: Boolean,+ val strokeWidth: Dp,+ val overlayColor: Color,+ val handleColor: Color,+ val backgroundColor: Color,+ val cropTheme: CropTheme = CropTheme.Dark+)++/**+ * Property for passing [CropOutline] between settings UI to [ImageCropper]+ */+@Immutable+data class CropOutlineProperty(+ val outlineType: OutlineType,+ val cropOutline: CropOutline+)++/**+ * Light, Dark or system controlled theme+ */+enum class CropTheme {+ Light,+ Dark,+ System+}++private val DefaultBackgroundColor = Color.Black.copy(0.55f)+private val DefaultOverlayColor = Color.Gray+private val DefaultHandleColor = Color.White\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropType.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropType.ktnew file mode 100644index 0000000..4e3e0f6--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/CropType.kt@@ -0,0 +1,29 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings++/**+ * Type of cropping operation+ *+ * If [CropType.Static] is selected overlay is stationary, image is movable.+ * If [CropType.Dynamic] is selected overlay can be moved, resized, image is stationary.+ */+enum class CropType {+ Static, Dynamic+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/Paths.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/Paths.ktnew file mode 100644index 0000000..12e3e22--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/settings/Paths.kt@@ -0,0 +1,52 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings++import androidx.compose.ui.graphics.Path++object Paths {+ val Favorite+ get() = Path().apply {+ moveTo(12.0f, 21.35f)+ relativeLineTo(-1.45f, -1.32f)+ cubicTo(5.4f, 15.36f, 2.0f, 12.28f, 2.0f, 8.5f)+ cubicTo(2.0f, 5.42f, 4.42f, 3.0f, 7.5f, 3.0f)+ relativeCubicTo(1.74f, 0.0f, 3.41f, 0.81f, 4.5f, 2.09f)+ cubicTo(13.09f, 3.81f, 14.76f, 3.0f, 16.5f, 3.0f)+ cubicTo(19.58f, 3.0f, 22.0f, 5.42f, 22.0f, 8.5f)+ relativeCubicTo(0.0f, 3.78f, -3.4f, 6.86f, -8.55f, 11.54f)+ lineTo(12.0f, 21.35f)+ close()+ }++ val Star = Path().apply {+ moveTo(12.0f, 17.27f)+ lineTo(18.18f, 21.0f)+ relativeLineTo(-1.64f, -7.03f)+ lineTo(22.0f, 9.24f)+ relativeLineTo(-7.19f, -0.61f)+ lineTo(12.0f, 2.0f)+ lineTo(9.19f, 8.63f)+ lineTo(2.0f, 9.24f)+ relativeLineTo(5.46f, 4.73f)+ lineTo(5.82f, 21.0f)+ close()+ }+}+diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropState.ktnew file mode 100644index 0000000..d9daa59--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropState.kt@@ -0,0 +1,101 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state++import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropProperties+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropType+++/**+ * Create and [remember] the [CropState] based on the currently appropriate transform+ * configuration to allow changing pan, zoom, and rotation.+ * @param imageSize size of the **Bitmap**+ * @param containerSize size of the Composable that draws **Bitmap**+ * @param cropProperties wrapper class that contains crop state properties such as+ * crop type,+ * @param keys are used to reset remember block to initial calculations. This can be used+ * when image, contentScale or any property changes which requires values to be reset to initial+ * values+ */+@Composable+fun rememberCropState(+ imageSize: IntSize,+ containerSize: IntSize,+ drawAreaSize: IntSize,+ cropProperties: CropProperties,+ isOverlayDraggable: Boolean = true,+ vararg keys: Any?+): CropState {++ // Properties of crop state+ val handleSize = cropProperties.handleSize+ val cropType = cropProperties.cropType+ val aspectRatio = cropProperties.aspectRatio+ val overlayRatio = cropProperties.overlayRatio+ val maxZoom = cropProperties.maxZoom+ val fling = cropProperties.fling+ val zoomable = cropProperties.zoomable+ val pannable = cropProperties.pannable+ val rotatable = cropProperties.rotatable+ val minDimension = cropProperties.minDimension+ val fixedAspectRatio = cropProperties.fixedAspectRatio++ return remember(*keys) {+ when (cropType) {+ CropType.Static -> {+ StaticCropState(+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ aspectRatio = aspectRatio,+ overlayRatio = overlayRatio,+ maxZoom = maxZoom,+ fling = fling,+ zoomable = zoomable,+ pannable = pannable,+ rotatable = rotatable,+ limitPan = false+ )+ }++ else -> {+ DynamicCropState(+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ aspectRatio = aspectRatio,+ overlayRatio = overlayRatio,+ maxZoom = maxZoom,+ handleSize = handleSize,+ fling = fling,+ zoomable = zoomable,+ pannable = pannable,+ rotatable = rotatable,+ limitPan = true,+ minDimension = minDimension,+ fixedAspectRatio = fixedAspectRatio,+ isOverlayDraggable = isOverlayDraggable,+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropStateImpl.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropStateImpl.ktnew file mode 100644index 0000000..4c15a95--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/CropStateImpl.kt@@ -0,0 +1,716 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.AnimationSpec+import androidx.compose.animation.core.VectorConverter+import androidx.compose.animation.core.tween+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.ImageCropSnapshot+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.TouchRegion+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.CropData+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropProperties+import kotlinx.coroutines.CompletableDeferred++val CropState.cropData: CropData+ get() = CropData(+ zoom = animatableZoom.targetValue,+ pan = Offset(animatablePanX.targetValue, animatablePanY.targetValue),+ rotation = animatableRotation.targetValue,+ overlayRect = overlayRect,+ cropRect = cropRect+ )++internal val CropState.cropSnapshot: ImageCropSnapshot?+ get() {+ if (+ imageSize.width <= 0 ||+ imageSize.height <= 0 ||+ containerSize.width <= 0 ||+ containerSize.height <= 0 ||+ drawAreaSize.width <= 0 ||+ drawAreaSize.height <= 0+ ) {+ return null+ }++ val imageWidth = imageSize.width.toFloat().coerceAtLeast(1f)+ val imageHeight = imageSize.height.toFloat().coerceAtLeast(1f)+ val overlayRect = targetOverlayRect+ val cropRect = snapshotCropRect()+ if (cropRect.width <= 0f || cropRect.height <= 0f ||+ overlayRect.width <= 0f || overlayRect.height <= 0f+ ) {+ return null+ }++ return ImageCropSnapshot(+ normalizedCropRect = Rect(+ left = (cropRect.left / imageWidth).coerceIn(0f, 1f),+ top = (cropRect.top / imageHeight).coerceIn(0f, 1f),+ right = (cropRect.right / imageWidth).coerceIn(0f, 1f),+ bottom = (cropRect.bottom / imageHeight).coerceIn(0f, 1f)+ ),+ normalizedOverlayCenter = Offset(+ x = overlayRect.center.x / containerSize.width.coerceAtLeast(1),+ y = overlayRect.center.y / containerSize.height.coerceAtLeast(1)+ ),+ overlaySizeFraction = overlaySizeFraction(+ overlayRect = overlayRect,+ containerSize = containerSize+ ),+ containerSize = containerSize,+ rotation = animatableRotation.targetValue+ )+ }++internal suspend fun CropState.restoreCropSnapshot(snapshot: ImageCropSnapshot) {+ val geometry = calculateRestoreGeometry(+ snapshot = snapshot,+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ overlayRatio = overlayRatio,+ minZoom = zoomMin,+ maxZoom = zoomMax+ ) ?: return++ snapOverlayRectTo(geometry.overlayRect)+ snapZoomTo(geometry.zoom)+ snapRotationTo(snapshot.rotation)+ snapPanXto(geometry.pan.x)+ snapPanYto(geometry.pan.y)+ drawAreaRect = updateImageDrawRectFromTransformation()+ resetTracking()+}++internal data class RestoredCropGeometry(+ val overlayRect: Rect,+ val zoom: Float,+ val pan: Offset+)++internal fun calculateRestoreGeometry(+ snapshot: ImageCropSnapshot,+ imageSize: IntSize,+ containerSize: IntSize,+ drawAreaSize: IntSize,+ overlayRatio: Float = 0.8f,+ minZoom: Float = 0.5f,+ maxZoom: Float = 20f+): RestoredCropGeometry? {+ if (+ imageSize.width <= 0 ||+ imageSize.height <= 0 ||+ containerSize.width <= 0 ||+ containerSize.height <= 0 ||+ drawAreaSize.width <= 0 ||+ drawAreaSize.height <= 0+ ) {+ return null+ }++ val normalizedCropRect = snapshot.normalizedCropRect.coerceToImageBounds()+ if (normalizedCropRect.width <= 0f || normalizedCropRect.height <= 0f) return null++ val containerWidth = containerSize.width.toFloat()+ val containerHeight = containerSize.height.toFloat()+ val cropWidthAtZoomOne = normalizedCropRect.width * drawAreaSize.width+ val cropHeightAtZoomOne = normalizedCropRect.height * drawAreaSize.height+ if (cropWidthAtZoomOne <= 0f || cropHeightAtZoomOne <= 0f) return null++ // Geometry is stored in image coordinates and restored relative to both viewport axes.+ // A numeric zoom value is tied to the old draw area, so carrying it across a rotation can+ // skew the frame even when undo and redo use the same snapshot.+ val viewportFillFraction = snapshot.overlaySizeFraction.coerceIn(0.1f, 1f)+ val zoom = minOf(+ containerWidth * viewportFillFraction / cropWidthAtZoomOne,+ containerHeight * viewportFillFraction / cropHeightAtZoomOne,+ maxZoom.coerceAtLeast(minZoom)+ ).coerceAtLeast(minZoom.coerceAtLeast(0.01f))+ if (!zoom.isFinite() || zoom <= 0f) return null++ val overlayWidth = cropWidthAtZoomOne * zoom+ val overlayHeight = cropHeightAtZoomOne * zoom+ val sourceContainerSize = snapshot.containerSize+ val keepAbsoluteCenter = sourceContainerSize.width == containerSize.width &&+ sourceContainerSize.height > 0+ val requestedCenter = if (keepAbsoluteCenter) {+ Offset(+ x = snapshot.normalizedOverlayCenter.x.coerceIn(0f, 1f) *+ sourceContainerSize.width,+ y = snapshot.normalizedOverlayCenter.y.coerceIn(0f, 1f) *+ sourceContainerSize.height+ )+ } else {+ Offset(+ x = snapshot.normalizedOverlayCenter.x.coerceIn(0f, 1f) * containerWidth,+ y = snapshot.normalizedOverlayCenter.y.coerceIn(0f, 1f) * containerHeight+ )+ }+ val overlayCenter = Offset(+ x = constrainedCenter(requestedCenter.x, overlayWidth, containerWidth),+ y = constrainedCenter(requestedCenter.y, overlayHeight, containerHeight)+ )+ val overlayRect = Rect(+ left = overlayCenter.x - overlayWidth / 2f,+ top = overlayCenter.y - overlayHeight / 2f,+ right = overlayCenter.x + overlayWidth / 2f,+ bottom = overlayCenter.y + overlayHeight / 2f+ )++ val drawWidth = drawAreaSize.width * zoom+ val drawHeight = drawAreaSize.height * zoom+ val drawLeft = overlayRect.left - normalizedCropRect.left * drawWidth+ val drawTop = overlayRect.top - normalizedCropRect.top * drawHeight++ return RestoredCropGeometry(+ overlayRect = overlayRect,+ zoom = zoom,+ pan = Offset(+ x = drawLeft - (containerWidth - drawWidth) / 2f,+ y = drawTop - (containerHeight - drawHeight) / 2f+ )+ )+}++private fun overlaySizeFraction(+ overlayRect: Rect,+ containerSize: IntSize+): Float {+ if (overlayRect.width <= 0f || overlayRect.height <= 0f) return 0.8f++ return maxOf(+ overlayRect.width / containerSize.width.coerceAtLeast(1),+ overlayRect.height / containerSize.height.coerceAtLeast(1)+ ).coerceIn(0.1f, 1f)+}++private fun constrainedCenter(+ requested: Float,+ size: Float,+ containerSize: Float+): Float {+ if (size >= containerSize) return containerSize / 2f+ return requested.coerceIn(size / 2f, containerSize - size / 2f)+}++private fun Rect.coerceToImageBounds(): Rect = Rect(+ left = left.coerceIn(0f, 1f),+ top = top.coerceIn(0f, 1f),+ right = right.coerceIn(0f, 1f),+ bottom = bottom.coerceIn(0f, 1f)+)++/**+ * Base class for crop operations. Any class that extends this class gets access to pan, zoom,+ * rotation values and animations via [TransformState], fling and moving back to bounds animations.+ * @param imageSize size of the **Bitmap**+ * @param containerSize size of the Composable that draws **Bitmap**. This is full size+ * of the Composable. [drawAreaSize] can be smaller than [containerSize] initially based+ * on content scale of Image composable+ * @param drawAreaSize size of the area that **Bitmap** is drawn+ * @param maxZoom maximum zoom value+ * @param fling when set to true dragging pointer builds up velocity. When last+ * pointer leaves Composable a movement invoked against friction till velocity drops below+ * to threshold+ * @param zoomable when set to true zoom is enabled+ * @param pannable when set to true pan is enabled+ * @param rotatable when set to true rotation is enabled+ * @param limitPan limits pan to bounds of parent Composable. Using this flag prevents creating+ * empty space on sides or edges of parent+ */+abstract class CropState internal constructor(+ imageSize: IntSize,+ containerSize: IntSize,+ drawAreaSize: IntSize,+ maxZoom: Float,+ internal var fling: Boolean = true,+ internal var aspectRatio: AspectRatio,+ internal var overlayRatio: Float,+ zoomable: Boolean = true,+ pannable: Boolean = true,+ rotatable: Boolean = false,+ limitPan: Boolean = false+) : TransformState(+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ initialZoom = 1f,+ initialRotation = 0f,+ maxZoom = maxZoom,+ zoomable = zoomable,+ pannable = pannable,+ rotatable = rotatable,+ limitPan = limitPan+) {++ private val animatableRectOverlay = Animatable(+ getOverlayFromAspectRatio(+ containerSize.width.toFloat(),+ containerSize.height.toFloat(),+ drawAreaSize.width.toFloat(),+ aspectRatio,+ overlayRatio+ ),+ Rect.VectorConverter+ )++ val overlayRect: Rect+ get() = animatableRectOverlay.value++ internal val targetOverlayRect: Rect+ get() = animatableRectOverlay.targetValue++ /**+ * Returns crop geometry from one coherent set of target values. During a configuration+ * change Compose can expose a new [CropState] while its rendered draw rectangle is still+ * catching up with the target pan and zoom. Saving [drawAreaRect] in that interval creates+ * a snapshot that neither undo nor redo can repair.+ */+ internal fun snapshotCropRect(): Rect = getCropRectangle(+ bitmapWidth = imageSize.width,+ bitmapHeight = imageSize.height,+ drawAreaRect = updateImageDrawRectFromTransformation(),+ overlayRect = animatableRectOverlay.targetValue+ )++ var cropRect: Rect = Rect.Zero+ get() = getCropRectangle(+ imageSize.width,+ imageSize.height,+ drawAreaRect,+ animatableRectOverlay.targetValue+ )+ private set+++ private var initialized: Boolean = false+ private var initializationStarted: Boolean = false+ private val initialization = CompletableDeferred<Unit>()++ /**+ * Region of touch inside, corners of or outside of overlay rectangle+ */+ var touchRegion by mutableStateOf(TouchRegion.None)++ internal suspend fun init() {+ if (initialized) return+ if (initializationStarted) {+ initialization.await()+ return+ }++ initializationStarted = true+ try {+ // When initial aspect ratio doesn't match drawable area+ // overlay gets updated so updates draw area as well+ animateTransformationToOverlayBounds(overlayRect, animate = false)+ initialized = true+ } finally {+ initialization.complete(Unit)+ }+ }++ internal suspend fun awaitInitialization() = initialization.await()++ /**+ * Update properties of [CropState] and animate to valid intervals if required+ */+ internal open suspend fun updateProperties(+ cropProperties: CropProperties,+ forceUpdate: Boolean = false,+ animate: Boolean = true+ ) {++ if (!initialized) return++ fling = cropProperties.fling+ pannable = cropProperties.pannable+ zoomable = cropProperties.zoomable+ rotatable = cropProperties.rotatable++ val maxZoom = cropProperties.maxZoom++ // Update overlay rectangle+ val aspectRatio = cropProperties.aspectRatio++ // Ratio of overlay to screen+ val overlayRatio = cropProperties.overlayRatio++ if (+ this.aspectRatio.value != aspectRatio.value ||+ maxZoom != zoomMax ||+ this.overlayRatio != overlayRatio ||+ forceUpdate+ ) {+ this.aspectRatio = aspectRatio+ this.overlayRatio = overlayRatio++ zoomMax = maxZoom+ animatableZoom.updateBounds(zoomMin, zoomMax)++ val currentZoom = if (zoom > zoomMax) zoomMax else zoom++ // Set new zoom+ snapZoomTo(currentZoom)++ // Calculate new region of image is drawn. It can be drawn left of 0 and right+ // of container width depending on transformation+ drawAreaRect = updateImageDrawRectFromTransformation()++ // Update overlay rectangle based on current draw area and new aspect ratio+ val targetOverlayRect = getOverlayFromAspectRatio(+ containerSize.width.toFloat(),+ containerSize.height.toFloat(),+ drawAreaSize.width.toFloat(),+ aspectRatio,+ overlayRatio+ )+ if (animate) {+ animateOverlayRectTo(targetOverlayRect)+ } else {+ snapOverlayRectTo(targetOverlayRect)+ }+ }++ // Animate zoom, pan, rotation to move draw area to cover overlay rect+ // inside draw area rect+ animateTransformationToOverlayBounds(overlayRect, animate = animate)+ }++ /**+ * Animate overlay rectangle to target value+ */+ internal suspend fun animateOverlayRectTo(+ rect: Rect,+ animationSpec: AnimationSpec<Rect> = tween(250)+ ) {+ animatableRectOverlay.animateTo(+ targetValue = rect,+ animationSpec = animationSpec+ )+ }++ /**+ * Snap overlay rectangle to target value+ */+ internal suspend fun snapOverlayRectTo(rect: Rect) {+ animatableRectOverlay.snapTo(rect)+ }++ /*+ Touch gestures+ */+ internal abstract suspend fun onDown(change: PointerInputChange)++ internal abstract suspend fun onMove(changes: List<PointerInputChange>)++ internal abstract suspend fun onUp(change: PointerInputChange)++ /*+ Transform gestures+ */+ internal abstract suspend fun onGesture(+ centroid: Offset,+ panChange: Offset,+ zoomChange: Float,+ rotationChange: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ )++ internal abstract suspend fun onGestureStart()++ internal abstract suspend fun onGestureEnd(onBoundsCalculated: () -> Unit)++ // Double Tap+ internal abstract suspend fun onDoubleTap(+ offset: Offset,+ zoom: Float = 1f,+ onAnimationEnd: () -> Unit+ )++ /**+ * Check if area that image is drawn covers [overlayRect]+ */+ internal fun isOverlayInImageDrawBounds(): Boolean {+ return drawAreaRect.left <= overlayRect.left &&+ drawAreaRect.top <= overlayRect.top &&+ drawAreaRect.right >= overlayRect.right &&+ drawAreaRect.bottom >= overlayRect.bottom+ }++ /**+ * Check if [rect] is inside container bounds+ */+ internal fun isRectInContainerBounds(rect: Rect): Boolean {+ return rect.left >= 0 &&+ rect.right <= containerSize.width &&+ rect.top >= 0 &&+ rect.bottom <= containerSize.height+ }++ /**+ * Update rectangle for area that image is drawn. This rect changes when zoom and+ * pan changes and position of image changes on screen as result of transformation.+ *+ * This function is called+ *+ * * when [onGesture] is called to update rect when zoom or pan changes+ * and if [fling] is true just after **fling** gesture starts with target+ * value in [StaticCropState].+ *+ * * when [updateProperties] is called in [CropState]+ *+ * * when [onUp] is called in [DynamicCropState] to match [overlayRect] that could be+ * changed and animated if it's out of [containerSize] bounds or its grow+ * bigger than previous size+ */+ internal fun updateImageDrawRectFromTransformation(): Rect {+ val containerWidth = containerSize.width+ val containerHeight = containerSize.height++ val originalDrawWidth = drawAreaSize.width+ val originalDrawHeight = drawAreaSize.height++ val panX = animatablePanX.targetValue+ val panY = animatablePanY.targetValue++ val left = (containerWidth - originalDrawWidth) / 2+ val top = (containerHeight - originalDrawHeight) / 2++ val zoom = animatableZoom.targetValue++ val newWidth = originalDrawWidth * zoom+ val newHeight = originalDrawHeight * zoom++ return Rect(+ offset = Offset(+ left - (newWidth - originalDrawWidth) / 2 + panX,+ top - (newHeight - originalDrawHeight) / 2 + panY,+ ),+ size = Size(newWidth, newHeight)+ )+ }++ /**+ * Resets to bounds with animation and resets tracking for fling animation.+ * Changes pan, zoom and rotation to valid bounds based on [drawAreaRect] and [overlayRect]+ */+ internal suspend fun animateTransformationToOverlayBounds(+ overlayRect: Rect,+ animate: Boolean,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) {+ // Keep current zoom+ // val zoom = zoom.coerceAtLeast(1f)++ // Calculate new pan based on overlay+ val newDrawAreaRect = calculateValidImageDrawRect(overlayRect, drawAreaRect)++ val newZoom =+ calculateNewZoom(oldRect = drawAreaRect, newRect = newDrawAreaRect, zoom = zoom)++ val leftChange = newDrawAreaRect.left - drawAreaRect.left+ val topChange = newDrawAreaRect.top - drawAreaRect.top++ val widthChange = newDrawAreaRect.width - drawAreaRect.width+ val heightChange = newDrawAreaRect.height - drawAreaRect.height++ val panXChange = leftChange + widthChange / 2+ val panYChange = topChange + heightChange / 2++ val newPanX = pan.x + panXChange+ val newPanY = pan.y + panYChange++ // Update draw area based on new pan and zoom values+ drawAreaRect = newDrawAreaRect++ if (animate) {+ resetWithAnimation(+ pan = Offset(newPanX, newPanY),+ zoom = newZoom,+ animationSpec = animationSpec+ )+ } else {+ snapPanXto(newPanX)+ snapPanYto(newPanY)+ snapZoomTo(newZoom)+ }++ resetTracking()+ }++ /**+ * If new overlay is bigger, when crop type is dynamic, we need to increase zoom at least+ * size of bigger dimension for image draw area([drawAreaRect]) to cover overlay([overlayRect])+ */+ private fun calculateNewZoom(oldRect: Rect, newRect: Rect, zoom: Float): Float {++ if (oldRect.size == Size.Zero || newRect.size == Size.Zero) return zoom++ val widthChange = (newRect.width / oldRect.width)+ .coerceAtLeast(1f)+ val heightChange = (newRect.height / oldRect.height)+ .coerceAtLeast(1f)++ return widthChange.coerceAtLeast(heightChange) * zoom+ }++ /**+ * Calculate valid position for image draw rectangle when pointer is up. Overlay rectangle+ * should fit inside draw image rectangle to have valid bounds when calculation is completed.+ *+ * @param rectOverlay rectangle of overlay that is used for cropping+ * @param rectDrawArea rectangle of image that is being drawn+ */+ private fun calculateValidImageDrawRect(rectOverlay: Rect, rectDrawArea: Rect): Rect {++ var width = rectDrawArea.width+ var height = rectDrawArea.height++ if (width < rectOverlay.width) {+ width = rectOverlay.width+ }++ if (height < rectOverlay.height) {+ height = rectOverlay.height+ }++ var rectImageArea = Rect(offset = rectDrawArea.topLeft, size = Size(width, height))++ if (rectImageArea.left > rectOverlay.left) {+ rectImageArea = rectImageArea.translate(rectOverlay.left - rectImageArea.left, 0f)+ }++ if (rectImageArea.right < rectOverlay.right) {+ rectImageArea = rectImageArea.translate(rectOverlay.right - rectImageArea.right, 0f)+ }++ if (rectImageArea.top > rectOverlay.top) {+ rectImageArea = rectImageArea.translate(0f, rectOverlay.top - rectImageArea.top)+ }++ if (rectImageArea.bottom < rectOverlay.bottom) {+ rectImageArea = rectImageArea.translate(0f, rectOverlay.bottom - rectImageArea.bottom)+ }++ return rectImageArea+ }++ /**+ * Create [Rect] to draw overlay based on selected aspect ratio+ */+ internal fun getOverlayFromAspectRatio(+ containerWidth: Float,+ containerHeight: Float,+ drawAreaWidth: Float,+ aspectRatio: AspectRatio,+ coefficient: Float+ ): Rect {++ if (aspectRatio == AspectRatio.Original) {+ val imageAspectRatio = imageSize.width.toFloat() / imageSize.height.toFloat()++ // Maximum width and height overlay rectangle can be measured with+ val overlayWidthMax = drawAreaWidth.coerceAtMost(containerWidth * coefficient)+ val overlayHeightMax =+ (overlayWidthMax / imageAspectRatio).coerceAtMost(containerHeight * coefficient)++ val offsetX = (containerWidth - overlayWidthMax) / 2f+ val offsetY = (containerHeight - overlayHeightMax) / 2f++ return Rect(+ offset = Offset(offsetX, offsetY),+ size = Size(overlayWidthMax, overlayHeightMax)+ )+ }++ val overlayWidthMax = containerWidth * coefficient+ val overlayHeightMax = containerHeight * coefficient++ val aspectRatioValue = aspectRatio.value++ var width = overlayWidthMax+ var height = overlayWidthMax / aspectRatioValue++ if (height > overlayHeightMax) {+ height = overlayHeightMax+ width = height * aspectRatioValue+ }++ val offsetX = (containerWidth - width) / 2f+ val offsetY = (containerHeight - height) / 2f++ return Rect(offset = Offset(offsetX, offsetY), size = Size(width, height))+ }++ /**+ * Get crop rectangle+ */+ private fun getCropRectangle(+ bitmapWidth: Int,+ bitmapHeight: Int,+ drawAreaRect: Rect,+ overlayRect: Rect+ ): Rect {++ if (drawAreaRect == Rect.Zero || overlayRect == Rect.Zero) return Rect(+ offset = Offset.Zero,+ Size(bitmapWidth.toFloat(), bitmapHeight.toFloat())+ )++ // Calculate latest image draw area based on overlay position+ // This is valid rectangle that contains crop area inside overlay+ val newRect = calculateValidImageDrawRect(overlayRect, drawAreaRect)++ val overlayWidth = overlayRect.width+ val overlayHeight = overlayRect.height++ val drawAreaWidth = newRect.width+ val drawAreaHeight = newRect.height++ val widthRatio = overlayWidth / drawAreaWidth+ val heightRatio = overlayHeight / drawAreaHeight++ val diffLeft = overlayRect.left - newRect.left+ val diffTop = overlayRect.top - newRect.top++ val croppedBitmapLeft = (diffLeft * (bitmapWidth / drawAreaWidth))+ val croppedBitmapTop = (diffTop * (bitmapHeight / drawAreaHeight))++ val croppedBitmapWidth = bitmapWidth * widthRatio+ val croppedBitmapHeight = bitmapHeight * heightRatio++ return Rect(+ offset = Offset(croppedBitmapLeft, croppedBitmapTop),+ size = Size(croppedBitmapWidth, croppedBitmapHeight)+ )+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/DynamicCropState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/DynamicCropState.ktnew file mode 100644index 0000000..5c024db--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/DynamicCropState.kt@@ -0,0 +1,842 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.TouchRegion+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.handlesTouched+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.settings.CropProperties+import kotlinx.coroutines.coroutineScope+import kotlin.math.roundToInt++/**+ * State for cropper with dynamic overlay. Overlay of this state can be moved or resized+ * using handles or touching inner position of overlay. When overlay overflow out of image bounds+ * or moves out of bounds it animates back to valid size and position+ *+ * @param handleSize size of the handle to control, move or scale dynamic overlay+ * @param imageSize size of the **Bitmap**+ * @param containerSize size of the Composable that draws **Bitmap**+ * @param maxZoom maximum zoom value+ * @param fling when set to true dragging pointer builds up velocity. When last+ * pointer leaves Composable a movement invoked against friction till velocity drops below+ * to threshold+ * @param zoomable when set to true zoom is enabled+ * @param pannable when set to true pan is enabled+ * @param rotatable when set to true rotation is enabled+ * @param limitPan limits pan to bounds of parent Composable. Using this flag prevents creating+ * @param minDimension minimum size of the overlay, if null defaults to handleSize * 2+ * @param fixedAspectRatio when set to true aspect ratio of overlay is fixed+ * empty space on sides or edges of parent+ */+class DynamicCropState internal constructor(+ private var handleSize: Float,+ imageSize: IntSize,+ containerSize: IntSize,+ drawAreaSize: IntSize,+ aspectRatio: AspectRatio,+ overlayRatio: Float,+ maxZoom: Float,+ fling: Boolean,+ zoomable: Boolean,+ pannable: Boolean,+ rotatable: Boolean,+ limitPan: Boolean,+ private val minDimension: IntSize?,+ private val fixedAspectRatio: Boolean,+ internal var isOverlayDraggable: Boolean,+) : CropState(+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ aspectRatio = aspectRatio,+ overlayRatio = overlayRatio,+ maxZoom = maxZoom,+ fling = fling,+ zoomable = zoomable,+ pannable = pannable,+ rotatable = rotatable,+ limitPan = limitPan+) {++ /**+ * Rectangle that covers bounds of Composable. This is a rectangle uses [containerSize] as+ * size and [Offset.Zero] as top left corner+ */+ private val rectBounds = Rect(+ offset = Offset.Zero,+ size = Size(containerSize.width.toFloat(), containerSize.height.toFloat())+ )++ // This rectangle is needed to set bounds set at first touch position while+ // moving to constraint current bounds to temp one from first down+ // When pointer is up+ private var rectTemp = Rect.Zero++ // Touch position for edge of the rectangle, used for not jumping to edge of rectangle+ // when user moves a handle. We set positionActual as position of selected handle+ // and using this distance as offset to not have a jump from touch position+ private var distanceToEdgeFromTouch = Offset.Zero++ private var doubleTapped = false++ // Check if transform gesture has been invoked+ // inside overlay but with multiple pointers to zoom+ private var gestureInvoked = false++ internal var pressedHandle by mutableStateOf(TouchRegion.None)+ private set++ override suspend fun updateProperties(+ cropProperties: CropProperties,+ forceUpdate: Boolean,+ animate: Boolean+ ) {+ handleSize = cropProperties.handleSize+ super.updateProperties(cropProperties, forceUpdate, animate)+ }++ override suspend fun onDown(change: PointerInputChange) {++ rectTemp = overlayRect.copy()++ val position = change.position+ val touchPositionScreenX = position.x+ val touchPositionScreenY = position.y++ val touchPositionOnScreen = Offset(touchPositionScreenX, touchPositionScreenY)++ // Get whether user touched outside, handles of rectangle or inner region or overlay+ // rectangle. Depending on where is touched we can move or scale overlay+ touchRegion = getTouchRegion(+ position = touchPositionOnScreen,+ rect = overlayRect,+ threshold = handleSize * 1.5f+ ).let {+ if (it == TouchRegion.Inside && !isOverlayDraggable) TouchRegion.None else it+ }+ pressedHandle = if (handlesTouched(touchRegion)) touchRegion else TouchRegion.None++ // This is the difference between touch position and edge+ // This is required for not moving edge of draw rect to touch position on move+ distanceToEdgeFromTouch =+ getDistanceToEdgeFromTouch(touchRegion, rectTemp, touchPositionOnScreen)+ }++ override suspend fun onMove(changes: List<PointerInputChange>) {++ if (changes.isEmpty()) {+ pressedHandle = TouchRegion.None+ touchRegion = TouchRegion.None+ return+ }++ gestureInvoked = changes.size > 1 && (touchRegion == TouchRegion.Inside)++ // If overlay is touched and pointer size is one update+ // or pointer size is bigger than one but touched any handles update+ if (touchRegion != TouchRegion.None && changes.size == 1 && !gestureInvoked) {++ val change = changes.first()++ // Default min dimension is handle size * 5+ val doubleHandleSize = handleSize * 5+ val defaultMinDimension =+ IntSize(doubleHandleSize.roundToInt(), doubleHandleSize.roundToInt())++ // update overlay rectangle based on where its touched and touch position to corners+ // This function moves and/or scales overlay rectangle+ val newRect = updateOverlayRect(+ distanceToEdgeFromTouch = distanceToEdgeFromTouch,+ touchRegion = touchRegion,+ minDimension = minDimension ?: defaultMinDimension,+ rectTemp = rectTemp,+ overlayRect = overlayRect,+ change = change,+ aspectRatio = getAspectRatio(),+ fixedAspectRatio = fixedAspectRatio,+ )++ snapOverlayRectTo(newRect)+ }+ }++ private fun getAspectRatio(): Float {+ return if (aspectRatio == AspectRatio.Original) {+ imageSize.width / imageSize.height.toFloat()+ } else {+ aspectRatio.value+ }+ }++ override suspend fun onUp(change: PointerInputChange) = coroutineScope {+ pressedHandle = TouchRegion.None++ if (touchRegion != TouchRegion.None) {++ val isInContainerBounds = isRectInContainerBounds(overlayRect)+ if (!isInContainerBounds) {++ // Calculate new overlay since it's out of Container bounds+ rectTemp = calculateOverlayRectInBounds(rectBounds, overlayRect)++ // Animate overlay to new bounds inside container+ animateOverlayRectTo(rectTemp)+ }++ // Update and animate pan, zoom and image draw area after overlay position is updated+ animateTransformationToOverlayBounds(overlayRect, true)++ // Update image draw area after animating pan, zoom or rotation is completed+ drawAreaRect = updateImageDrawRectFromTransformation()++ touchRegion = TouchRegion.None+ }++ gestureInvoked = false+ }++ override suspend fun onGesture(+ centroid: Offset,+ panChange: Offset,+ zoomChange: Float,+ rotationChange: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ ) {++ if (touchRegion == TouchRegion.None || gestureInvoked) {+ doubleTapped = false++ val newPan = if (gestureInvoked) Offset.Zero else panChange++ updateTransformState(+ centroid = centroid,+ zoomChange = zoomChange,+ panChange = newPan,+ rotationChange = rotationChange+ )++ // Update image draw rectangle based on pan, zoom or rotation change+ drawAreaRect = updateImageDrawRectFromTransformation()++ // Fling Gesture+ if (pannable && fling) {+ if (changes.size == 1) {+ addPosition(mainPointer.uptimeMillis, mainPointer.position)+ }+ }+ }+ }++ override suspend fun onGestureStart() = Unit++ override suspend fun onGestureEnd(onBoundsCalculated: () -> Unit) {++ if (touchRegion == TouchRegion.None || gestureInvoked) {++ // Gesture end might be called after second tap and we don't want to fling+ // or animate back to valid bounds when doubled tapped+ if (!doubleTapped) {++ if (pannable && fling && !gestureInvoked && zoom > 1) {+ fling {+ // We get target value on start instead of updating bounds after+ // gesture has finished+ drawAreaRect = updateImageDrawRectFromTransformation()+ onBoundsCalculated()+ }+ } else {+ onBoundsCalculated()+ }++ animateTransformationToOverlayBounds(overlayRect, animate = true)+ }+ }+ }++ override suspend fun onDoubleTap(+ offset: Offset,+ zoom: Float,+ onAnimationEnd: () -> Unit+ ) {+ doubleTapped = true++ if (fling) {+ resetTracking()+ }+ resetWithAnimation(pan = pan, zoom = zoom, rotation = rotation)++ // We get target value on start instead of updating bounds after+ // gesture has finished+ drawAreaRect = updateImageDrawRectFromTransformation()+++ if (!isOverlayInImageDrawBounds()) {+ // Moves rectangle to bounds inside drawArea Rect while keeping aspect ratio+ // of current overlay rect+ animateOverlayRectTo(+ getOverlayFromAspectRatio(+ containerSize.width.toFloat(),+ containerSize.height.toFloat(),+ drawAreaSize.width.toFloat(),+ aspectRatio,+ overlayRatio+ )+ )++ animateTransformationToOverlayBounds(overlayRect, false)+ }+ onAnimationEnd()+ }+++// //TODO Change pan when zoom is bigger than 1f and touchRegion is inside overlay rect+// private suspend fun moveOverlayToBounds(change: PointerInputChange, newRect: Rect) {+// val bounds = drawAreaRect+//+// val positionChange = change.positionChangeIgnoreConsumed()+//+// // When zoom is bigger than 100% and dynamic overlay is not at any edge of+// // image we can pan in the same direction motion goes towards when touch region+// // of rectangle is not one of the handles but region inside+// val isPanRequired = touchRegion == TouchRegion.Inside && zoom > 1f+//+// // Overlay moving right+// if (isPanRequired && newRect.right < bounds.right) {+// println("Moving right newRect $newRect, bounds: $bounds")+// snapOverlayRectTo(newRect.translate(-positionChange.x, 0f))+// snapPanXto(pan.x - positionChange.x * zoom)+// // Overlay moving left+// } else if (isPanRequired && pan.x < bounds.left && newRect.left <= 0f) {+// snapOverlayRectTo(newRect.translate(-positionChange.x, 0f))+// snapPanXto(pan.x - positionChange.x * zoom)+// } else if (isPanRequired && pan.y < bounds.top && newRect.top <= 0f) {+// // Overlay moving top+// snapOverlayRectTo(newRect.translate(0f, -positionChange.y))+// snapPanYto(pan.y - positionChange.y * zoom)+// } else if (isPanRequired && -pan.y < bounds.bottom && newRect.bottom >= containerSize.height) {+// // Overlay moving bottom+// snapOverlayRectTo(newRect.translate(0f, -positionChange.y))+// snapPanYto(pan.y - positionChange.y * zoom)+// } else {+// snapOverlayRectTo(newRect)+// }+// if (touchRegion != TouchRegion.None) {+// change.consume()+// }+// }++ /**+ * When pointer is up calculate valid position and size overlay can be updated to inside+ * a virtual rect between `topLeft = (0,0)` to `bottomRight=(containerWidth, containerHeight)`+ *+ * [overlayRect] might be shrunk or moved up/down/left/right to container bounds when+ * it's out of Composable region+ */+ private fun calculateOverlayRectInBounds(rectBounds: Rect, rectCurrent: Rect): Rect {++ var width = rectCurrent.width+ var height = rectCurrent.height++ if (width > rectBounds.width) {+ width = rectBounds.width+ }++ if (height > rectBounds.height) {+ height = rectBounds.height+ }++ var rect = Rect(offset = rectCurrent.topLeft, size = Size(width, height))++ if (rect.left < rectBounds.left) {+ rect = rect.translate(rectBounds.left - rect.left, 0f)+ }++ if (rect.top < rectBounds.top) {+ rect = rect.translate(0f, rectBounds.top - rect.top)+ }++ if (rect.right > rectBounds.right) {+ rect = rect.translate(rectBounds.right - rect.right, 0f)+ }++ if (rect.bottom > rectBounds.bottom) {+ rect = rect.translate(0f, rectBounds.bottom - rect.bottom)+ }++ return rect+ }++ private fun updateOverlayRect(+ distanceToEdgeFromTouch: Offset,+ touchRegion: TouchRegion,+ minDimension: IntSize,+ rectTemp: Rect,+ overlayRect: Rect,+ change: PointerInputChange,+ aspectRatio: Float,+ fixedAspectRatio: Boolean,+ ): Rect {++ val position = change.position+ val screenX = position.x + distanceToEdgeFromTouch.x+ val screenY = position.y + distanceToEdgeFromTouch.y++ val minW = minDimension.width.toFloat()+ val minH = minDimension.height.toFloat()++ val bounds = rectBounds++ fun clampNonFixed(left: Float, top: Float, right: Float, bottom: Float): Rect {+ val l = left.coerceIn(bounds.left, bounds.right - minW)+ val t = top.coerceIn(bounds.top, bounds.bottom - minH)+ val r = right.coerceIn(l + minW, bounds.right)+ val b = bottom.coerceIn(t + minH, bounds.bottom)+ return Rect(l, t, r, b)+ }++ fun anchoredCornerTopLeft(anchorR: Float, anchorB: Float, candidateLeft: Float): Rect {+ var width = (anchorR - candidateLeft).coerceAtLeast(minW)+ val maxWidth = (anchorR - bounds.left).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val maxHeight = (anchorB - bounds.top).coerceAtLeast(minH)+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val left = anchorR - width+ val top = anchorB - height+ return Rect(+ left.coerceAtLeast(bounds.left),+ top.coerceAtLeast(bounds.top),+ anchorR.coerceAtMost(bounds.right),+ anchorB.coerceAtMost(bounds.bottom)+ )+ }++ fun anchoredCornerBottomLeft(anchorR: Float, anchorT: Float, candidateLeft: Float): Rect {+ var width = (anchorR - candidateLeft).coerceAtLeast(minW)+ val maxWidth = (anchorR - bounds.left).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val maxHeight = (bounds.bottom - anchorT).coerceAtLeast(minH)+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val left = anchorR - width+ val bottom = anchorT + height+ return Rect(+ left.coerceAtLeast(bounds.left),+ anchorT.coerceAtLeast(bounds.top),+ anchorR.coerceAtMost(bounds.right),+ bottom.coerceAtMost(bounds.bottom)+ )+ }++ fun anchoredCornerTopRight(anchorL: Float, anchorB: Float, candidateRight: Float): Rect {+ var width = (candidateRight - anchorL).coerceAtLeast(minW)+ val maxWidth = (bounds.right - anchorL).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val maxHeight = (anchorB - bounds.top).coerceAtLeast(minH)+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val right = anchorL + width+ val top = anchorB - height+ return Rect(+ anchorL.coerceAtLeast(bounds.left),+ top.coerceAtLeast(bounds.top),+ right.coerceAtMost(bounds.right),+ anchorB.coerceAtMost(bounds.bottom)+ )+ }++ fun anchoredCornerBottomRight(anchorL: Float, anchorT: Float, candidateRight: Float): Rect {+ var width = (candidateRight - anchorL).coerceAtLeast(minW)+ val maxWidth = (bounds.right - anchorL).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val maxHeight = (bounds.bottom - anchorT).coerceAtLeast(minH)+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val right = anchorL + width+ val bottom = anchorT + height+ return Rect(+ anchorL.coerceAtLeast(bounds.left),+ anchorT.coerceAtLeast(bounds.top),+ right.coerceAtMost(bounds.right),+ bottom.coerceAtMost(bounds.bottom)+ )+ }++ fun centerTop(anchorB: Float, candidateTop: Float): Rect {+ var height = (anchorB - candidateTop).coerceAtLeast(minH)+ val maxHeight = (anchorB - bounds.top).coerceAtLeast(minH)+ height = height.coerceAtMost(maxHeight)+ var width = height * aspectRatio+ val halfMaxWidth =+ minOf(bounds.right - rectTemp.center.x, rectTemp.center.x - bounds.left)+ val maxWidth = halfMaxWidth * 2f+ if (width > maxWidth) {+ width = maxWidth+ height = (width / aspectRatio).coerceAtLeast(minH)+ }+ val left = rectTemp.center.x - width / 2f+ val right = rectTemp.center.x + width / 2f+ val top = anchorB - height+ return Rect(+ left.coerceAtLeast(bounds.left),+ top.coerceAtLeast(bounds.top),+ right.coerceAtMost(bounds.right),+ anchorB.coerceAtMost(bounds.bottom)+ )+ }++ fun centerBottom(anchorT: Float, candidateBottom: Float): Rect {+ var height = (candidateBottom - anchorT).coerceAtLeast(minH)+ val maxHeight = (bounds.bottom - anchorT).coerceAtLeast(minH)+ height = height.coerceAtMost(maxHeight)+ var width = height * aspectRatio+ val halfMaxWidth =+ minOf(bounds.right - rectTemp.center.x, rectTemp.center.x - bounds.left)+ val maxWidth = halfMaxWidth * 2f+ if (width > maxWidth) {+ width = maxWidth+ height = (width / aspectRatio).coerceAtLeast(minH)+ }+ val left = rectTemp.center.x - width / 2f+ val right = rectTemp.center.x + width / 2f+ val bottom = anchorT + height+ return Rect(+ left.coerceAtLeast(bounds.left),+ anchorT.coerceAtLeast(bounds.top),+ right.coerceAtMost(bounds.right),+ bottom.coerceAtMost(bounds.bottom)+ )+ }++ fun centerLeft(anchorR: Float, candidateLeft: Float): Rect {+ var width = (anchorR - candidateLeft).coerceAtLeast(minW)+ val maxWidth = (anchorR - bounds.left).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val halfMaxHeight =+ minOf(rectTemp.center.y - bounds.top, bounds.bottom - rectTemp.center.y)+ val maxHeight = halfMaxHeight * 2f+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val left = anchorR - width+ val top = rectTemp.center.y - height / 2f+ val bottom = rectTemp.center.y + height / 2f+ return Rect(+ left.coerceAtLeast(bounds.left),+ top.coerceAtLeast(bounds.top),+ anchorR.coerceAtMost(bounds.right),+ bottom.coerceAtMost(bounds.bottom)+ )+ }++ fun centerRight(anchorL: Float, candidateRight: Float): Rect {+ var width = (candidateRight - anchorL).coerceAtLeast(minW)+ val maxWidth = (bounds.right - anchorL).coerceAtLeast(minW)+ width = width.coerceAtMost(maxWidth)+ var height = width / aspectRatio+ val halfMaxHeight =+ minOf(rectTemp.center.y - bounds.top, bounds.bottom - rectTemp.center.y)+ val maxHeight = halfMaxHeight * 2f+ if (height > maxHeight) {+ height = maxHeight+ width = (height * aspectRatio).coerceAtLeast(minW)+ }+ val right = anchorL + width+ val top = rectTemp.center.y - height / 2f+ val bottom = rectTemp.center.y + height / 2f+ return Rect(+ anchorL.coerceAtLeast(bounds.left),+ top.coerceAtLeast(bounds.top),+ right.coerceAtMost(bounds.right),+ bottom.coerceAtMost(bounds.bottom)+ )+ }++ val result = when (touchRegion) {+ TouchRegion.TopLeft -> {+ val anchorR = rectTemp.right.coerceAtMost(bounds.right)+ if (fixedAspectRatio) anchoredCornerTopLeft(+ anchorR,+ rectTemp.bottom.coerceAtMost(bounds.bottom),+ screenX.coerceAtMost(anchorR - minW)+ )+ else {+ val left = screenX.coerceIn(bounds.left, anchorR - minW)+ val top = screenY.coerceIn(+ bounds.top,+ rectTemp.bottom.coerceAtMost(bounds.bottom) - minH+ )+ clampNonFixed(left, top, anchorR, rectTemp.bottom.coerceAtMost(bounds.bottom))+ }+ }++ TouchRegion.BottomLeft -> {+ val anchorR = rectTemp.right.coerceAtMost(bounds.right)+ if (fixedAspectRatio) anchoredCornerBottomLeft(+ anchorR,+ rectTemp.top.coerceAtLeast(bounds.top),+ screenX.coerceAtMost(anchorR - minW)+ )+ else {+ val left = screenX.coerceIn(bounds.left, anchorR - minW)+ val bottom = screenY.coerceIn(+ rectTemp.top.coerceAtLeast(bounds.top) + minH,+ bounds.bottom+ )+ clampNonFixed(left, rectTemp.top.coerceAtLeast(bounds.top), anchorR, bottom)+ }+ }++ TouchRegion.TopRight -> {+ val anchorL = rectTemp.left.coerceAtLeast(bounds.left)+ if (fixedAspectRatio) anchoredCornerTopRight(+ anchorL,+ rectTemp.bottom.coerceAtMost(bounds.bottom),+ screenX.coerceAtLeast(anchorL + minW)+ )+ else {+ val right = screenX.coerceIn(anchorL + minW, bounds.right)+ val top = screenY.coerceIn(+ bounds.top,+ rectTemp.bottom.coerceAtMost(bounds.bottom) - minH+ )+ clampNonFixed(anchorL, top, right, rectTemp.bottom.coerceAtMost(bounds.bottom))+ }+ }++ TouchRegion.BottomRight -> {+ val anchorL = rectTemp.left.coerceAtLeast(bounds.left)+ if (fixedAspectRatio) anchoredCornerBottomRight(+ anchorL,+ rectTemp.top.coerceAtLeast(bounds.top),+ screenX.coerceAtLeast(anchorL + minW)+ )+ else {+ val right = screenX.coerceIn(anchorL + minW, bounds.right)+ val bottom = screenY.coerceIn(+ rectTemp.top.coerceAtLeast(bounds.top) + minH,+ bounds.bottom+ )+ clampNonFixed(anchorL, rectTemp.top.coerceAtLeast(bounds.top), right, bottom)+ }+ }++ TouchRegion.TopCenter -> {+ if (fixedAspectRatio) centerTop(+ rectTemp.bottom.coerceAtMost(bounds.bottom),+ screenY.coerceAtMost(rectTemp.bottom - minH)+ )+ else {+ val top = screenY.coerceIn(+ bounds.top,+ rectTemp.bottom.coerceAtMost(bounds.bottom) - minH+ )+ clampNonFixed(+ rectTemp.left.coerceAtLeast(bounds.left),+ top,+ rectTemp.right.coerceAtMost(bounds.right),+ rectTemp.bottom.coerceAtMost(bounds.bottom)+ )+ }+ }++ TouchRegion.BottomCenter -> {+ if (fixedAspectRatio) centerBottom(+ rectTemp.top.coerceAtLeast(bounds.top),+ screenY.coerceAtLeast(rectTemp.top + minH)+ )+ else {+ val bottom = screenY.coerceIn(+ rectTemp.top.coerceAtLeast(bounds.top) + minH,+ bounds.bottom+ )+ clampNonFixed(+ rectTemp.left.coerceAtLeast(bounds.left),+ rectTemp.top.coerceAtLeast(bounds.top),+ rectTemp.right.coerceAtMost(bounds.right),+ bottom+ )+ }+ }++ TouchRegion.CenterLeft -> {+ val anchorR = rectTemp.right.coerceAtMost(bounds.right)+ if (fixedAspectRatio) centerLeft(anchorR, screenX.coerceAtMost(anchorR - minW))+ else {+ val left = screenX.coerceIn(bounds.left, anchorR - minW)+ clampNonFixed(+ left,+ rectTemp.top.coerceAtLeast(bounds.top),+ anchorR,+ rectTemp.bottom.coerceAtMost(bounds.bottom)+ )+ }+ }++ TouchRegion.CenterRight -> {+ val anchorL = rectTemp.left.coerceAtLeast(bounds.left)+ if (fixedAspectRatio) centerRight(anchorL, screenX.coerceAtLeast(anchorL + minW))+ else {+ val right = screenX.coerceIn(anchorL + minW, bounds.right)+ clampNonFixed(+ anchorL,+ rectTemp.top.coerceAtLeast(bounds.top),+ right,+ rectTemp.bottom.coerceAtMost(bounds.bottom)+ )+ }+ }++ TouchRegion.Inside -> {+ val drag = change.positionChangeIgnoreConsumed()+ val newLeft = (overlayRect.left + drag.x).coerceIn(+ bounds.left,+ bounds.right - overlayRect.width+ )+ val newTop = (overlayRect.top + drag.y).coerceIn(+ bounds.top,+ bounds.bottom - overlayRect.height+ )+ Rect(newLeft, newTop, newLeft + overlayRect.width, newTop + overlayRect.height)+ }++ else -> overlayRect+ }++ return result+ }++ /**+ * get [TouchRegion] based on touch position on screen relative to [overlayRect].+ */+ private fun getTouchRegion(+ position: Offset,+ rect: Rect,+ threshold: Float+ ): TouchRegion {++ val closedTouchRange = -threshold / 2..threshold+ val centerX = rect.left + rect.width / 2+ val centerY = rect.top + rect.height / 2++ return when {+ position.x - rect.left in closedTouchRange &&+ position.y - rect.top in closedTouchRange -> TouchRegion.TopLeft++ rect.right - position.x in closedTouchRange &&+ position.y - rect.top in closedTouchRange -> TouchRegion.TopRight++ rect.right - position.x in closedTouchRange &&+ rect.bottom - position.y in closedTouchRange -> TouchRegion.BottomRight++ position.x - rect.left in closedTouchRange &&+ rect.bottom - position.y in closedTouchRange -> TouchRegion.BottomLeft++ centerX - position.x in closedTouchRange &&+ position.y - rect.top in closedTouchRange -> TouchRegion.TopCenter++ rect.right - position.x in closedTouchRange &&+ position.y - centerY in closedTouchRange -> TouchRegion.CenterRight++ position.x - rect.left in closedTouchRange &&+ position.y - centerY in closedTouchRange -> TouchRegion.CenterLeft++ centerX - position.x in closedTouchRange &&+ rect.bottom - position.y in closedTouchRange -> TouchRegion.BottomCenter++ else -> {+ if (rect.contains(offset = position)) TouchRegion.Inside+ else TouchRegion.None+ }+ }+ }++ /**+ * Returns how far user touched to corner or center of sides of the screen. [TouchRegion]+ * where user exactly has touched is already passed to this function. For instance user+ * touched top left then this function returns distance to top left from user's position so+ * we can add an offset to not jump edge to position user touched.+ */+ private fun getDistanceToEdgeFromTouch(+ touchRegion: TouchRegion,+ rect: Rect,+ touchPosition: Offset+ ) = when (touchRegion) {+ TouchRegion.TopLeft -> {+ rect.topLeft - touchPosition+ }++ TouchRegion.TopRight -> {+ rect.topRight - touchPosition+ }++ TouchRegion.BottomLeft -> {+ rect.bottomLeft - touchPosition+ }++ TouchRegion.BottomRight -> {+ rect.bottomRight - touchPosition+ }++ TouchRegion.TopCenter -> {+ rect.topCenter - touchPosition+ }++ TouchRegion.CenterRight -> {+ rect.centerRight - touchPosition+ }++ TouchRegion.BottomCenter -> {+ rect.bottomCenter - touchPosition+ }++ TouchRegion.CenterLeft -> {+ rect.centerLeft - touchPosition+ }++ else -> {+ Offset.Zero+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/StaticCropState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/StaticCropState.ktnew file mode 100644index 0000000..e64a8cf--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/StaticCropState.kt@@ -0,0 +1,145 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import kotlinx.coroutines.coroutineScope++/**+ * * State for cropper with dynamic overlay. When this state is selected instead of overlay+ * image is moved while overlay is stationary.+ *+ * @param imageSize size of the **Bitmap**+ * @param containerSize size of the Composable that draws **Bitmap**+ * @param maxZoom maximum zoom value+ * @param fling when set to true dragging pointer builds up velocity. When last+ * pointer leaves Composable a movement invoked against friction till velocity drops below+ * to threshold+ * @param zoomable when set to true zoom is enabled+ * @param pannable when set to true pan is enabled+ * @param rotatable when set to true rotation is enabled+ * @param limitPan limits pan to bounds of parent Composable. Using this flag prevents creating+ * empty space on sides or edges of parent+ */+class StaticCropState internal constructor(+ imageSize: IntSize,+ containerSize: IntSize,+ drawAreaSize: IntSize,+ aspectRatio: AspectRatio,+ overlayRatio: Float,+ maxZoom: Float = 5f,+ fling: Boolean = false,+ zoomable: Boolean = true,+ pannable: Boolean = true,+ rotatable: Boolean = false,+ limitPan: Boolean = false+) : CropState(+ imageSize = imageSize,+ containerSize = containerSize,+ drawAreaSize = drawAreaSize,+ aspectRatio = aspectRatio,+ overlayRatio = overlayRatio,+ maxZoom = maxZoom,+ fling = fling,+ zoomable = zoomable,+ pannable = pannable,+ rotatable = rotatable,+ limitPan = limitPan+) {++ override suspend fun onDown(change: PointerInputChange) = Unit+ override suspend fun onMove(changes: List<PointerInputChange>) = Unit+ override suspend fun onUp(change: PointerInputChange) = Unit++ private var doubleTapped = false++ /*+ Transform gestures+ */+ override suspend fun onGesture(+ centroid: Offset,+ panChange: Offset,+ zoomChange: Float,+ rotationChange: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ ) = coroutineScope {+ doubleTapped = false++ updateTransformState(+ centroid = centroid,+ zoomChange = zoomChange,+ panChange = panChange,+ rotationChange = rotationChange+ )++ // Update image draw rectangle based on pan, zoom or rotation change+ drawAreaRect = updateImageDrawRectFromTransformation()++ // Fling Gesture+ if (pannable && fling) {+ if (changes.size == 1) {+ addPosition(mainPointer.uptimeMillis, mainPointer.position)+ }+ }+ }++ override suspend fun onGestureStart() = coroutineScope {}++ override suspend fun onGestureEnd(onBoundsCalculated: () -> Unit) {++ // Gesture end might be called after second tap and we don't want to fling+ // or animate back to valid bounds when doubled tapped+ if (!doubleTapped) {++ if (pannable && fling && zoom > 1) {+ fling {+ // We get target value on start instead of updating bounds after+ // gesture has finished+ drawAreaRect = updateImageDrawRectFromTransformation()+ onBoundsCalculated()+ }+ } else {+ onBoundsCalculated()+ }++ animateTransformationToOverlayBounds(overlayRect, animate = true)+ }+ }++ // Double Tap+ override suspend fun onDoubleTap(+ offset: Offset,+ zoom: Float,+ onAnimationEnd: () -> Unit+ ) {+ doubleTapped = true++ if (fling) {+ resetTracking()+ }+ resetWithAnimation(pan = pan, zoom = zoom, rotation = rotation)+ drawAreaRect = updateImageDrawRectFromTransformation()+ animateTransformationToOverlayBounds(overlayRect, true)+ onAnimationEnd()+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/TransformState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/TransformState.ktnew file mode 100644index 0000000..843053b--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/state/TransformState.kt@@ -0,0 +1,273 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state++import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.AnimationSpec+import androidx.compose.animation.core.exponentialDecay+import androidx.compose.animation.core.tween+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.input.pointer.util.VelocityTracker+import androidx.compose.ui.unit.IntSize+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch++/**+ * State of the pan, zoom and rotation. Allows to change zoom, pan via [Animatable]+ * objects' [Animatable.animateTo], [Animatable.snapTo].+ * @param initialZoom initial zoom level+ * @param initialRotation initial angle in degrees+ * @param minZoom minimum zoom+ * @param maxZoom maximum zoom+ * @param zoomable when set to true zoom is enabled+ * @param pannable when set to true pan is enabled+ * @param rotatable when set to true rotation is enabled+ * @param limitPan limits pan to bounds of parent Composable. Using this flag prevents creating+ * empty space on sides or edges of parent.+ *+ */+@Stable+open class TransformState(+ internal val imageSize: IntSize,+ val containerSize: IntSize,+ val drawAreaSize: IntSize,+ initialZoom: Float = 1f,+ initialRotation: Float = 0f,+ minZoom: Float = 0.5f, // Definitely+ maxZoom: Float = 10f,+ internal var zoomable: Boolean = true,+ internal var pannable: Boolean = true,+ internal var rotatable: Boolean = true,+ internal var limitPan: Boolean = false+) {++ var drawAreaRect: Rect by mutableStateOf(+ Rect(+ offset = Offset(+ x = ((containerSize.width - drawAreaSize.width) / 2).toFloat(),+ y = ((containerSize.height - drawAreaSize.height) / 2).toFloat()+ ),+ size = Size(drawAreaSize.width.toFloat(), drawAreaSize.height.toFloat())+ )+ )++ internal val zoomMin = minZoom.coerceAtLeast(0.5f) // Definitely+ internal var zoomMax = maxZoom.coerceAtLeast(1f)+ private val zoomInitial = initialZoom.coerceIn(zoomMin, zoomMax)+ private val rotationInitial = initialRotation % 360++ internal val animatablePanX = Animatable(0f)+ internal val animatablePanY = Animatable(0f)+ internal val animatableZoom = Animatable(zoomInitial)+ internal val animatableRotation = Animatable(rotationInitial)++ private val velocityTracker = VelocityTracker()++ init {+ animatableZoom.updateBounds(zoomMin, zoomMax)+ require(zoomMax >= zoomMin)+ }++ val pan: Offset+ get() = Offset(animatablePanX.value, animatablePanY.value)++ val zoom: Float+ get() = animatableZoom.value++ val rotation: Float+ get() = animatableRotation.value++ val isZooming: Boolean+ get() = animatableZoom.isRunning++ val isPanning: Boolean+ get() = animatablePanX.isRunning || animatablePanY.isRunning++ val isRotating: Boolean+ get() = animatableRotation.isRunning++ val isAnimationRunning: Boolean+ get() = isZooming || isPanning || isRotating++ internal open fun updateBounds(lowerBound: Offset?, upperBound: Offset?) {+ animatablePanX.updateBounds(lowerBound?.x, upperBound?.x)+ animatablePanY.updateBounds(lowerBound?.y, upperBound?.y)+ }++ /**+ * Update centroid, pan, zoom and rotation of this state when transform gestures are+ * invoked with one or multiple pointers+ */+ internal open suspend fun updateTransformState(+ centroid: Offset,+ panChange: Offset,+ zoomChange: Float,+ rotationChange: Float = 1f,+ ) {+ val newZoom = (this.zoom * zoomChange).coerceIn(zoomMin, zoomMax)++ snapZoomTo(newZoom)+ val newRotation = if (rotatable) {+ this.rotation + rotationChange+ } else {+ 0f+ }+ snapRotationTo(newRotation)++ if (pannable) {+ val newPan = this.pan + panChange.times(this.zoom / newZoom)+ snapPanXto(newPan.x)+ snapPanYto(newPan.y)+ }+ }++ /**+ * Reset [pan], [zoom] and [rotation] with animation.+ */+ internal suspend fun resetWithAnimation(+ pan: Offset = Offset.Zero,+ zoom: Float = 1f,+ rotation: Float = 0f,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) = coroutineScope {+ launch { animatePanXto(pan.x, animationSpec) }+ launch { animatePanYto(pan.y, animationSpec) }+ launch { animateZoomTo(zoom, animationSpec) }+ launch { animateRotationTo(rotation, animationSpec) }+ }++ internal suspend fun animatePanXto(+ panX: Float,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) {+ if (pannable && pan.x != panX) {+ animatablePanX.animateTo(panX, animationSpec)+ }+ }++ internal suspend fun animatePanYto(+ panY: Float,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) {+ if (pannable && pan.y != panY) {+ animatablePanY.animateTo(panY, animationSpec)+ }+ }++ internal suspend fun animateZoomTo(+ zoom: Float,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) {+ if (zoomable && this.zoom != zoom) {+ val newZoom = zoom.coerceIn(zoomMin, zoomMax)+ animatableZoom.animateTo(newZoom, animationSpec)+ }+ }++ suspend fun animateRotationTo(+ rotation: Float,+ animationSpec: AnimationSpec<Float> = tween(250)+ ) {+ if (rotatable && this.rotation != rotation) {+ animatableRotation.animateTo(rotation, animationSpec)+ }+ }++ internal suspend fun snapPanXto(panX: Float) {+ if (pannable) {+ animatablePanX.snapTo(panX)+ }+ }++ internal suspend fun snapPanYto(panY: Float) {+ if (pannable) {+ animatablePanY.snapTo(panY)+ }+ }++ internal suspend fun snapZoomTo(zoom: Float) {+ if (zoomable) {+ animatableZoom.snapTo(zoom.coerceIn(zoomMin, zoomMax))+ }+ }++ internal suspend fun snapRotationTo(rotation: Float) {+ if (rotatable) {+ animatableRotation.snapTo(rotation)+ }+ }++ /*+ Fling gesture+ */+ internal fun addPosition(timeMillis: Long, position: Offset) {+ velocityTracker.addPosition(+ timeMillis = timeMillis,+ position = position+ )+ }++ /**+ * Create a fling gesture when user removes finger from scree to have continuous movement+ * until [velocityTracker] speed reached to lower bound+ */+ internal suspend fun fling(onFlingStart: () -> Unit) = coroutineScope {+ val velocityTracker = velocityTracker.calculateVelocity()+ val velocity = Offset(velocityTracker.x, velocityTracker.y)+ var flingStarted = false++ launch {+ animatablePanX.animateDecay(+ velocity.x,+ exponentialDecay(absVelocityThreshold = 20f),+ block = {+ // This callback returns target value of fling gesture initially+ if (!flingStarted) {+ onFlingStart()+ flingStarted = true+ }+ }+ )+ }++ launch {+ animatablePanY.animateDecay(+ velocity.y,+ exponentialDecay(absVelocityThreshold = 20f),+ block = {+ // This callback returns target value of fling gesture initially+ if (!flingStarted) {+ onFlingStart()+ flingStarted = true+ }+ }+ )+ }+ }++ internal fun resetTracking() {+ velocityTracker.resetTracking()+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DimensionUtil.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DimensionUtil.ktnew file mode 100644index 0000000..7f70099--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DimensionUtil.kt@@ -0,0 +1,62 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++/**+ * [Linear Interpolation](https://en.wikipedia.org/wiki/Linear_interpolation) function that moves+ * amount from it's current position to start and amount+ * @param start of interval+ * @param stop of interval+ * @param fraction closed unit interval [0, 1]+ */+fun lerp(start: Float, stop: Float, fraction: Float): Float {+ return (1 - fraction) * start + fraction * stop+}++/**+ * Scale x1 from start1..end1 range to start2..end2 range++ */+fun scale(start1: Float, end1: Float, pos: Float, start2: Float, end2: Float) =+ lerp(start2, end2, calculateFraction(start1, end1, pos))++/**+ * Scale x.start, x.endInclusive from a1..b1 range to a2..b2 range+ */+fun scale(+ start1: Float,+ end1: Float,+ range: ClosedFloatingPointRange<Float>,+ start2: Float,+ end2: Float+) =+ scale(start1, end1, range.start, start2, end2)..scale(+ start1,+ end1,+ range.endInclusive,+ start2,+ end2+ )+++/**+ * Calculate fraction for value between a range [end] and [start] coerced into 0f-1f range+ */+fun calculateFraction(start: Float, end: Float, pos: Float) =+ (if (end - start == 0f) 0f else (pos - start) / (end - start)).coerceIn(0f, 1f)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DrawScopeUtils.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DrawScopeUtils.ktnew file mode 100644index 0000000..0d27deb--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/DrawScopeUtils.kt@@ -0,0 +1,68 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.nativeCanvas++/**+ * Draw grid that is divided by 2 vertical and 2 horizontal lines for overlay+ */+fun DrawScope.drawGrid(rect: Rect, strokeWidth: Float, color: Color) {++ val width = rect.width+ val height = rect.height+ val gridWidth = width / 3+ val gridHeight = height / 3++ // Horizontal lines+ for (i in 1..2) {+ drawLine(+ color = color,+ start = Offset(rect.left, rect.top + i * gridHeight),+ end = Offset(rect.right, rect.top + i * gridHeight),+ strokeWidth = strokeWidth+ )+ }++ // Vertical lines+ for (i in 1..2) {+ drawLine(+ color,+ start = Offset(rect.left + i * gridWidth, rect.top),+ end = Offset(rect.left + i * gridWidth, rect.bottom),+ strokeWidth = strokeWidth+ )+ }+}++/**+ * Draw with layer to use [BlendMode]s+ */+fun DrawScope.drawWithLayer(block: DrawScope.() -> Unit) {+ with(drawContext.canvas.nativeCanvas) {+ val checkPoint = saveLayer(null, null)+ block()+ restoreToCount(checkPoint)+ }+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ImageContentScaleUtil.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ImageContentScaleUtil.ktnew file mode 100644index 0000000..0cf7968--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ImageContentScaleUtil.kt@@ -0,0 +1,106 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.BoxWithConstraintsScope+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize++/**+ * Get Rectangle of [ImageBitmap] with [bitmapWidth] and [bitmapHeight] that is drawn inside+ * Canvas with [imageWidth] and [imageHeight]. [boxWidth] and [boxHeight] belong+ * to [BoxWithConstraints] that contains Canvas.+ * @param boxWidth width of the parent container+ * @param boxHeight height of the parent container+ * @param imageWidth width of the [Canvas] that draws [ImageBitmap]+ * @param imageHeight height of the [Canvas] that draws [ImageBitmap]+ * @param bitmapWidth intrinsic width of the [ImageBitmap]+ * @param bitmapHeight intrinsic height of the [ImageBitmap]+ * @return [IntRect] that covers [ImageBitmap] bounds. When image [ContentScale] is crop+ * this rectangle might return smaller rectangle than actual [ImageBitmap] and left or top+ * of the rectangle might be bigger than zero.+ */+internal fun getScaledBitmapRect(+ boxWidth: Int,+ boxHeight: Int,+ imageWidth: Float,+ imageHeight: Float,+ bitmapWidth: Int,+ bitmapHeight: Int+): IntRect {+ // Get scale of box to width of the image+ // We need a rect that contains Bitmap bounds to pass if any child requires it+ // For a image with 100x100 px with 300x400 px container and image with crop 400x400px+ // So we need to pass top left as 0,50 and size+ val scaledBitmapX = boxWidth / imageWidth+ val scaledBitmapY = boxHeight / imageHeight++ val topLeft = IntOffset(+ x = (bitmapWidth * (imageWidth - boxWidth) / imageWidth / 2)+ .coerceAtLeast(0f).toInt(),+ y = (bitmapHeight * (imageHeight - boxHeight) / imageHeight / 2)+ .coerceAtLeast(0f).toInt()+ )++ val size = IntSize(+ width = (bitmapWidth * scaledBitmapX).toInt().coerceAtMost(bitmapWidth),+ height = (bitmapHeight * scaledBitmapY).toInt().coerceAtMost(bitmapHeight)+ )++ return IntRect(offset = topLeft, size = size)+}++/**+ * Get [IntSize] of the parent or container that contains [Canvas] that draws [ImageBitmap]+ * @param bitmapWidth intrinsic width of the [ImageBitmap]+ * @param bitmapHeight intrinsic height of the [ImageBitmap]+ * @return size of parent Composable. When Modifier is assigned with fixed or finite size+ * they are used, but when any dimension is set to infinity intrinsic dimensions of+ * [ImageBitmap] are returned+ */+internal fun BoxWithConstraintsScope.getParentSize(+ bitmapWidth: Int,+ bitmapHeight: Int+): IntSize {+ // Check if Composable has fixed size dimensions+ val hasBoundedDimens = constraints.hasBoundedWidth && constraints.hasBoundedHeight+ // Check if Composable has infinite dimensions+ val hasFixedDimens = constraints.hasFixedWidth && constraints.hasFixedHeight++ // Box is the parent(BoxWithConstraints) that contains Canvas under the hood+ // Canvas aspect ratio or size might not match parent but it's upper bounds are+ // what are passed from parent. Canvas cannot be bigger or taller than BoxWithConstraints+ val boxWidth: Int = if (hasBoundedDimens || hasFixedDimens) {+ constraints.maxWidth+ } else {+ constraints.minWidth.coerceAtLeast(bitmapWidth)+ }+ val boxHeight: Int = if (hasBoundedDimens || hasFixedDimens) {+ constraints.maxHeight+ } else {+ constraints.minHeight.coerceAtLeast(bitmapHeight)+ }+ return IntSize(boxWidth, boxHeight)+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/OffsetUtil.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/OffsetUtil.ktnew file mode 100644index 0000000..9bc10cf--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/OffsetUtil.kt@@ -0,0 +1,30 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++import androidx.compose.ui.geometry.Offset+++/**+ * Coerce an [Offset] x value in [horizontalRange] and y value in [verticalRange]+ */+fun Offset.coerceIn(+ horizontalRange: ClosedRange<Float>,+ verticalRange: ClosedRange<Float>+) = Offset(this.x.coerceIn(horizontalRange), this.y.coerceIn(verticalRange))\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ShapeUtils.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ShapeUtils.ktnew file mode 100644index 0000000..d995595--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ShapeUtils.kt@@ -0,0 +1,190 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++import android.graphics.Matrix+import androidx.compose.foundation.shape.GenericShape+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.asAndroidPath+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.model.AspectRatio+import kotlin.math.cos+import kotlin.math.sin+++/**+ * Creates a polygon with number of [sides] centered at ([cx],[cy]) with [radius].+ * ```+ * To generate regular polygons (i.e. where each interior angle is the same),+ * polar coordinates are extremely useful. You can calculate the angle necessary+ * to produce the desired number of sides (as the interior angles total 360º)+ * and then use multiples of this angle with the same radius to describe each point.+ * val x = radius * Math.cos(angle);+ * val y = radius * Math.sin(angle);+ *+ * For instance to draw triangle loop thrice with angle+ * 0, 120, 240 degrees in radians and draw lines from each coordinate.+ * ```+ */+fun createPolygonPath(cx: Float, cy: Float, sides: Int, radius: Float): Path {++ val angle = 2.0 * Math.PI / sides++ return Path().apply {+ moveTo(+ cx + (radius * cos(0.0)).toFloat(),+ cy + (radius * sin(0.0)).toFloat()+ )+ for (i in 1 until sides) {+ lineTo(+ cx + (radius * cos(angle * i)).toFloat(),+ cy + (radius * sin(angle * i)).toFloat()+ )+ }+ close()+ }+}+++/**+ * Create a polygon shape+ */+fun createPolygonShape(sides: Int, degrees: Float = 0f): GenericShape {+ return GenericShape { size: Size, _: LayoutDirection ->++ val radius = size.width.coerceAtMost(size.height) / 2+ addPath(+ createPolygonPath(+ cx = size.width / 2,+ cy = size.height / 2,+ sides = sides,+ radius = radius+ )+ )+ val matrix = Matrix()+ matrix.postRotate(degrees, size.width / 2, size.height / 2)+ this.asAndroidPath().transform(matrix)+ }+}++/**+ * Creates a [Rect] shape with given aspect ratio.+ */+fun createRectShape(aspectRatio: AspectRatio): GenericShape {+ return GenericShape { size: Size, _: LayoutDirection ->+ val value = aspectRatio.value++ val width = size.width+ val height = size.height+ val shapeSize =+ if (aspectRatio == AspectRatio.Original) Size(width, height)+ else if (value > 1) Size(width = width, height = width / value)+ else Size(width = height * value, height = height)++ addRect(Rect(offset = Offset.Zero, size = shapeSize))+ }+}++/**+ * Scales this path to [width] and [height] from [Path.getBounds] and translates+ * as difference between scaled path and original path+ */+fun Path.scaleAndTranslatePath(+ width: Float,+ height: Float,+) {+ val pathSize = getBounds().size++ val matrix = Matrix()+ matrix.postScale(+ width / pathSize.width,+ height / pathSize.height+ )++ this.asAndroidPath().transform(matrix)++ val left = getBounds().left+ val top = getBounds().top++ translate(Offset(-left, -top))+}++/**+ * Build an outline from a shape using aspect ratio, shape and coefficient to scale+ *+ * @return [Triple] that contains left, top offset and [Outline]+ */+fun buildOutline(+ aspectRatio: AspectRatio,+ coefficient: Float,+ shape: Shape,+ size: Size,+ layoutDirection: LayoutDirection,+ density: Density+): Pair<Offset, Outline> {++ val (shapeSize, offset) = calculateSizeAndOffsetFromAspectRatio(aspectRatio, coefficient, size)++ val outline = shape.createOutline(+ size = shapeSize,+ layoutDirection = layoutDirection,+ density = density+ )+ return Pair(offset, outline)+}+++/**+ * Calculate new size and offset based on [size], [coefficient] and [aspectRatio]+ *+ * For 4/3f aspect ratio with 1000px width, 1000px height with coefficient 1f+ * it returns Size(1000f, 750f), Offset(0f, 125f).+ */+fun calculateSizeAndOffsetFromAspectRatio(+ aspectRatio: AspectRatio,+ coefficient: Float,+ size: Size,+): Pair<Size, Offset> {+ val width = size.width+ val height = size.height++ val value = aspectRatio.value++ val newSize = if (aspectRatio == AspectRatio.Original) {+ Size(width * coefficient, height * coefficient)+ } else if (value > 1) {+ Size(+ width = coefficient * width,+ height = coefficient * width / value+ )+ } else {+ Size(width = coefficient * height * value, height = coefficient * height)+ }++ val left = (width - newSize.width) / 2+ val top = (height - newSize.height) / 2++ return Pair(newSize, Offset(left, top))+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomLevel.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomLevel.ktnew file mode 100644index 0000000..76b1066--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomLevel.kt@@ -0,0 +1,26 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++/**+ * Enum class for zoom levels+ */+enum class ZoomLevel {+ Min, Mid, Max+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomUtil.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomUtil.ktnew file mode 100644index 0000000..16f6ce4--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/cropper/util/ZoomUtil.kt@@ -0,0 +1,89 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.cropper.util++import androidx.compose.ui.graphics.GraphicsLayerScope+import com.chethan616.clearpdf.imageeditor.thirdparty.cropper.state.TransformState++/**+ * Calculate zoom level and zoom value when user double taps+ */+internal fun calculateZoom(+ zoomLevel: ZoomLevel,+ initial: Float,+ min: Float,+ max: Float+): Pair<ZoomLevel, Float> {++ val newZoomLevel: ZoomLevel+ val newZoom: Float++ when (zoomLevel) {+ ZoomLevel.Mid -> {+ newZoomLevel = ZoomLevel.Max+ newZoom = max.coerceAtMost(3f)+ }++ ZoomLevel.Max -> {+ newZoomLevel = ZoomLevel.Min+ newZoom = if (min == initial) initial else min+ }++ else -> {+ newZoomLevel = ZoomLevel.Mid+ newZoom = if (min == initial) (min + max.coerceAtMost(3f)) / 2 else initial+ }+ }+ return Pair(newZoomLevel, newZoom)+}++internal fun getNextZoomLevel(zoomLevel: ZoomLevel): ZoomLevel = when (zoomLevel) {+ ZoomLevel.Mid -> {+ ZoomLevel.Max+ }++ ZoomLevel.Max -> {+ ZoomLevel.Min+ }++ else -> {+ ZoomLevel.Mid+ }+}++/**+ * Update graphic layer with [transformState]+ */+internal fun GraphicsLayerScope.update(transformState: TransformState) {++ // Set zoom+ val zoom = transformState.zoom+ this.scaleX = zoom+ this.scaleY = zoom++ // Set pan+ val pan = transformState.pan+ val translationX = pan.x+ val translationY = pan.y+ this.translationX = translationX+ this.translationY = translationY++ // Set rotation+ this.rotationZ = transformState.rotation+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/FreeCrop.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/FreeCrop.ktnew file mode 100644index 0000000..f014d19--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/FreeCrop.kt@@ -0,0 +1,76 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): OpenCV warpPerspective replaced with android.graphics.Matrix+ * setPolyToPoly so the perspective crop needs no native library.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.freecorners++import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Matrix+import android.graphics.Paint+import android.graphics.PointF+import androidx.compose.ui.geometry.Offset+import com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.model.Quad+import com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.model.distance+import kotlin.math.max+import kotlin.math.roundToInt++object FreeCrop {++ /**+ * Warps the quadrilateral [points] (TL, TR, BR, BL in bitmap pixels) of [bitmap] into an+ * upright rectangle. Output size follows the original OpenCV implementation: the shorter of+ * each pair of opposite edges.+ */+ fun crop(+ bitmap: Bitmap,+ points: List<Offset>+ ): Bitmap {+ val corners = Quad(+ topLeftCorner = PointF(points[0].x, points[0].y),+ topRightCorner = PointF(points[1].x, points[1].y),+ bottomRightCorner = PointF(points[2].x, points[2].y),+ bottomLeftCorner = PointF(points[3].x, points[3].y)+ )+ val tl = corners.topLeftCorner+ val tr = corners.topRightCorner+ val br = corners.bottomRightCorner+ val bl = corners.bottomLeftCorner++ val width = max(1, minOf(tl.distance(tr), bl.distance(br)).roundToInt())+ val height = max(1, minOf(tl.distance(bl), tr.distance(br)).roundToInt())++ val src = floatArrayOf(tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y)+ val dst = floatArrayOf(+ 0f, 0f,+ width.toFloat(), 0f,+ width.toFloat(), height.toFloat(),+ 0f, height.toFloat()+ )+ val matrix = Matrix()+ if (!matrix.setPolyToPoly(src, 0, dst, 0, 4)) return bitmap++ val out = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)+ Canvas(out).drawBitmap(+ bitmap,+ matrix,+ Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG or Paint.DITHER_FLAG)+ )+ return out+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropper.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropper.ktnew file mode 100644index 0000000..ad8e0f3--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropper.kt@@ -0,0 +1,1449 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.compose++import android.graphics.Bitmap+import android.net.Uri+import androidx.compose.animation.core.animate+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.spring+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.Image+import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateCentroid+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.magnifier+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.isSpecified+import androidx.compose.ui.graphics.BlendMode+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.CompositingStrategy+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.clipPath+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChange+import androidx.compose.ui.input.pointer.positionChanged+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.layout.positionInParent+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.DpSize+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.toSize+import androidx.compose.ui.util.fastAny+import androidx.compose.ui.util.fastForEach+import com.chethan616.clearpdf.imageeditor.thirdparty.gesture.detectTransformGestures+import com.chethan616.clearpdf.imageeditor.thirdparty.image.ImageWithConstraints+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlin.math.exp+import kotlin.math.roundToInt++@Composable+fun FreeCornersCropper(+ bitmap: Bitmap,+ sourceImageUri: Uri? = null,+ sourceImageSize: IntSize = IntSize(bitmap.width, bitmap.height),+ croppingTrigger: Boolean,+ onCropped: (List<Offset>) -> Unit,+ state: FreeCornersCropperState = rememberFreeCornersCropperState(),+ onTransformationCommitted: () -> Unit = {},+ modifier: Modifier = Modifier,+ showMagnifier: Boolean = true,+ handlesSize: Dp = 8.dp,+ frameStrokeWidth: Dp = 1.2.dp,+ onZoomChange: (Float) -> Unit = {},+ coercePointsToImageArea: Boolean = true,+ isOverlayDraggable: Boolean = true,+ overlayColor: Color = Color.Black.copy(0.55f),+ contentPadding: PaddingValues = PaddingValues(24.dp),+ gridColor: Color,+ handlesColor: Color+) {+ val density = LocalDensity.current+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val currentOnTransformationCommitted by rememberUpdatedState(onTransformationCommitted)+ val imageKey: Any = sourceImageUri ?: FreeCornersCropperImageKey(+ bitmap = bitmap,+ generationId = bitmap.generationId+ )+ val attachmentKey = remember(imageKey) { Any() }++ val handleRadiusPx = with(density) {+ handlesSize.toPx()+ }+ val strictCornerTouchRadiusPx = with(density) {+ maxOf(+ handleRadiusPx * STRICT_CORNER_TOUCH_RADIUS_MULTIPLIER,+ MinStrictCornerTouchRadius.toPx()+ )+ }+ val cornerTouchRadiusPx = with(density) {+ maxOf(handleRadiusPx * CORNER_TOUCH_RADIUS_MULTIPLIER, MinCornerTouchRadius.toPx())+ }+ val edgeTouchRadiusPx = with(density) {+ maxOf(handleRadiusPx * EDGE_TOUCH_RADIUS_MULTIPLIER, MinEdgeTouchRadius.toPx())+ }+ val frameStrokeWidthPx = with(density) {+ frameStrokeWidth.toPx()+ }+ val middleHandleStrokeWidthPx = with(density) {+ MiddleHandleStrokeWidth.toPx()+ }+ val imageBitmap = remember(imageKey) { bitmap.asImageBitmap() }++ var dragTarget by remember(imageKey) { mutableStateOf<DragTarget>(DragTarget.None) }+ var magnifierCenter by remember(imageKey) { mutableStateOf(Offset.Unspecified) }+ var baseImageBounds by remember(imageKey) { mutableStateOf(Rect.Zero) }+ var drawPoints by remember(imageKey) { mutableStateOf(emptyList<Offset>()) }+ var imageScale by remember(imageKey) { mutableFloatStateOf(1f) }+ var imageTranslation by remember(imageKey) { mutableStateOf(Offset.Zero) }+ var viewportBounds by remember(imageKey) { mutableStateOf(Rect.Zero) }+ var pendingLayoutSnapshot by remember(imageKey) {+ mutableStateOf<FreeCornersCropSnapshot?>(null)+ }+ var transformAnimationJob by remember { mutableStateOf<Job?>(null) }++ fun captureLayoutSnapshot() {+ if (pendingLayoutSnapshot != null) return+ pendingLayoutSnapshot = state.snapshotForLayoutChange()+ }++ fun attachState() {+ state.attach(+ attachmentKey = attachmentKey,+ imageKey = imageKey,+ captureSnapshot = {+ captureFreeCornersCropSnapshot(+ points = drawPoints,+ imageBounds = baseImageBounds,+ imageScale = imageScale,+ imageTranslation = imageTranslation,+ viewportBounds = viewportBounds+ )+ },+ restoreSnapshot = { snapshot ->+ transformAnimationJob?.cancel()+ restoreFreeCornersCropSnapshot(+ snapshot = snapshot,+ imageBounds = baseImageBounds,+ viewportBounds = viewportBounds,+ coercePointsToImageArea = coercePointsToImageArea+ )?.let { restored ->+ drawPoints = restored.points+ imageScale = restored.imageScale+ imageTranslation = restored.imageTranslation+ }+ dragTarget = DragTarget.None+ magnifierCenter = Offset.Unspecified+ }+ )+ }++ fun beginTransformation() {+ transformAnimationJob?.cancel()+ attachState()+ state.beginTransformation()+ }++ fun endTransformation() {+ if (state.endTransformation()) {+ currentOnTransformationCommitted()+ }+ }++ SideEffect {+ attachState()+ }+ DisposableEffect(state, attachmentKey) {+ onDispose {+ transformAnimationJob?.cancel()+ state.prepareForReattachment(attachmentKey)+ state.detach(attachmentKey)+ }+ }++ fun updateImageTransform(scale: Float, translation: Offset) {+ imageScale = scale+ imageTranslation = translation+ }++ onZoomChange(imageScale)++ ImageWithConstraints(+ modifier = modifier+ .clipToBounds()+ .onSizeChanged { size ->+ val newViewportBounds = Rect(+ left = handleRadiusPx.coerceAtMost(size.width / 2f),+ top = handleRadiusPx.coerceAtMost(size.height / 2f),+ right = size.width - handleRadiusPx.coerceAtMost(size.width / 2f),+ bottom = size.height - handleRadiusPx.coerceAtMost(size.height / 2f)+ )+ if (+ viewportBounds.hasPositiveSize() &&+ viewportBounds != newViewportBounds+ ) {+ captureLayoutSnapshot()+ }+ viewportBounds = newViewportBounds+ }+ .pointerInput(imageKey, coercePointsToImageArea) {+ detectOneFingerZoomGestures(+ onDoubleTap = { position ->+ beginTransformation()+ val minScale = if (coercePointsToImageArea) {+ calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ } else {+ MINIMUM_CROP_ZOOM+ }+ val zoomedScale = DEFAULT_DOUBLE_TAP_SCALE.coerceIn(minScale, MAX_ZOOM)+ val targetScale = if (+ imageScale >= zoomedScale - SCALE_COMPARISON_TOLERANCE+ ) {+ minScale+ } else {+ zoomedScale+ }+ val target = calculateTransformAfterZoom(+ currentScale = imageScale,+ currentTranslation = imageTranslation,+ targetScale = targetScale,+ centroid = position,+ transformCenter = baseImageBounds.center+ )+ transformAnimationJob = scope.launch {+ animateTransformTo(+ startScale = imageScale,+ startTranslation = imageTranslation,+ targetScale = targetScale,+ targetTranslation = if (coercePointsToImageArea) {+ coerceImageTranslation(+ translation = target.translation,+ scale = targetScale,+ imageBounds = baseImageBounds,+ cropBounds = drawPoints.boundingRect(),+ coerceToCrop = true+ )+ } else {+ target.translation+ },+ onUpdate = ::updateImageTransform+ )+ endTransformation()+ }+ },+ onZoomStart = {+ beginTransformation()+ },+ onZoom = { centroid, zoom ->+ val minScale = if (coercePointsToImageArea) {+ calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ } else {+ MINIMUM_CROP_ZOOM+ }+ val targetScale = (imageScale * zoom).coerceIn(+ minimumValue = minScale * MIN_SCALE_GESTURE_RESISTANCE,+ maximumValue = MAX_ZOOM+ )+ val target = calculateTransformAfterZoom(+ currentScale = imageScale,+ currentTranslation = imageTranslation,+ targetScale = targetScale,+ centroid = centroid,+ transformCenter = baseImageBounds.center+ )+ imageScale = targetScale+ imageTranslation = if (coercePointsToImageArea) {+ coerceImageTranslation(+ translation = target.translation,+ scale = targetScale,+ imageBounds = baseImageBounds,+ cropBounds = drawPoints.boundingRect(),+ coerceToCrop = true+ )+ } else {+ target.translation+ }+ },+ onZoomEnd = {+ if (!coercePointsToImageArea) {+ endTransformation()+ return@detectOneFingerZoomGestures+ }++ transformAnimationJob = scope.launch {+ val minScale = calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ val targetScale = imageScale.coerceIn(minScale, MAX_ZOOM)+ val targetTranslation = coerceImageTranslation(+ translation = imageTranslation,+ scale = targetScale,+ imageBounds = baseImageBounds,+ cropBounds = drawPoints.boundingRect(),+ coerceToCrop = coercePointsToImageArea+ )+ animateTransformTo(+ startScale = imageScale,+ startTranslation = imageTranslation,+ targetScale = targetScale,+ targetTranslation = targetTranslation,+ onUpdate = ::updateImageTransform+ )+ endTransformation()+ }+ }+ )+ }+ .pointerInput(imageKey, coercePointsToImageArea) {+ var transformGestureActive = false++ detectTransformGestures(+ consume = true,+ onGestureStart = {+ transformGestureActive = false+ transformAnimationJob?.cancel()+ },+ onGesture = { centroid, pan, zoom, _, _, _ ->+ if (!transformGestureActive) {+ transformGestureActive = true+ beginTransformation()+ }+ val minScale = if (coercePointsToImageArea) {+ calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ } else {+ MINIMUM_CROP_ZOOM+ }+ val targetScale = (imageScale * zoom).coerceIn(+ minimumValue = minScale * MIN_SCALE_GESTURE_RESISTANCE,+ maximumValue = MAX_ZOOM+ )+ val target = calculateTransformAfterZoom(+ currentScale = imageScale,+ currentTranslation = imageTranslation,+ targetScale = targetScale,+ centroid = centroid,+ transformCenter = baseImageBounds.center+ )+ imageScale = targetScale+ imageTranslation = target.translation + pan+ },+ onGestureEnd = {+ if (!transformGestureActive) {+ return@detectTransformGestures+ }+ if (!coercePointsToImageArea) {+ endTransformation()+ return@detectTransformGestures+ }++ transformAnimationJob = scope.launch {+ val minScale = calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ val targetScale = imageScale.coerceIn(minScale, MAX_ZOOM)+ val targetTranslation = coerceImageTranslation(+ translation = imageTranslation,+ scale = targetScale,+ imageBounds = baseImageBounds,+ cropBounds = drawPoints.boundingRect(),+ coerceToCrop = coercePointsToImageArea+ )+ animateTransformTo(+ startScale = imageScale,+ startTranslation = imageTranslation,+ targetScale = targetScale,+ targetTranslation = targetTranslation,+ onUpdate = ::updateImageTransform+ )+ endTransformation()+ }+ }+ )+ },+ imageBitmap = imageBitmap,+ drawImage = false+ ) {+ val internalPaddingDp = 16.dp+ val internalPadding = with(density) { internalPaddingDp.toPx() }+ val containerWidthPx = with(density) { maxWidth.toPx() }+ val containerHeightPx = with(density) { maxHeight.toPx() }+ val horizontalPointInset = handleRadiusPx.coerceAtMost(containerWidthPx / 2f)+ val verticalPointInset = handleRadiusPx.coerceAtMost(containerHeightPx / 2f)+ val containerBounds = Rect(+ left = horizontalPointInset,+ top = verticalPointInset,+ right = containerWidthPx - horizontalPointInset,+ bottom = containerHeightPx - verticalPointInset+ )+ val selectedCornerIndex = (dragTarget as? DragTarget.Corner)?.index+ val selectedEdge = dragTarget as? DragTarget.Edge+ val cropPointsInitialized = drawPoints.size == CROP_POINTS_COUNT+ val pointScales = List(drawPoints.size) {+ animateFloatAsState(if (it == selectedCornerIndex) 1.4f else 1f)+ }+ val edgeScales = edgeIndices.map { (firstIndex, secondIndex) ->+ animateFloatAsState(+ if (selectedEdge?.firstIndex == firstIndex &&+ selectedEdge.secondIndex == secondIndex+ ) {+ 1.4f+ } else {+ 1f+ }+ )+ }++ LaunchedEffect(croppingTrigger, baseImageBounds, cropPointsInitialized) {+ if (croppingTrigger && cropPointsInitialized && baseImageBounds.hasPositiveSize()) {+ fun scaledPointsFor(size: IntSize): List<Offset> {+ val widthScale = size.width.toFloat() / baseImageBounds.width.coerceAtLeast(1f)+ val heightScale =+ size.height.toFloat() / baseImageBounds.height.coerceAtLeast(1f)++ return drawPoints.map {+ val untransformed = it.untransform(+ center = baseImageBounds.center,+ scale = imageScale,+ translation = imageTranslation+ )+ Offset(+ x = ((untransformed.x - baseImageBounds.left) * widthScale).roundToInt()+ .coerceIn(0, size.width).toFloat(),+ y = ((untransformed.y - baseImageBounds.top) * heightScale).roundToInt()+ .coerceIn(0, size.height).toFloat()+ )+ }+ }++ // ClearPDF: report corners normalised to 0..1 of the bitmap so the editor can+ // replay the warp non-destructively at any resolution (see FreeCrop.crop).+ val precision = 100_000+ onCropped(+ scaledPointsFor(IntSize(precision, precision)).map {+ Offset(it.x / precision, it.y / precision)+ }+ )+ }+ }++ Image(+ bitmap = imageBitmap,+ contentDescription = null,+ modifier = Modifier+ .padding(internalPaddingDp)+ .padding(contentPadding)+ .aspectRatio(bitmap.width / bitmap.height.toFloat())+ .onGloballyPositioned {+ val position = it.positionInParent()+ val newImageBounds = Rect(+ offset = position,+ size = it.size.toSize()+ )+ if (+ baseImageBounds.hasPositiveSize() &&+ baseImageBounds != newImageBounds+ ) {+ captureLayoutSnapshot()+ }+ baseImageBounds = newImageBounds+ }+ .graphicsLayer {+ scaleX = imageScale+ scaleY = imageScale+ translationX = imageTranslation.x+ translationY = imageTranslation.y+ },+ contentScale = ContentScale.FillBounds+ )++ LaunchedEffect(imageKey, baseImageBounds, viewportBounds) {+ if (baseImageBounds.hasPositiveSize() && viewportBounds.hasPositiveSize()) {+ transformAnimationJob?.cancel()+ transformAnimationJob = null+ dragTarget = DragTarget.None+ magnifierCenter = Offset.Unspecified+ attachState()+ val layoutSnapshot = pendingLayoutSnapshot+ ?: state.snapshotForLayoutChange()+ val restored = layoutSnapshot?.let { snapshot ->+ restoreFreeCornersCropSnapshot(+ snapshot = snapshot,+ imageBounds = baseImageBounds,+ viewportBounds = viewportBounds,+ coercePointsToImageArea = coercePointsToImageArea+ )+ }+ if (restored != null) {+ drawPoints = restored.points+ imageScale = restored.imageScale+ imageTranslation = restored.imageTranslation+ } else if (drawPoints.size != CROP_POINTS_COUNT) {+ val inset = internalPadding.coerceAtMost(+ minOf(baseImageBounds.width, baseImageBounds.height) / 4f+ )+ drawPoints = baseImageBounds.insetBy(inset).corners()+ imageScale = 1f+ imageTranslation = Offset.Zero+ }+ pendingLayoutSnapshot = null+ attachState()+ state.onCropperReady()+ }+ }++ fun currentPointBounds(): Rect = containerBounds++ fun Offset.coerceToPointBounds(): Offset = currentPointBounds().let { bounds ->+ coerceIn(+ horizontalRange = bounds.left..bounds.right,+ verticalRange = bounds.top..bounds.bottom+ )+ }++ fun Offset.coerceDragAmountFor(points: List<Offset>): Offset {+ val bounds = currentPointBounds()+ val horizontalRange = bounds.left..bounds.right+ val verticalRange = bounds.top..bounds.bottom+ var minX = Float.NEGATIVE_INFINITY+ var maxX = Float.POSITIVE_INFINITY+ var minY = Float.NEGATIVE_INFINITY+ var maxY = Float.POSITIVE_INFINITY++ points.forEach { point ->+ minX = minX.coerceAtLeast(horizontalRange.start - point.x)+ maxX = maxX.coerceAtMost(horizontalRange.endInclusive - point.x)+ minY = minY.coerceAtLeast(verticalRange.start - point.y)+ maxY = maxY.coerceAtMost(verticalRange.endInclusive - point.y)+ }++ return Offset(+ x = x.coerceIn(minX, maxX),+ y = y.coerceIn(minY, maxY)+ )+ }++ LaunchedEffect(coercePointsToImageArea) {+ transformAnimationJob?.cancel()+ }++ LaunchedEffect(drawPoints, coercePointsToImageArea, dragTarget) {+ transformAnimationJob?.cancel()+ if (!coercePointsToImageArea ||+ dragTarget != DragTarget.None ||+ drawPoints.size != CROP_POINTS_COUNT ||+ !baseImageBounds.hasPositiveSize()+ ) {+ return@LaunchedEffect+ }++ val targetScale = imageScale.coerceAtLeast(+ calculateMinimumScale(+ cropBounds = drawPoints.boundingRect(),+ imageBounds = baseImageBounds+ )+ )+ val targetTranslation = coerceImageTranslation(+ translation = imageTranslation,+ scale = targetScale,+ imageBounds = baseImageBounds,+ cropBounds = drawPoints.boundingRect(),+ coerceToCrop = true+ )++ if (targetScale != imageScale || targetTranslation != imageTranslation) {+ transformAnimationJob = scope.launch {+ animateTransformTo(+ startScale = imageScale,+ startTranslation = imageTranslation,+ targetScale = targetScale,+ targetTranslation = targetTranslation,+ onUpdate = ::updateImageTransform+ )+ endTransformation()+ }+ } else {+ endTransformation()+ }+ }++ Canvas(+ modifier = Modifier+ .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)+ .size(maxWidth, maxHeight)+ .then(+ if (showMagnifier && magnifierCenter.isSpecified) {+ Modifier.magnifier(+ magnifierCenter = {+ magnifierCenter - Offset(0f, 100.dp.toPx())+ },+ sourceCenter = {+ magnifierCenter+ },+ size = DpSize(100.dp, 100.dp),+ cornerRadius = 50.dp,+ elevation = 2.dp+ )+ } else {+ Modifier+ }+ )+ .pointerInput(+ contentPadding,+ coercePointsToImageArea,+ handleRadiusPx,+ strictCornerTouchRadiusPx,+ cornerTouchRadiusPx,+ edgeTouchRadiusPx,+ imageKey,+ showMagnifier,+ isOverlayDraggable,+ containerBounds,+ baseImageBounds+ ) {+ detectCropDragGestures(+ hitTest = { offset ->+ findDragTarget(+ points = drawPoints,+ touchPosition = offset,+ touchRadii = TouchRadii(+ strictCorner = strictCornerTouchRadiusPx,+ corner = cornerTouchRadiusPx,+ edge = edgeTouchRadiusPx+ ),+ isOverlayDraggable = isOverlayDraggable+ )+ },+ onDragStart = { target ->+ beginTransformation()+ dragTarget = target+ magnifierCenter =+ if (showMagnifier && dragTarget != DragTarget.None) {+ dragTarget.focusPoint(drawPoints)+ } else {+ Offset.Unspecified+ }+ },+ onDrag = { dragAmount ->+ val selectedIndices = dragTarget.pointIndices+ val selectedPoints = selectedIndices.mapNotNull { index ->+ drawPoints.getOrNull(index)+ }+ val coercedDragAmount = dragAmount.coerceDragAmountFor(selectedPoints)++ if (selectedIndices.isNotEmpty()) {+ drawPoints = drawPoints+ .toMutableList()+ .apply {+ selectedIndices.forEach { index ->+ this[index] = this[index]+ .plus(coercedDragAmount)+ .coerceToPointBounds()+ }+ }++ if (showMagnifier) {+ magnifierCenter = dragTarget.focusPoint(drawPoints)+ }+ }+ },+ onDragEnd = {+ dragTarget = DragTarget.None+ magnifierCenter = Offset.Unspecified+ if (!coercePointsToImageArea) {+ endTransformation()+ }+ },+ onDragCancel = {+ dragTarget = DragTarget.None+ magnifierCenter = Offset.Unspecified+ if (!coercePointsToImageArea) {+ endTransformation()+ }+ }+ )+ }+ ) {+ if (drawPoints.size != CROP_POINTS_COUNT) return@Canvas++ val (x, y) = drawPoints[0]+ val (x1, y1) = drawPoints[1]+ val (x2, y2) = drawPoints[2]+ val (x3, y3) = drawPoints[3]++ val framePath = Path().apply {+ moveTo(x, y)+ lineTo(x1, y1)+ lineTo(x2, y2)+ lineTo(x3, y3)+ close()+ }++ drawRect(overlayColor)++ drawPath(+ path = framePath,+ brush = SolidColor(Color.Transparent),+ blendMode = BlendMode.Clear+ )++ clipPath(framePath) {+ drawPerspectiveGrid(+ points = drawPoints,+ color = gridColor,+ strokeWidth = frameStrokeWidthPx+ )+ }++ drawPath(+ path = framePath,+ brush = SolidColor(gridColor),+ style = Stroke(frameStrokeWidthPx)+ )++ edgeIndices.forEachIndexed { index, (firstIndex, secondIndex) ->+ val firstPoint = drawPoints[firstIndex]+ val secondPoint = drawPoints[secondIndex]+ val edgeVector = secondPoint - firstPoint+ val edgeLength = edgeVector.getDistance()+ if (edgeLength > 0f) {+ val center = (firstPoint + secondPoint) / 2f+ val halfHandleLength = minOf(+ handleRadiusPx * MIDDLE_HANDLE_LENGTH_MULTIPLIER *+ edgeScales[index].value,+ edgeLength / 2f+ )+ val handleVector = edgeVector / edgeLength * halfHandleLength++ drawLine(+ color = handlesColor,+ start = center - handleVector,+ end = center + handleVector,+ strokeWidth = middleHandleStrokeWidthPx * edgeScales[index].value,+ cap = StrokeCap.Round+ )+ }+ }++ drawPoints.forEachIndexed { index, point ->+ val scale = pointScales[index].value++ drawCircle(+ color = handlesColor,+ center = point,+ radius = handleRadiusPx * scale+ )+ }+ }+ }+}++private sealed class DragTarget {+ object None : DragTarget()+ object Overlay : DragTarget()+ data class Corner(val index: Int) : DragTarget()+ data class Edge(+ val firstIndex: Int,+ val secondIndex: Int+ ) : DragTarget()++ val pointIndices: List<Int>+ get() = when (this) {+ is Corner -> listOf(index)+ is Edge -> listOf(firstIndex, secondIndex)+ Overlay -> pointsIndices+ None -> emptyList()+ }++ private companion object {+ val pointsIndices = listOf(0, 1, 2, 3)+ }+}++private suspend fun PointerInputScope.detectCropDragGestures(+ hitTest: (Offset) -> DragTarget,+ onDragStart: (DragTarget) -> Unit,+ onDrag: (Offset) -> Unit,+ onDragEnd: () -> Unit,+ onDragCancel: () -> Unit+) {+ var lastTapUpTime: Long? = null+ var lastTapPosition = Offset.Unspecified++ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ val timeSinceLastTap = lastTapUpTime?.let { down.uptimeMillis - it }+ val isSecondTap = lastTapPosition.isSpecified &&+ timeSinceLastTap != null &&+ timeSinceLastTap >= viewConfiguration.doubleTapMinTimeMillis &&+ timeSinceLastTap <= viewConfiguration.doubleTapTimeoutMillis &&+ (down.position - lastTapPosition).getDistance() <=+ viewConfiguration.touchSlop * DOUBLE_TAP_POSITION_TOLERANCE_MULTIPLIER+ val candidate = if (isSecondTap) DragTarget.None else hitTest(down.position)++ var accumulatedDrag = Offset.Zero+ var dragStarted = false+ var isCanceled = false+ var isMultiTouch = false+ var upTime = down.uptimeMillis+ var upPosition = down.position++ do {+ val event = awaitPointerEvent(PointerEventPass.Main)+ if (event.changes.size > 1) {+ isMultiTouch = true+ isCanceled = dragStarted+ }++ val change = event.changes.firstOrNull { it.id == down.id }+ if (change == null) {+ isCanceled = dragStarted+ break+ }++ upTime = change.uptimeMillis+ upPosition = change.position++ if (change.isConsumed) {+ isCanceled = dragStarted+ break+ }++ val dragAmount = change.positionChange()+ if (!isMultiTouch && candidate != DragTarget.None && dragAmount != Offset.Zero) {+ accumulatedDrag += dragAmount+ if (dragStarted || accumulatedDrag.getDistance() > viewConfiguration.touchSlop) {+ val appliedDrag = if (dragStarted) dragAmount else accumulatedDrag+ if (!dragStarted) {+ dragStarted = true+ onDragStart(candidate)+ }+ change.consume()+ onDrag(appliedDrag)+ accumulatedDrag = Offset.Zero+ }+ }+ } while (change.pressed)++ if (dragStarted) {+ if (isCanceled) onDragCancel() else onDragEnd()+ lastTapUpTime = null+ lastTapPosition = Offset.Unspecified+ } else {+ if (isSecondTap || isMultiTouch || upTime - down.uptimeMillis >+ viewConfiguration.longPressTimeoutMillis+ ) {+ lastTapUpTime = null+ lastTapPosition = Offset.Unspecified+ } else {+ lastTapUpTime = upTime+ lastTapPosition = upPosition+ }+ }+ }+}++private data class FreeCornersCropperImageKey(+ val bitmap: Bitmap,+ val generationId: Int+)++private data class ImageTransform(+ val translation: Offset+)++private suspend fun PointerInputScope.detectOneFingerZoomGestures(+ onDoubleTap: (Offset) -> Unit,+ onZoomStart: () -> Unit,+ onZoom: (centroid: Offset, zoom: Float) -> Unit,+ onZoomEnd: () -> Unit+) = awaitEachGesture {+ val firstDown = awaitFirstDown(requireUnconsumed = false)+ var firstUp = firstDown+ var hasMoved = false+ var isMultiTouch = false+ var isCanceled = false++ do {+ val event = awaitPointerEvent()+ if (event.changes.fastAny { it.isConsumed }) {+ isCanceled = true+ break+ }+ if (event.changes.fastAny { it.positionChanged() }) {+ hasMoved = true+ }+ if (event.changes.size > 1) {+ isMultiTouch = true+ }+ firstUp = event.changes.first()+ } while (event.changes.fastAny { it.pressed })++ val isTap = !hasMoved &&+ !isMultiTouch &&+ !isCanceled &&+ firstUp.uptimeMillis - firstDown.uptimeMillis <=+ viewConfiguration.longPressTimeoutMillis++ if (isTap) {+ val secondDown = awaitSecondDown(firstUp)+ if (secondDown != null) {+ var secondUp: PointerInputChange = secondDown+ var isZooming = false+ var isSecondMultiTouch = false+ var isSecondCanceled = false++ do {+ val event = awaitPointerEvent(PointerEventPass.Initial)+ if (event.changes.fastAny { it.isConsumed }) {+ isSecondCanceled = true+ break+ }++ if (event.changes.size > 1) {+ isSecondMultiTouch = true+ }++ val panChange = event.calculatePan()+ if (!isSecondMultiTouch && panChange != Offset.Zero) {+ if (!isZooming) {+ onZoomStart()+ }+ isZooming = true+ val zoomChange = exp(panChange.y * ONE_FINGER_ZOOM_SENSITIVITY)+ if (zoomChange != 1f) {+ onZoom(+ event.calculateCentroid(useCurrent = true),+ zoomChange+ )+ }+ event.changes.fastForEach {+ if (it.positionChanged()) {+ it.consume()+ }+ }+ }+ secondUp = event.changes.first()+ } while (event.changes.fastAny { it.pressed })++ if (isZooming && !isSecondMultiTouch && !isSecondCanceled) {+ onZoomEnd()+ } else if (!isSecondMultiTouch &&+ !isSecondCanceled &&+ secondUp.uptimeMillis - secondDown.uptimeMillis <=+ viewConfiguration.longPressTimeoutMillis+ ) {+ onDoubleTap(secondUp.position)+ }+ }+ }+}++private suspend fun AwaitPointerEventScope.awaitSecondDown(+ firstUp: PointerInputChange+): PointerInputChange? = withTimeoutOrNull(viewConfiguration.doubleTapTimeoutMillis) {+ val minUptime = firstUp.uptimeMillis + viewConfiguration.doubleTapMinTimeMillis+ var change: PointerInputChange+ do {+ change = awaitFirstDown()+ } while (change.uptimeMillis < minUptime)+ change+}++private fun calculateMinimumScale(+ cropBounds: Rect,+ imageBounds: Rect+): Float {+ if (cropBounds == Rect.Zero || !imageBounds.hasPositiveSize()) return 1f++ return maxOf(+ cropBounds.width / imageBounds.width,+ cropBounds.height / imageBounds.height+ ).coerceIn(MINIMUM_CROP_ZOOM, MAX_ZOOM)+}++private fun calculateTransformAfterZoom(+ currentScale: Float,+ currentTranslation: Offset,+ targetScale: Float,+ centroid: Offset,+ transformCenter: Offset+): ImageTransform {+ if (currentScale <= 0f || !centroid.isSpecified || !transformCenter.isSpecified) {+ return ImageTransform(currentTranslation)+ }++ val scaleChange = targetScale / currentScale+ return ImageTransform(+ translation = currentTranslation ++ (centroid - transformCenter - currentTranslation) * (1f - scaleChange)+ )+}++private fun coerceImageTranslation(+ translation: Offset,+ scale: Float,+ imageBounds: Rect,+ cropBounds: Rect,+ coerceToCrop: Boolean+): Offset {+ if (!imageBounds.hasPositiveSize()) return Offset.Zero++ val scaledImageBounds = imageBounds.transform(+ center = imageBounds.center,+ scale = scale,+ translation = Offset.Zero+ )++ val horizontalRange: ClosedFloatingPointRange<Float>+ val verticalRange: ClosedFloatingPointRange<Float>++ if (coerceToCrop && cropBounds != Rect.Zero) {+ val minTranslationX = cropBounds.right - scaledImageBounds.right+ val maxTranslationX = cropBounds.left - scaledImageBounds.left+ val minTranslationY = cropBounds.bottom - scaledImageBounds.bottom+ val maxTranslationY = cropBounds.top - scaledImageBounds.top+ horizontalRange = minTranslationX..maxTranslationX+ verticalRange = minTranslationY..maxTranslationY+ } else {+ val horizontalPan = ((scaledImageBounds.width - imageBounds.width) / 2f)+ .coerceAtLeast(0f)+ val verticalPan = ((scaledImageBounds.height - imageBounds.height) / 2f)+ .coerceAtLeast(0f)+ horizontalRange = -horizontalPan..horizontalPan+ verticalRange = -verticalPan..verticalPan+ }++ return Offset(+ x = translation.x.coerceInOrCenter(horizontalRange),+ y = translation.y.coerceInOrCenter(verticalRange)+ )+}++private suspend fun animateTransformTo(+ startScale: Float,+ startTranslation: Offset,+ targetScale: Float,+ targetTranslation: Offset,+ onUpdate: (scale: Float, translation: Offset) -> Unit+) {+ animate(+ initialValue = 0f,+ targetValue = 1f,+ animationSpec = spring()+ ) { progress, _ ->+ onUpdate(+ startScale + (targetScale - startScale) * progress,+ startTranslation + (targetTranslation - startTranslation) * progress+ )+ }+}++private fun findDragTarget(+ points: List<Offset>,+ touchPosition: Offset,+ touchRadii: TouchRadii,+ isOverlayDraggable: Boolean+): DragTarget {+ val touchedStrictCornerIndex = findTouchedCornerIndex(+ points = points,+ touchPosition = touchPosition,+ distanceThresholdSquared = touchRadii.strictCorner.square()+ )++ if (touchedStrictCornerIndex != null) return DragTarget.Corner(touchedStrictCornerIndex)++ val touchedEdge = edgeIndices+ .mapNotNull { (firstIndex, secondIndex) ->+ val firstPoint = points.getOrNull(firstIndex) ?: return@mapNotNull null+ val secondPoint = points.getOrNull(secondIndex) ?: return@mapNotNull null+ val edgeTouch = touchPosition.edgeTouch(firstPoint, secondPoint)++ if (edgeTouch.projection in EdgeTouchProjectionRange &&+ edgeTouch.distanceSquared < touchRadii.edge.square()+ ) {+ DragTarget.Edge(firstIndex, secondIndex) to edgeTouch.distanceSquared+ } else {+ null+ }+ }+ .minByOrNull { it.second }+ ?.first++ if (touchedEdge != null) return touchedEdge++ val touchedCornerIndex = findTouchedCornerIndex(+ points = points,+ touchPosition = touchPosition,+ distanceThresholdSquared = touchRadii.corner.square()+ )++ if (touchedCornerIndex != null) return DragTarget.Corner(touchedCornerIndex)++ return if (isOverlayDraggable && touchPosition.isInsidePolygon(points)) {+ DragTarget.Overlay+ } else {+ DragTarget.None+ }+}++private fun DragTarget.focusPoint(points: List<Offset>): Offset {+ return when (this) {+ is DragTarget.Corner -> points.getOrNull(index) ?: Offset.Unspecified+ is DragTarget.Edge -> {+ val firstPoint = points.getOrNull(firstIndex) ?: return Offset.Unspecified+ val secondPoint = points.getOrNull(secondIndex) ?: return Offset.Unspecified+ Offset(+ x = (firstPoint.x + secondPoint.x) / 2f,+ y = (firstPoint.y + secondPoint.y) / 2f+ )+ }++ DragTarget.Overlay ->+ points+ .takeIf { it.isNotEmpty() }+ ?.reduce(Offset::plus)+ ?.div(points.size.toFloat())+ ?: Offset.Unspecified++ DragTarget.None -> Offset.Unspecified+ }+}++private fun findTouchedCornerIndex(+ points: List<Offset>,+ touchPosition: Offset,+ distanceThresholdSquared: Float+): Int? = points+ .mapIndexedNotNull { index, point ->+ val distanceSquared = point.minus(touchPosition).getDistanceSquared()+ if (distanceSquared < distanceThresholdSquared) {+ index to distanceSquared+ } else {+ null+ }+ }+ .minByOrNull { it.second }+ ?.first++private fun Float.square(): Float = this * this++private data class EdgeTouch(+ val distanceSquared: Float,+ val projection: Float+)++private data class TouchRadii(+ val strictCorner: Float,+ val corner: Float,+ val edge: Float+)++private fun Offset.edgeTouch(start: Offset, end: Offset): EdgeTouch {+ val segmentX = end.x - start.x+ val segmentY = end.y - start.y+ val lengthSquared = segmentX * segmentX + segmentY * segmentY++ if (lengthSquared == 0f) {+ return EdgeTouch(+ distanceSquared = minus(start).getDistanceSquared(),+ projection = 0f+ )+ }++ val projection = (((x - start.x) * segmentX + (y - start.y) * segmentY) / lengthSquared)+ .coerceIn(0f, 1f)+ val closestPoint = Offset(+ x = start.x + projection * segmentX,+ y = start.y + projection * segmentY+ )++ return EdgeTouch(+ distanceSquared = minus(closestPoint).getDistanceSquared(),+ projection = projection+ )+}++private fun Offset.isInsidePolygon(points: List<Offset>): Boolean {+ if (points.size < 3) return false++ var isInside = false+ var previous = points.last()+ points.forEach { current ->+ if ((current.y > y) != (previous.y > y)) {+ val intersectionX = (previous.x - current.x) * (y - current.y) /+ (previous.y - current.y) + current.x+ if (x < intersectionX) isInside = !isInside+ }+ previous = current+ }+ return isInside+}++private fun List<Offset>.boundingRect(): Rect {+ if (isEmpty()) return Rect.Zero++ return Rect(+ left = minOf { it.x },+ top = minOf { it.y },+ right = maxOf { it.x },+ bottom = maxOf { it.y }+ )+}++private fun Rect.hasPositiveSize(): Boolean = width > 0f && height > 0f++private fun Rect.insetBy(value: Float): Rect = Rect(+ left = left + value,+ top = top + value,+ right = right - value,+ bottom = bottom - value+)++private fun Rect.corners(): List<Offset> = listOf(+ topLeft,+ topRight,+ bottomRight,+ bottomLeft+)++private fun Rect.transform(+ center: Offset,+ scale: Float,+ translation: Offset+): Rect = Rect(+ topLeft = topLeft.transform(center, scale, translation),+ bottomRight = bottomRight.transform(center, scale, translation)+)++private fun Offset.transform(+ center: Offset,+ scale: Float,+ translation: Offset+): Offset = center + (this - center) * scale + translation++private fun Offset.untransform(+ center: Offset,+ scale: Float,+ translation: Offset+): Offset = center + (this - center - translation) / scale++internal data class RestoredFreeCornersCropSnapshot(+ val points: List<Offset>,+ val imageScale: Float,+ val imageTranslation: Offset+)++internal fun captureFreeCornersCropSnapshot(+ points: List<Offset>,+ imageBounds: Rect,+ imageScale: Float,+ imageTranslation: Offset,+ viewportBounds: Rect+): FreeCornersCropSnapshot? {+ if (+ points.size != CROP_POINTS_COUNT ||+ !imageBounds.hasPositiveSize() ||+ imageScale <= 0f ||+ !viewportBounds.hasPositiveSize()+ ) {+ return null+ }++ val normalizedPoints = points.map { point ->+ val untransformed = point.untransform(+ center = imageBounds.center,+ scale = imageScale,+ translation = imageTranslation+ )+ Offset(+ x = (untransformed.x - imageBounds.left) / imageBounds.width,+ y = (untransformed.y - imageBounds.top) / imageBounds.height+ )+ }+ val cropBounds = points.boundingRect()+ return FreeCornersCropSnapshot(+ normalizedPoints = normalizedPoints,+ normalizedViewportCenter = Offset(+ x = (cropBounds.center.x - viewportBounds.left) / viewportBounds.width,+ y = (cropBounds.center.y - viewportBounds.top) / viewportBounds.height+ ),+ viewportFillFraction = maxOf(+ cropBounds.width / viewportBounds.width,+ cropBounds.height / viewportBounds.height+ ).coerceIn(MIN_VIEWPORT_FILL_FRACTION, 1f)+ )+}++internal fun restoreFreeCornersCropSnapshot(+ snapshot: FreeCornersCropSnapshot,+ imageBounds: Rect,+ viewportBounds: Rect,+ coercePointsToImageArea: Boolean = true+): RestoredFreeCornersCropSnapshot? {+ if (+ snapshot.normalizedPoints.size != CROP_POINTS_COUNT ||+ !imageBounds.hasPositiveSize() ||+ !viewportBounds.hasPositiveSize()+ ) {+ return null+ }++ val normalizedPoints = if (coercePointsToImageArea) {+ snapshot.normalizedPoints.map { point ->+ Offset(point.x.coerceIn(0f, 1f), point.y.coerceIn(0f, 1f))+ }+ } else {+ snapshot.normalizedPoints+ }+ val imagePoints = normalizedPoints.map { point ->+ Offset(+ x = imageBounds.left + point.x * imageBounds.width,+ y = imageBounds.top + point.y * imageBounds.height+ )+ }+ val imageCropBounds = imagePoints.boundingRect()+ if (!imageCropBounds.hasPositiveSize()) return null++ val fillFraction = snapshot.viewportFillFraction+ .coerceIn(MIN_VIEWPORT_FILL_FRACTION, 1f)+ val imageScale = minOf(+ viewportBounds.width * fillFraction / imageCropBounds.width,+ viewportBounds.height * fillFraction / imageCropBounds.height,+ MAX_ZOOM+ ).coerceAtLeast(MINIMUM_CROP_ZOOM)+ val scaledCropSize = imageCropBounds.size * imageScale+ val halfCropWidth = scaledCropSize.width / 2f+ val halfCropHeight = scaledCropSize.height / 2f+ val preferredCenter = Offset(+ x = viewportBounds.left ++ snapshot.normalizedViewportCenter.x * viewportBounds.width,+ y = viewportBounds.top ++ snapshot.normalizedViewportCenter.y * viewportBounds.height+ )+ val targetCenter = Offset(+ x = preferredCenter.x.coerceIn(+ viewportBounds.left + halfCropWidth,+ viewportBounds.right - halfCropWidth+ ),+ y = preferredCenter.y.coerceIn(+ viewportBounds.top + halfCropHeight,+ viewportBounds.bottom - halfCropHeight+ )+ )+ val imageTranslation = targetCenter - imageBounds.center -+ (imageCropBounds.center - imageBounds.center) * imageScale+ return RestoredFreeCornersCropSnapshot(+ points = imagePoints.map { point ->+ point.transform(+ center = imageBounds.center,+ scale = imageScale,+ translation = imageTranslation+ )+ },+ imageScale = imageScale,+ imageTranslation = imageTranslation+ )+}++private val edgeIndices = listOf(+ 0 to 1,+ 1 to 2,+ 2 to 3,+ 3 to 0+)++private val EdgeTouchProjectionRange = 0.20f..0.80f++private val MinStrictCornerTouchRadius = 22.dp+private val MinCornerTouchRadius = 30.dp+private val MinEdgeTouchRadius = 22.dp++private const val STRICT_CORNER_TOUCH_RADIUS_MULTIPLIER = 1.9f+private const val CORNER_TOUCH_RADIUS_MULTIPLIER = 3.2f+private const val EDGE_TOUCH_RADIUS_MULTIPLIER = 2.5f+private const val MIDDLE_HANDLE_LENGTH_MULTIPLIER = 1.5f+private val MiddleHandleStrokeWidth = 3.5.dp+private const val DOUBLE_TAP_POSITION_TOLERANCE_MULTIPLIER = 4f+private const val MINIMUM_CROP_ZOOM = 0.05f+private const val MIN_VIEWPORT_FILL_FRACTION = 0.1f+private const val CROP_POINTS_COUNT = 4+private const val MAX_ZOOM = 20f+private const val DEFAULT_DOUBLE_TAP_SCALE = 3f+private const val MIN_SCALE_GESTURE_RESISTANCE = 0.85f+private const val SCALE_COMPARISON_TOLERANCE = 0.01f+private const val ONE_FINGER_ZOOM_SENSITIVITY = 0.004f++private fun Offset.coerceIn(+ horizontalRange: ClosedRange<Float>,+ verticalRange: ClosedRange<Float>+) = Offset(this.x.coerceIn(horizontalRange), this.y.coerceIn(verticalRange))++private fun Float.coerceInOrCenter(range: ClosedFloatingPointRange<Float>): Float {+ return if (range.start <= range.endInclusive) {+ coerceIn(range)+ } else {+ (range.start + range.endInclusive) / 2f+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropperState.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropperState.ktnew file mode 100644index 0000000..453b93f--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/FreeCornersCropperState.kt@@ -0,0 +1,207 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.compose++import androidx.compose.runtime.Composable+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.geometry.Offset++private const val MaxHistorySize = 50++@Stable+class FreeCornersCropperState {+ var canUndo: Boolean by mutableStateOf(false)+ private set++ var canRedo: Boolean by mutableStateOf(false)+ private set++ private var imageKey: Any? = null+ private var attachmentKey: Any? = null+ private var captureSnapshot: (() -> FreeCornersCropSnapshot?)? = null+ private var restoreSnapshot: ((FreeCornersCropSnapshot) -> Unit)? = null+ private var pendingSnapshot: FreeCornersCropSnapshot? = null+ private var currentSnapshot: FreeCornersCropSnapshot? = null+ private var restoreCurrentSnapshotOnCropperReady = false+ private val undoHistory = ArrayDeque<FreeCornersCropSnapshot>()+ private val redoHistory = ArrayDeque<FreeCornersCropSnapshot>()++ fun undo() {+ endTransformation()+ val current = currentSnapshot ?: captureSnapshot?.invoke() ?: return+ val previous = undoHistory.removeLastOrNull() ?: return++ redoHistory.addLast(current)+ redoHistory.trimToMaxSize()+ currentSnapshot = previous+ restoreSnapshot?.invoke(previous)+ updateAvailability()+ }++ fun redo() {+ endTransformation()+ val current = currentSnapshot ?: captureSnapshot?.invoke() ?: return+ val next = redoHistory.removeLastOrNull() ?: return++ undoHistory.addLast(current)+ undoHistory.trimToMaxSize()+ currentSnapshot = next+ restoreSnapshot?.invoke(next)+ updateAvailability()+ }++ fun beginTransformation() {+ restoreCurrentSnapshotOnCropperReady = false+ if (pendingSnapshot == null) {+ pendingSnapshot = captureSnapshot?.invoke()+ }+ }++ fun endTransformation(): Boolean {+ val before = pendingSnapshot ?: return false+ pendingSnapshot = null+ val after = captureSnapshot?.invoke() ?: return false+ currentSnapshot = after++ if (before != after) {+ undoHistory.addLast(before)+ undoHistory.trimToMaxSize()+ redoHistory.clear()+ updateAvailability()+ return true+ }+ return false+ }++ fun discardPendingTransformation() {+ pendingSnapshot = null+ }++ fun prepareForReattachment(attachmentKey: Any? = null) {+ if (attachmentKey != null && this.attachmentKey !== attachmentKey) return+ if (restoreCurrentSnapshotOnCropperReady) return+ if (pendingSnapshot != null || currentSnapshot == null) {+ captureSnapshot?.invoke()?.let { currentSnapshot = it }+ }+ restoreCurrentSnapshotOnCropperReady = currentSnapshot != null+ }++ fun finishReattachment() {+ restoreCurrentSnapshotOnCropperReady = false+ }++ internal fun snapshotForLayoutChange(): FreeCornersCropSnapshot? {+ if (pendingSnapshot != null) {+ captureSnapshot?.invoke()?.let { currentSnapshot = it }+ }+ if (currentSnapshot == null) {+ currentSnapshot = captureSnapshot?.invoke()+ }+ return currentSnapshot+ }++ internal fun attach(+ attachmentKey: Any,+ imageKey: Any?,+ captureSnapshot: () -> FreeCornersCropSnapshot?,+ restoreSnapshot: (FreeCornersCropSnapshot) -> Unit+ ) {+ val imageChanged = this.imageKey != imageKey+ if (!imageChanged && this.attachmentKey != null && this.attachmentKey !== attachmentKey) {+ if (pendingSnapshot != null || currentSnapshot == null) {+ this.captureSnapshot?.invoke()?.let { currentSnapshot = it }+ }+ restoreCurrentSnapshotOnCropperReady = currentSnapshot != null+ pendingSnapshot = null+ }+ if (imageChanged) {+ this.imageKey = imageKey+ pendingSnapshot = null+ currentSnapshot = null+ restoreCurrentSnapshotOnCropperReady = false+ undoHistory.clear()+ redoHistory.clear()+ updateAvailability()+ }+ this.attachmentKey = attachmentKey+ this.captureSnapshot = captureSnapshot+ this.restoreSnapshot = restoreSnapshot+ }++ internal fun detach(attachmentKey: Any) {+ if (this.attachmentKey !== attachmentKey) return+ this.attachmentKey = null+ restoreCurrentSnapshotOnCropperReady = currentSnapshot != null+ captureSnapshot = null+ restoreSnapshot = null+ pendingSnapshot = null+ }++ internal fun onCropperReady() {+ if (restoreCurrentSnapshotOnCropperReady) {+ currentSnapshot?.let { restoreSnapshot?.invoke(it) }+ restoreCurrentSnapshotOnCropperReady = false+ } else if (currentSnapshot == null) {+ currentSnapshot = captureSnapshot?.invoke()+ }+ }++ fun clearHistory() {+ pendingSnapshot = null+ currentSnapshot = captureSnapshot?.invoke()+ restoreCurrentSnapshotOnCropperReady = false+ undoHistory.clear()+ redoHistory.clear()+ updateAvailability()+ }++ fun reset() {+ attachmentKey = null+ pendingSnapshot = null+ currentSnapshot = null+ restoreCurrentSnapshotOnCropperReady = false+ undoHistory.clear()+ redoHistory.clear()+ updateAvailability()+ }++ private fun updateAvailability() {+ canUndo = undoHistory.isNotEmpty()+ canRedo = redoHistory.isNotEmpty()+ }++ private fun ArrayDeque<FreeCornersCropSnapshot>.trimToMaxSize() {+ while (size > MaxHistorySize) removeFirst()+ }+}++@Composable+fun rememberFreeCornersCropperState(): FreeCornersCropperState = remember {+ FreeCornersCropperState()+}++internal data class FreeCornersCropSnapshot(+ val normalizedPoints: List<Offset>,+ val normalizedViewportCenter: Offset,+ val viewportFillFraction: Float+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/PerspectiveGrid.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/PerspectiveGrid.ktnew file mode 100644index 0000000..cba312f--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/compose/PerspectiveGrid.kt@@ -0,0 +1,153 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.compose++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import kotlin.math.abs++internal fun DrawScope.drawPerspectiveGrid(+ points: List<Offset>,+ color: Color,+ strokeWidth: Float+) {+ if (points.size != QUAD_POINTS_COUNT) return++ val transform = PerspectiveQuadTransform.from(points)++ fun pointAt(horizontalFraction: Float, verticalFraction: Float): Offset {+ return transform+ ?.map(horizontalFraction, verticalFraction)+ ?: points.bilinearPoint(horizontalFraction, verticalFraction)+ }++ for (index in 1 until GRID_DIVISIONS) {+ val fraction = index.toFloat() / GRID_DIVISIONS++ drawLine(+ color = color,+ start = pointAt(fraction, 0f),+ end = pointAt(fraction, 1f),+ strokeWidth = strokeWidth+ )+ drawLine(+ color = color,+ start = pointAt(0f, fraction),+ end = pointAt(1f, fraction),+ strokeWidth = strokeWidth+ )+ }+}++private data class PerspectiveQuadTransform(+ val horizontalX: Float,+ val verticalX: Float,+ val originX: Float,+ val horizontalY: Float,+ val verticalY: Float,+ val originY: Float,+ val horizontalPerspective: Float,+ val verticalPerspective: Float,+ val fallbackPoints: List<Offset>+) {+ fun map(horizontalFraction: Float, verticalFraction: Float): Offset {+ val denominator = horizontalPerspective * horizontalFraction ++ verticalPerspective * verticalFraction + HOMOGENEOUS_ORIGIN+ if (abs(denominator) <= TRANSFORM_EPSILON) {+ return fallbackPoints.bilinearPoint(horizontalFraction, verticalFraction)+ }++ val point = Offset(+ x = (horizontalX * horizontalFraction + verticalX * verticalFraction + originX) /+ denominator,+ y = (horizontalY * horizontalFraction + verticalY * verticalFraction + originY) /+ denominator+ )+ return point.takeIf { it.x.isFinite() && it.y.isFinite() }+ ?: fallbackPoints.bilinearPoint(horizontalFraction, verticalFraction)+ }++ companion object {+ fun from(points: List<Offset>): PerspectiveQuadTransform? {+ val topLeft = points[TOP_LEFT_INDEX]+ val topRight = points[TOP_RIGHT_INDEX]+ val bottomRight = points[BOTTOM_RIGHT_INDEX]+ val bottomLeft = points[BOTTOM_LEFT_INDEX]++ val rightEdgeX = topRight.x - bottomRight.x+ val rightEdgeY = topRight.y - bottomRight.y+ val bottomEdgeX = bottomLeft.x - bottomRight.x+ val bottomEdgeY = bottomLeft.y - bottomRight.y+ val perspectiveX = topLeft.x - topRight.x + bottomRight.x - bottomLeft.x+ val perspectiveY = topLeft.y - topRight.y + bottomRight.y - bottomLeft.y+ val determinant = rightEdgeX * bottomEdgeY - bottomEdgeX * rightEdgeY++ if (abs(determinant) <= TRANSFORM_EPSILON) return null++ val horizontalPerspective =+ (perspectiveX * bottomEdgeY - bottomEdgeX * perspectiveY) / determinant+ val verticalPerspective =+ (rightEdgeX * perspectiveY - perspectiveX * rightEdgeY) / determinant+ val topRightDenominator = HOMOGENEOUS_ORIGIN + horizontalPerspective+ val bottomLeftDenominator = HOMOGENEOUS_ORIGIN + verticalPerspective+ val bottomRightDenominator =+ HOMOGENEOUS_ORIGIN + horizontalPerspective + verticalPerspective+ val minimumDenominator = minOf(+ topRightDenominator,+ bottomLeftDenominator,+ bottomRightDenominator+ )++ if (minimumDenominator <= TRANSFORM_EPSILON) return null++ return PerspectiveQuadTransform(+ horizontalX = topRight.x - topLeft.x + horizontalPerspective * topRight.x,+ verticalX = bottomLeft.x - topLeft.x + verticalPerspective * bottomLeft.x,+ originX = topLeft.x,+ horizontalY = topRight.y - topLeft.y + horizontalPerspective * topRight.y,+ verticalY = bottomLeft.y - topLeft.y + verticalPerspective * bottomLeft.y,+ originY = topLeft.y,+ horizontalPerspective = horizontalPerspective,+ verticalPerspective = verticalPerspective,+ fallbackPoints = points+ )+ }+ }+}++private fun List<Offset>.bilinearPoint(+ horizontalFraction: Float,+ verticalFraction: Float+): Offset {+ val top = this[TOP_LEFT_INDEX] ++ (this[TOP_RIGHT_INDEX] - this[TOP_LEFT_INDEX]) * horizontalFraction+ val bottom = this[BOTTOM_LEFT_INDEX] ++ (this[BOTTOM_RIGHT_INDEX] - this[BOTTOM_LEFT_INDEX]) * horizontalFraction+ return top + (bottom - top) * verticalFraction+}++private const val QUAD_POINTS_COUNT = 4+private const val GRID_DIVISIONS = 3+private const val TRANSFORM_EPSILON = 0.0001f+private const val HOMOGENEOUS_ORIGIN = 1f+private const val TOP_LEFT_INDEX = 0+private const val TOP_RIGHT_INDEX = 1+private const val BOTTOM_RIGHT_INDEX = 2+private const val BOTTOM_LEFT_INDEX = 3diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/model/Quad.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/model/Quad.ktnew file mode 100644index 0000000..357bb11--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/freecorners/model/Quad.kt@@ -0,0 +1,32 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.freecorners.model++import android.graphics.PointF+import kotlin.math.hypot++class Quad(+ val topLeftCorner: PointF,+ val topRightCorner: PointF,+ val bottomRightCorner: PointF,+ val bottomLeftCorner: PointF+)++// ClearPDF: OpenCV Point helpers replaced with a plain PointF distance.+fun PointF.distance(point: PointF): Float = hypot(point.x - x, point.y - y)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/AwaitPointerMotionEvent.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/AwaitPointerMotionEvent.ktnew file mode 100644index 0000000..5cb7421--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/AwaitPointerMotionEvent.kt@@ -0,0 +1,240 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.gesture++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEvent+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.PointerEventPass.Final+import androidx.compose.ui.input.pointer.PointerEventPass.Initial+import androidx.compose.ui.input.pointer.PointerEventPass.Main+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.PointerInputScope+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Reads [awaitFirstDown], and [AwaitPointerEventScope.awaitPointerEvent] to+ * get [PointerInputChange] and motion event states+ * [onDown], [onMove], and [onUp].+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove one or multiple pointers are being moved on screen.+ * @param onUp last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ */+suspend fun PointerInputScope.detectMotionEvents(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (PointerInputChange) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main+) {+ coroutineScope {+ awaitEachGesture {+ // Wait for at least one pointer to press down, and set first contact position+ val down: PointerInputChange = awaitFirstDown(requireUnconsumed)+++ var pointer = down+ // Main pointer is the one that is down initially+ var pointerId = down.id++ // If a move event is followed fast enough down is skipped, especially by Canvas+ // to prevent it we add delay after first touch+ var waitedAfterDown = false++ launch {+ delay(delayAfterDownInMillis)+ onDown(down)+ waitedAfterDown = true+ }++ while (true) {++ val event: PointerEvent = awaitPointerEvent(pass)++ val anyPressed = event.changes.any { it.pressed }++ // There are at least one pointer pressed+ if (anyPressed) {+ // Get pointer that is down, if first pointer is up+ // get another and use it if other pointers are also down+ // event.changes.first() doesn't return same order+ val pointerInputChange =+ event.changes.firstOrNull { it.id == pointerId }+ ?: event.changes.first()++ // Next time will check same pointer with this id+ pointerId = pointerInputChange.id+ pointer = pointerInputChange++ if (waitedAfterDown) {+ onMove(pointer)+ }+ } else {+ // All of the pointers are up+ onUp(pointer)+ break+ }+ }+ }+ }+}++/**+ * Reads [awaitFirstDown], and [AwaitPointerEventScope.awaitPointerEvent] to+ * get [PointerInputChange] and motion event states+ * [onDown], [onMove], and [onUp]. Unlike overload of this function [onMove] returns+ * list of [PointerInputChange] to get data about all pointers that are on the screen.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove one or multiple pointers are being moved on screen.+ * @param onUp last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ */+suspend fun PointerInputScope.detectMotionEventsAsList(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (List<PointerInputChange>) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main+) {++ coroutineScope {+ awaitEachGesture {+ // Wait for at least one pointer to press down, and set first contact position+ val down: PointerInputChange = awaitFirstDown(requireUnconsumed)+ onDown(down)++ var pointer = down+ // Main pointer is the one that is down initially+ var pointerId = down.id++ // If a move event is followed fast enough down is skipped, especially by Canvas+ // to prevent it we add delay after first touch+ var waitedAfterDown = false++ launch {+ delay(delayAfterDownInMillis)+ waitedAfterDown = true+ }++ while (true) {++ val event: PointerEvent = awaitPointerEvent(pass)++ val anyPressed = event.changes.any { it.pressed }++ // There are at least one pointer pressed+ if (anyPressed) {+ // Get pointer that is down, if first pointer is up+ // get another and use it if other pointers are also down+ // event.changes.first() doesn't return same order+ val pointerInputChange =+ event.changes.firstOrNull { it.id == pointerId }+ ?: event.changes.first()++ // Next time will check same pointer with this id+ pointerId = pointerInputChange.id+ pointer = pointerInputChange++ if (waitedAfterDown) {+ onMove(event.changes)+ }++ } else {+ // All of the pointers are up+ onUp(pointer)+ break+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/PointerMotionModifier.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/PointerMotionModifier.ktnew file mode 100644index 0000000..1ce5cac--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/PointerMotionModifier.kt@@ -0,0 +1,447 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++@file:Suppress("unused")++package com.chethan616.clearpdf.imageeditor.thirdparty.gesture++import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.ui.Modifier+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.PointerEventPass.Final+import androidx.compose.ui.input.pointer.PointerEventPass.Initial+import androidx.compose.ui.input.pointer.PointerEventPass.Main+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.pointerInput++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with a different [key1].+ */+fun Modifier.pointerMotionEvents(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (PointerInputChange) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ key1: Any? = Unit+) = this.then(+ Modifier.pointerInput(key1) {+ detectMotionEvents(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with a different [key1] or [key2].+ */+fun Modifier.pointerMotionEvents(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (PointerInputChange) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ key1: Any?,+ key2: Any?+) = this.then(+ Modifier.pointerInput(key1, key2) {+ detectMotionEvents(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with any different [keys].+ */+fun Modifier.pointerMotionEvents(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (PointerInputChange) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ vararg keys: Any?,+) = this.then(+ Modifier.pointerInput(*keys) {+ detectMotionEvents(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with a different [key1].+ */+fun Modifier.pointerMotionEventList(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (List<PointerInputChange>) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ key1: Any? = Unit+) = this.then(+ Modifier.pointerInput(key1) {+ detectMotionEventsAsList(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with a different [key1] or [key2].+ */+fun Modifier.pointerMotionEventList(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (List<PointerInputChange>) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ key1: Any? = Unit,+ key2: Any? = Unit+) = this.then(+ Modifier.pointerInput(key1, key2) {+ detectMotionEventsAsList(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)++/**+ * Create a modifier for processing pointer motion input within the region of the modified element.+ *+ * After [AwaitPointerEventScope.awaitFirstDown] returned a [PointerInputChange] then+ * [onDown] is called at first pointer contact.+ * Moving any pointer causes [AwaitPointerEventScope.awaitPointerEvent] then [onMove] is called.+ * When last pointer is up [onUp] is called.+ *+ * To prevent other pointer functions that call [awaitFirstDown]+ * or [AwaitPointerEventScope.awaitPointerEvent]+ * (scroll, swipe, detect functions)+ * receiving changes call [PointerInputChange.consume] in [onMove] or call+ * [PointerInputChange.consume] in [onDown] to prevent events+ * that check first pointer interaction.+ *+ * @param onDown is invoked when first pointer is down initially.+ * @param onMove is invoked when one or multiple pointers are being moved on screen.+ * @param onUp is invoked when last pointer is up+ * @param delayAfterDownInMillis is optional delay after [onDown] This delay might be+ * required Composables like **Canvas** to process [onDown] before [onMove]+ * @param requireUnconsumed is `true` and the first+ * down is consumed in the [PointerEventPass.Main] pass, that gesture is ignored.+ * @param pass The enumeration of passes where [PointerInputChange]+ * traverses up and down the UI tree.+ *+ * PointerInputChanges traverse throw the hierarchy in the following passes:+ *+ * 1. [Initial]: Down the tree from ancestor to descendant.+ * 2. [Main]: Up the tree from descendant to ancestor.+ * 3. [Final]: Down the tree from ancestor to descendant.+ *+ * These passes serve the following purposes:+ *+ * 1. Initial: Allows ancestors to consume aspects of [PointerInputChange] before descendants.+ * This is where, for example, a scroller may block buttons from getting tapped by other fingers+ * once scrolling has started.+ * 2. Main: The primary pass where gesture filters should react to and consume aspects of+ * [PointerInputChange]s. This is the primary path where descendants will interact with+ * [PointerInputChange]s before parents. This allows for buttons to respond to a tap before a+ * container of the bottom to respond to a tap.+ * 3. Final: This pass is where children can learn what aspects of [PointerInputChange]s were+ * consumed by parents during the [Main] pass. For example, this is how a button determines that+ * it should no longer respond to fingers lifting off of it because a parent scroller has+ * consumed movement in a [PointerInputChange].+ *+ * The pointer input handling block will be cancelled and re-started when pointerInput+ * is recomposed with any different [keys].+ */+fun Modifier.pointerMotionEventList(+ onDown: (PointerInputChange) -> Unit = {},+ onMove: (List<PointerInputChange>) -> Unit = {},+ onUp: (PointerInputChange) -> Unit = {},+ delayAfterDownInMillis: Long = 0L,+ requireUnconsumed: Boolean = true,+ pass: PointerEventPass = Main,+ vararg keys: Any?+) = this.then(+ Modifier.pointerInput(*keys) {+ detectMotionEventsAsList(+ onDown,+ onMove,+ onUp,+ delayAfterDownInMillis,+ requireUnconsumed,+ pass+ )+ }+)diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/TransformGesture.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/TransformGesture.ktnew file mode 100644index 0000000..0a0822c--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/gesture/TransformGesture.kt@@ -0,0 +1,401 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.gesture++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.foundation.gestures.calculateCentroid+import androidx.compose.foundation.gestures.calculateCentroidSize+import androidx.compose.foundation.gestures.calculatePan+import androidx.compose.foundation.gestures.calculateRotation+import androidx.compose.foundation.gestures.calculateZoom+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerEventPass+import androidx.compose.ui.input.pointer.PointerInputChange+import androidx.compose.ui.input.pointer.PointerInputScope+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChanged+import androidx.compose.ui.util.fastAny+import kotlinx.coroutines.currentCoroutineContext+import kotlinx.coroutines.isActive+import kotlin.coroutines.cancellation.CancellationException+import kotlin.math.PI+import kotlin.math.abs++enum class PointerRequisite {+ LessThan, EqualTo, GreaterThan, None+}++/**+ * A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the+ * user can use rotation, panning and zoom gestures. [onGesture] will be called when any of the+ * rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and+ * pan as an offset in pixels. Each of these changes is a difference between the previous call+ * and the current gesture. This will consume all position changes after touch slop has+ * been reached. [onGesture] will also provide centroid of all the pointers that are down.+ *+ * After gesture started when last pointer is up [onGestureEnd] is triggered.+ *+ * @param consume flag consume [PointerInputChange]s this gesture uses. Consuming+ * returns [PointerInputChange.isConsumed] true which is observed by other gestures such+ * as drag, scroll and transform. When this flag is true other gesture don't receive events+ * @param onGestureStart callback for notifying transform gesture has started with initial+ * pointer+ * @param onGesture callback for passing centroid, pan, zoom, rotation and main pointer and+ * pointer size to caller. Main pointer is the one that touches screen first. If it's lifted+ * next one that is down is the main pointer.+ * @param onGestureEnd callback that notifies last pointer is up and gesture is ended if it's+ * started by fulfilling requisite.+ *+ */+suspend fun PointerInputScope.detectTransformGestures(+ panZoomLock: Boolean = false,+ consume: Boolean = true,+ onGestureStart: (PointerInputChange) -> Unit = {},+ onGesture: (+ centroid: Offset,+ pan: Offset,+ zoom: Float,+ rotation: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ ) -> Unit,+ onGestureEnd: (PointerInputChange) -> Unit = {}+) {+ awaitEachGesture {+ var rotation = 0f+ var zoom = 1f+ var pan = Offset.Zero+ var pastTouchSlop = false+ val touchSlop = viewConfiguration.touchSlop+ var lockedToPanZoom = false+++ // Wait for at least one pointer to press down, and set first contact position+ val down: PointerInputChange = awaitFirstDown(requireUnconsumed = false)+ onGestureStart(down)++ var pointer = down+ // Main pointer is the one that is down initially+ var pointerId = down.id++ do {+ val event = awaitPointerEvent()++ // If any position change is consumed from another PointerInputChange+ // or pointer count requirement is not fulfilled+ val canceled =+ event.changes.any { it.isConsumed }++ if (!canceled) {++ // Get pointer that is down, if first pointer is up+ // get another and use it if other pointers are also down+ // event.changes.first() doesn't return same order+ val pointerInputChange =+ event.changes.firstOrNull { it.id == pointerId }+ ?: event.changes.first()++ // Next time will check same pointer with this id+ pointerId = pointerInputChange.id+ pointer = pointerInputChange++ val zoomChange = event.calculateZoom()+ val rotationChange = event.calculateRotation()+ val panChange = event.calculatePan()++ if (!pastTouchSlop) {+ zoom *= zoomChange+ rotation += rotationChange+ pan += panChange++ val centroidSize = event.calculateCentroidSize(useCurrent = false)+ val zoomMotion = abs(1 - zoom) * centroidSize+ val rotationMotion =+ abs(rotation * PI.toFloat() * centroidSize / 180f)+ val panMotion = pan.getDistance()++ if (zoomMotion > touchSlop ||+ rotationMotion > touchSlop ||+ panMotion > touchSlop+ ) {+ pastTouchSlop = true+ lockedToPanZoom = panZoomLock && rotationMotion < touchSlop+ }+ }++ if (pastTouchSlop) {+ val centroid = event.calculateCentroid(useCurrent = false)+ val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange+ if (effectiveRotation != 0f ||+ zoomChange != 1f ||+ panChange != Offset.Zero+ ) {+ onGesture(+ centroid,+ panChange,+ zoomChange,+ effectiveRotation,+ pointer,+ event.changes+ )+ }++ if (consume) {+ event.changes.forEach {+ if (it.positionChanged()) {+ it.consume()+ }+ }+ }+ }+ }+ } while (!canceled && event.changes.any { it.pressed })+ onGestureEnd(pointer)+ }+}++/**+ * A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the+ * user can use rotation, panning and zoom gestures. [onGesture] will be called when any of the+ * rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and+ * pan as an offset in pixels. Each of these changes is a difference between the previous call+ * and the current gesture. This will consume all position changes after touch slop has+ * been reached. [onGesture] will also provide centroid of all the pointers that are down.+ *+ * After gesture started when last pointer is up [onGestureEnd] is triggered.+ *+ *+ * @param numberOfPointers number of pointer required to be down for gestures to commence. Value+ * of this parameter cannot be lower than 1+ * @param requisite determines whether number of pointer down should be equal to less than or+ * greater than [numberOfPointers] for this gesture.+ * If [PointerRequisite.None] is set [numberOfPointers] is+ * not taken into consideration+ * @param consume flag consume [PointerInputChange]s this gesture uses. Consuming+ * returns [PointerInputChange.isConsumed] true which is observed by other gestures such+ * as drag, scroll and transform. When this flag is true other gesture don't receive events+ * @param onGestureStart callback for notifying transform gesture has started with initial+ * pointer+ * @param onGesture callback for passing centroid, pan, zoom, rotation and pointer size to+ * caller+ * @param onGestureEnd callback that notifies last pointer is up and gesture is ended if it's+ * started by fulfilling requisite.+ *+ */+suspend fun PointerInputScope.detectPointerTransformGestures(+ panZoomLock: Boolean = false,+ numberOfPointers: Int = 1,+ requisite: PointerRequisite = PointerRequisite.None,+ consume: Boolean = true,+ onGestureStart: (PointerInputChange) -> Unit = {},+ onGesture:+ (+ centroid: Offset,+ pan: Offset,+ zoom: Float,+ rotation: Float,+ mainPointer: PointerInputChange,+ changes: List<PointerInputChange>+ ) -> Unit,+ onGestureEnd: (PointerInputChange) -> Unit = {},+ onGestureCancel: () -> Unit = {},+) {++ require(numberOfPointers > 0)++ awaitEachGesture {+ var rotation = 0f+ var zoom = 1f+ var pan = Offset.Zero+ var pastTouchSlop = false+ val touchSlop = viewConfiguration.touchSlop+ var lockedToPanZoom = false++ var gestureStarted = false++ // Wait for at least one pointer to press down, and set first contact position+ val down: PointerInputChange = awaitFirstDown(requireUnconsumed = false)+ onGestureStart(down)++ var pointer = down+ // Main pointer is the one that is down initially+ var pointerId = down.id+++ do {+ val event = awaitPointerEvent()++ val downPointerCount = event.changes.map {+ it.pressed+ }.size++ val requirementFulfilled = when (requisite) {+ PointerRequisite.LessThan -> {+ (downPointerCount < numberOfPointers)+ }++ PointerRequisite.EqualTo -> {+ (downPointerCount == numberOfPointers)+ }++ PointerRequisite.GreaterThan -> {+ (downPointerCount > numberOfPointers)+ }++ else -> true+ }++ // If any position change is consumed from another PointerInputChange+ // or pointer count requirement is not fulfilled+ val canceled =+ event.changes.any { it.isConsumed }++ if (!canceled && requirementFulfilled) {++ gestureStarted = true+ // Get pointer that is down, if first pointer is up+ // get another and use it if other pointers are also down+ // event.changes.first() doesn't return same order+ val pointerInputChange =+ event.changes.firstOrNull { it.id == pointerId }+ ?: event.changes.first()++ // Next time will check same pointer with this id+ pointerId = pointerInputChange.id+ pointer = pointerInputChange++ val zoomChange = event.calculateZoom()+ val rotationChange = event.calculateRotation()+ val panChange = event.calculatePan()++ if (!pastTouchSlop) {+ zoom *= zoomChange+ rotation += rotationChange+ pan += panChange++ val centroidSize = event.calculateCentroidSize(useCurrent = false)+ val zoomMotion = abs(1 - zoom) * centroidSize+ val rotationMotion =+ abs(rotation * PI.toFloat() * centroidSize / 180f)+ val panMotion = pan.getDistance()++ if (zoomMotion > touchSlop ||+ rotationMotion > touchSlop ||+ panMotion > touchSlop+ ) {+ pastTouchSlop = true+ lockedToPanZoom = panZoomLock && rotationMotion < touchSlop+ }+ }++ if (pastTouchSlop) {+ val centroid = event.calculateCentroid(useCurrent = false)+ val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange+ if (effectiveRotation != 0f ||+ zoomChange != 1f ||+ panChange != Offset.Zero+ ) {+ onGesture(+ centroid,+ panChange,+ zoomChange,+ effectiveRotation,+ pointer,+ event.changes+ )+ }++ if (consume) {+ event.changes.forEach {+ if (it.positionChanged()) {+ it.consume()+ }+ }+ }+ }+ }+ } while (!canceled && event.changes.any { it.pressed })++ if (gestureStarted) {+ onGestureEnd(pointer)+ } else {+ onGestureCancel()+ }+ }+}+++fun Modifier.observePointersCountWithOffset(+ enabled: Boolean = true,+ onChange: (Int, Offset) -> Unit+) = this then if (enabled) Modifier.pointerInput(Unit) {+ onEachGesture {+ val context = currentCoroutineContext()+ awaitPointerEventScope {+ do {+ val event = awaitPointerEvent()+ onChange(+ event.changes.size,+ event.changes.firstOrNull()?.position ?: Offset.Unspecified+ )+ } while (event.changes.any { it.pressed } && context.isActive)+ onChange(0, Offset.Unspecified)+ }+ }+} else Modifier++suspend fun PointerInputScope.onEachGesture(block: suspend PointerInputScope.() -> Unit) {+ val currentContext = currentCoroutineContext()+ while (currentContext.isActive) {+ try {+ block()++ // Wait for all pointers to be up. Gestures start when a finger goes down.+ awaitAllPointersUp()+ } catch (e: CancellationException) {+ if (currentContext.isActive) {+ // The current gesture was canceled. Wait for all fingers to be "up" before looping+ // again.+ awaitAllPointersUp()+ } else {+ // forEachGesture was cancelled externally. Rethrow the cancellation exception to+ // propagate it upwards.+ throw e+ }+ }+ }+}++private suspend fun PointerInputScope.awaitAllPointersUp() {+ awaitPointerEventScope { awaitAllPointersUp() }+}++private suspend fun AwaitPointerEventScope.awaitAllPointersUp() {+ if (!allPointersUp()) {+ do {+ val events = awaitPointerEvent(PointerEventPass.Final)+ } while (events.changes.fastAny { it.pressed })+ }+}++private fun AwaitPointerEventScope.allPointersUp(): Boolean =+ !currentEvent.changes.fastAny { it.pressed }\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageScope.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageScope.ktnew file mode 100644index 0000000..dc1b3a5--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageScope.kt@@ -0,0 +1,111 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.image++import androidx.compose.foundation.Canvas+import androidx.compose.runtime.Stable+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntRect+++/**+ * Receiver scope being used by the children parameter of [ImageWithConstraints]+ */+@Stable+interface ImageScope {+ /**+ * The constraints given by the parent layout in pixels.+ *+ * Use [minWidth], [maxWidth], [minHeight] or [maxHeight] if you need value in [Dp].+ */+ val constraints: Constraints++ /**+ * The minimum width in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val minWidth: Dp++ /**+ * The maximum width in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val maxWidth: Dp++ /**+ * The minimum height in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val minHeight: Dp++ /**+ * The maximum height in [Dp].+ *+ * @see constraints for the values in pixels.+ */+ val maxHeight: Dp++ /**+ * Width of area inside BoxWithConstraints that is scaled based on [ContentScale]+ * This is width of the [Canvas] draw [ImageBitmap]+ */+ val imageWidth: Dp++ /**+ * Height of area inside BoxWithConstraints that is scaled based on [ContentScale]+ * This is height of the [Canvas] draw [ImageBitmap]+ */+ val imageHeight: Dp++ /**+ * [IntRect] that covers boundaries of [ImageBitmap]+ */+ val rect: IntRect+}++internal data class ImageScopeImpl(+ private val density: Density,+ override val constraints: Constraints,+ override val imageWidth: Dp,+ override val imageHeight: Dp,+ override val rect: IntRect,+) : ImageScope {++ override val minWidth: Dp get() = with(density) { constraints.minWidth.toDp() }++ override val maxWidth: Dp+ get() = with(density) {+ if (constraints.hasBoundedWidth) constraints.maxWidth.toDp() else Dp.Infinity+ }++ override val minHeight: Dp get() = with(density) { constraints.minHeight.toDp() }++ override val maxHeight: Dp+ get() = with(density) {+ if (constraints.hasBoundedHeight) constraints.maxHeight.toDp() else Dp.Infinity+ }+}\ No newline at end of filediff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageWithConstraints.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageWithConstraints.ktnew file mode 100644index 0000000..a18f276--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/ImageWithConstraints.kt@@ -0,0 +1,251 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.image++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.DefaultAlpha+import androidx.compose.ui.graphics.FilterQuality+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.translate+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.role+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.Constraints+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize+import com.chethan616.clearpdf.imageeditor.thirdparty.image.util.getParentSize+import com.chethan616.clearpdf.imageeditor.thirdparty.image.util.getScaledBitmapRect+++/**+ * A composable that lays out and draws a given [ImageBitmap]. This will attempt to+ * size the composable according to the [ImageBitmap]'s given width and height. However, an+ * optional [Modifier] parameter can be provided to adjust sizing or draw additional content (ex.+ * background). Any unspecified dimension will leverage the [ImageBitmap]'s size as a minimum+ * constraint.+ *+ * [ImageScope] returns constraints, width and height of the drawing area based on [contentScale]+ * and rectangle of [imageBitmap] drawn. When a bitmap is displayed scaled to fit area of Composable+ * space used for drawing image is represented with [ImageScope.imageWidth] and+ * [ImageScope.imageHeight].+ *+ * When we display a bitmap 1000x1000px with [ContentScale.Crop] if it's cropped to 500x500px+ * [ImageScope.rect] returns `IntRect(250,250,750,750)`.+ *+ * @param alignment determines where image will be aligned inside [BoxWithConstraints]+ * This is observable when bitmap image/width ratio differs from [Canvas] that draws [ImageBitmap]+ * @param contentDescription text used by accessibility services to describe what this image+ * represents. This should always be provided unless this image is used for decorative purposes,+ * and does not represent a meaningful action that a user can take. This text should be+ * localized, such as by using [androidx.compose.ui.res.stringResource] or similar+ * @param contentScale how image should be scaled inside Canvas to match parent dimensions.+ * [ContentScale.Fit] for instance maintains src ratio and scales image to fit inside the parent.+ * @param alpha Opacity to be applied to [imageBitmap] from 0.0f to 1.0f representing+ * fully transparent to fully opaque respectively+ * @param colorFilter ColorFilter to apply to the [imageBitmap] when drawn into the destination+ * @param filterQuality Sampling algorithm applied to the [imageBitmap] when it is scaled and drawn+ * into the destination. The default is [FilterQuality.Low] which scales using a bilinear+ * sampling algorithm+ * @param content is a Composable that can be matched at exact position where [imageBitmap] is drawn.+ * This is useful for drawing thumbs, cropping or another layout that should match position+ * with the image that is scaled is drawn+ * @param drawImage flag to draw image on canvas. Some Composables might only require+ * the calculation and rectangle bounds of image after scaling but not drawing.+ * Composables like image cropper that scales or+ * rotates image. Drawing here again have 2 drawings overlap each other.+ */+@Composable+fun ImageWithConstraints(+ modifier: Modifier = Modifier,+ imageBitmap: ImageBitmap,+ alignment: Alignment = Alignment.Center,+ contentScale: ContentScale = ContentScale.Fit,+ contentDescription: String? = null,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+ drawImage: Boolean = true,+ content: @Composable ImageScope.() -> Unit = {}+) {++ val semantics = if (contentDescription != null) {+ Modifier.semantics {+ this.contentDescription = contentDescription+ this.role = Role.Image+ }+ } else {+ Modifier+ }++ BoxWithConstraints(+ modifier = modifier+ .then(semantics),+ contentAlignment = alignment,+ ) {++ val bitmapWidth = imageBitmap.width+ val bitmapHeight = imageBitmap.height++ val (boxWidth: Int, boxHeight: Int) = getParentSize(bitmapWidth, bitmapHeight)++ // Src is Bitmap, Dst is the container(Image) that Bitmap will be displayed+ val srcSize = Size(bitmapWidth.toFloat(), bitmapHeight.toFloat())+ val dstSize = Size(boxWidth.toFloat(), boxHeight.toFloat())++ val scaleFactor = contentScale.computeScaleFactor(srcSize, dstSize)++ // Image is the container for bitmap that is located inside Box+ // image bounds can be smaller or bigger than its parent based on how it's scaled+ val imageWidth = bitmapWidth * scaleFactor.scaleX+ val imageHeight = bitmapHeight * scaleFactor.scaleY++ val bitmapRect = getScaledBitmapRect(+ boxWidth = boxWidth,+ boxHeight = boxHeight,+ imageWidth = imageWidth,+ imageHeight = imageHeight,+ bitmapWidth = bitmapWidth,+ bitmapHeight = bitmapHeight+ )++ ImageLayout(+ constraints = constraints,+ imageBitmap = imageBitmap,+ bitmapRect = bitmapRect,+ imageWidth = imageWidth,+ imageHeight = imageHeight,+ boxWidth = boxWidth,+ boxHeight = boxHeight,+ alpha = alpha,+ colorFilter = colorFilter,+ filterQuality = filterQuality,+ drawImage = drawImage,+ content = content+ )+ }+}++@Composable+private fun ImageLayout(+ constraints: Constraints,+ imageBitmap: ImageBitmap,+ bitmapRect: IntRect,+ imageWidth: Float,+ imageHeight: Float,+ boxWidth: Int,+ boxHeight: Int,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+ drawImage: Boolean = true,+ content: @Composable ImageScope.() -> Unit+) {+ val density = LocalDensity.current++ // Dimensions of canvas that will draw this Bitmap+ val canvasWidthInDp: Dp+ val canvasHeightInDp: Dp++ with(density) {+ canvasWidthInDp = imageWidth.coerceAtMost(boxWidth.toFloat()).toDp()+ canvasHeightInDp = imageHeight.coerceAtMost(boxHeight.toFloat()).toDp()+ }++ // Send rectangle of Bitmap drawn to Canvas as bitmapRect, content scale modes like+ // crop might crop image from center so Rect can be such as IntRect(250,250,500,500)++ // canvasWidthInDp, and canvasHeightInDp are Canvas dimensions coerced to Box size+ // that covers Canvas+ val imageScopeImpl = ImageScopeImpl(+ density = density,+ constraints = constraints,+ imageWidth = canvasWidthInDp,+ imageHeight = canvasHeightInDp,+ rect = bitmapRect+ )++ // width and height params for translating draw position if scaled Image dimensions are+ // bigger than Canvas dimensions+ if (drawImage) {+ ImageImpl(+ modifier = Modifier.size(canvasWidthInDp, canvasHeightInDp),+ imageBitmap = imageBitmap,+ alpha = alpha,+ width = imageWidth.toInt(),+ height = imageHeight.toInt(),+ colorFilter = colorFilter,+ filterQuality = filterQuality+ )+ }++ imageScopeImpl.content()+}++@Composable+private fun ImageImpl(+ modifier: Modifier,+ imageBitmap: ImageBitmap,+ width: Int,+ height: Int,+ alpha: Float = DefaultAlpha,+ colorFilter: ColorFilter? = null,+ filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,+) {+ val bitmapWidth = imageBitmap.width+ val bitmapHeight = imageBitmap.height++ Canvas(modifier = modifier.clipToBounds()) {++ val canvasWidth = size.width.toInt()+ val canvasHeight = size.height.toInt()++ // Translate to left or down when Image size is bigger than this canvas.+ // ImageSize is bigger when scale modes like Crop is used which enlarges image+ // For instance 1000x1000 image can be 1000x2000 for a Canvas with 1000x1000+ // so top is translated -500 to draw center of ImageBitmap+ translate(+ top = (-height + canvasHeight) / 2f,+ left = (-width + canvasWidth) / 2f,++ ) {+ drawImage(+ imageBitmap,+ srcSize = IntSize(bitmapWidth, bitmapHeight),+ dstSize = IntSize(width, height),+ alpha = alpha,+ colorFilter = colorFilter,+ filterQuality = filterQuality+ )+ }+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/util/ImageContentScaleUtil.kt b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/util/ImageContentScaleUtil.ktnew file mode 100644index 0000000..6269585--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/imageeditor/thirdparty/image/util/ImageContentScaleUtil.kt@@ -0,0 +1,106 @@+/*+ * ImageToolbox is an image editor for android+ * Copyright (c) 2026 T8RIN (Malik Mukhametzyanov)+ * Modified by ClearPDF (2026): repackaged and adapted for the ClearPDF image editor.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ * You should have received a copy of the Apache License+ * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>.+ */++package com.chethan616.clearpdf.imageeditor.thirdparty.image.util++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.BoxWithConstraintsScope+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntRect+import androidx.compose.ui.unit.IntSize++/**+ * Get Rectangle of [ImageBitmap] with [bitmapWidth] and [bitmapHeight] that is drawn inside+ * Canvas with [imageWidth] and [imageHeight]. [boxWidth] and [boxHeight] belong+ * to [BoxWithConstraints] that contains Canvas.+ * @param boxWidth width of the parent container+ * @param boxHeight height of the parent container+ * @param imageWidth width of the [Canvas] that draws [ImageBitmap]+ * @param imageHeight height of the [Canvas] that draws [ImageBitmap]+ * @param bitmapWidth intrinsic width of the [ImageBitmap]+ * @param bitmapHeight intrinsic height of the [ImageBitmap]+ * @return [IntRect] that covers [ImageBitmap] bounds. When image [ContentScale] is crop+ * this rectangle might return smaller rectangle than actual [ImageBitmap] and left or top+ * of the rectangle might be bigger than zero.+ */+internal fun getScaledBitmapRect(+ boxWidth: Int,+ boxHeight: Int,+ imageWidth: Float,+ imageHeight: Float,+ bitmapWidth: Int,+ bitmapHeight: Int+): IntRect {+ // Get scale of box to width of the image+ // We need a rect that contains Bitmap bounds to pass if any child requires it+ // For a image with 100x100 px with 300x400 px container and image with crop 400x400px+ // So we need to pass top left as 0,50 and size+ val scaledBitmapX = boxWidth / imageWidth+ val scaledBitmapY = boxHeight / imageHeight++ val topLeft = IntOffset(+ x = (bitmapWidth * (imageWidth - boxWidth) / imageWidth / 2)+ .coerceAtLeast(0f).toInt(),+ y = (bitmapHeight * (imageHeight - boxHeight) / imageHeight / 2)+ .coerceAtLeast(0f).toInt()+ )++ val size = IntSize(+ width = (bitmapWidth * scaledBitmapX).toInt().coerceAtMost(bitmapWidth),+ height = (bitmapHeight * scaledBitmapY).toInt().coerceAtMost(bitmapHeight)+ )++ return IntRect(offset = topLeft, size = size)+}++/**+ * Get [IntSize] of the parent or container that contains [Canvas] that draws [ImageBitmap]+ * @param bitmapWidth intrinsic width of the [ImageBitmap]+ * @param bitmapHeight intrinsic height of the [ImageBitmap]+ * @return size of parent Composable. When Modifier is assigned with fixed or finite size+ * they are used, but when any dimension is set to infinity intrinsic dimensions of+ * [ImageBitmap] are returned+ */+internal fun BoxWithConstraintsScope.getParentSize(+ bitmapWidth: Int,+ bitmapHeight: Int+): IntSize {+ // Check if Composable has fixed size dimensions+ val hasBoundedDimens = constraints.hasBoundedWidth && constraints.hasBoundedHeight+ // Check if Composable has infinite dimensions+ val hasFixedDimens = constraints.hasFixedWidth && constraints.hasFixedHeight++ // Box is the parent(BoxWithConstraints) that contains Canvas under the hood+ // Canvas aspect ratio or size might not match parent but it's upper bounds are+ // what are passed from parent. Canvas cannot be bigger or taller than BoxWithConstraints+ val boxWidth: Int = if (hasBoundedDimens || hasFixedDimens) {+ constraints.maxWidth+ } else {+ constraints.minWidth.coerceAtLeast(bitmapWidth)+ }+ val boxHeight: Int = if (hasBoundedDimens || hasFixedDimens) {+ constraints.maxHeight+ } else {+ constraints.minHeight.coerceAtLeast(bitmapHeight)+ }+ return IntSize(boxWidth, boxHeight)+}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 25b3323..46160ab 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -19,6 +19,9 @@ accompanist = "0.36.0"pdfbox = "2.0.27.0"kotlinxCoroutines = "1.10.2"tesseract4android = "4.9.0"+toolboxGpuimage = "8.0.8"+exifinterface = "1.3.7"+mlkitSubjectSegmentation = "16.0.0-beta1"[libraries]kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }@@ -36,6 +39,11 @@ androidx-navigation-compose = { group = "androidx.navigation", name = "navigatioandroidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }+# Image editor (ImageToolbox-derived; see THIRD_PARTY_NOTICES.md)+toolbox-gpuimage = { group = "com.github.T8RIN.ImageToolboxLibs", name = "gpuimage", version.ref = "toolboxGpuimage" }+androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" }+mlkit-subject-segmentation = { group = "com.google.android.gms", name = "play-services-mlkit-subject-segmentation", version.ref = "mlkitSubjectSegmentation" }+# ML Kit & Scanningplay-services-mlkit-scanner = { group = "com.google.android.gms", name = "play-services-mlkit-document-scanner", version.ref = "mlkit" }camerax-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }