├── app ├── .gitignore ├── src │ └── main │ │ ├── assets │ │ ├── brisquemodels.zip │ │ └── faq │ │ │ ├── what_is_this.md │ │ │ └── which_models.md │ │ ├── res │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ ├── values │ │ │ ├── colors.xml │ │ │ ├── themes.xml │ │ │ └── strings.xml │ │ ├── values-night │ │ │ ├── colors.xml │ │ │ └── themes.xml │ │ ├── mipmap-anydpi-v26 │ │ │ └── ic_launcher.xml │ │ ├── drawable │ │ │ ├── ic_launcher_background.xml │ │ │ ├── ic_brisque.xml │ │ │ ├── ic_launcher_monochrome.xml │ │ │ ├── dejpeg.xml │ │ │ └── ic_launcher_foreground.xml │ │ ├── xml │ │ │ ├── file_paths.xml │ │ │ ├── backup_rules.xml │ │ │ └── data_extraction_rules.xml │ │ ├── layout │ │ │ ├── dialog_switch_row.xml │ │ │ └── preference_switch_row.xml │ │ └── drawable-night │ │ │ └── dejpeg.xml │ │ ├── jniLibs │ │ └── arm64-v8a │ │ │ ├── libc++_shared.so │ │ │ ├── libopencv_ml.so │ │ │ ├── libbrisque_jni.so │ │ │ ├── libonnxruntime.so │ │ │ ├── libopencv_core.so │ │ │ ├── libopencv_imgproc.so │ │ │ ├── libopencv_quality.so │ │ │ └── libopencv_imgcodecs.so │ │ ├── java │ │ └── com │ │ │ └── je │ │ │ └── dejpeg │ │ │ ├── compose │ │ │ ├── ui │ │ │ │ ├── theme │ │ │ │ │ ├── Color.kt │ │ │ │ │ ├── Type.kt │ │ │ │ │ └── Theme.kt │ │ │ │ ├── components │ │ │ │ │ ├── DialogDefaults.kt │ │ │ │ │ ├── ImportProgressDialog.kt │ │ │ │ │ ├── AboutDialog.kt │ │ │ │ │ ├── LoadingDialog.kt │ │ │ │ │ ├── PreferenceComponents.kt │ │ │ │ │ ├── PreferencesDialog.kt │ │ │ │ │ ├── MaterialSwitchViews.kt │ │ │ │ │ ├── ChunkDialog.kt │ │ │ │ │ ├── DownloadModelDialog.kt │ │ │ │ │ ├── DialogManager.kt │ │ │ │ │ └── FAQDialog.kt │ │ │ │ └── MainScreen.kt │ │ │ ├── utils │ │ │ │ ├── helpers │ │ │ │ │ ├── ModelRepository.kt │ │ │ │ │ ├── ImagePickerHelper.kt │ │ │ │ │ ├── ModelMigrationHelper.kt │ │ │ │ │ ├── ImageLoadingHelper.kt │ │ │ │ │ └── ServiceCommunicationHelper.kt │ │ │ │ ├── BRISQUE │ │ │ │ │ └── BRISQUEAssesser.kt │ │ │ │ ├── ZipExtractor.kt │ │ │ │ ├── CacheManager.kt │ │ │ │ ├── HapticFeedback.kt │ │ │ │ ├── ImageActions.kt │ │ │ │ └── TimeEstimator.kt │ │ │ ├── NotificationHelper.kt │ │ │ └── MainActivity.kt │ │ │ └── data │ │ │ └── AppPreferences.kt │ │ ├── cpp │ │ ├── CMakeLists.txt │ │ └── brisque_assessor.cpp │ │ └── AndroidManifest.xml ├── proguard-rules.pro └── build.gradle.kts ├── fastlane ├── metadata │ └── android │ │ └── en-US │ │ ├── changelogs │ │ ├── 300.txt │ │ ├── 253.txt │ │ ├── 270.txt │ │ ├── 252.txt │ │ ├── 310.txt │ │ ├── 250.txt │ │ ├── 261.txt │ │ ├── 242.txt │ │ ├── 220.txt │ │ ├── 230.txt │ │ ├── 320.txt │ │ └── 251.txt │ │ ├── short_description.txt │ │ ├── images │ │ ├── icon.png │ │ └── phoneScreenshots │ │ │ ├── 01.png │ │ │ └── 02.png │ │ └── full_description.txt └── githubassets │ ├── dejpeg.png │ ├── obtanium.png │ ├── IzzyOnDroid.png │ └── badge_github.png ├── chainner ├── fbcnn_node.png ├── README.md └── fbcnn_node.py ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── .gitignore ├── settings.gradle.kts ├── gradle.properties ├── gradlew.bat ├── README.md └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/300.txt: -------------------------------------------------------------------------------- 1 | migrate to Jetpack Compose -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/253.txt: -------------------------------------------------------------------------------- 1 | fix erroring on chunked images -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/270.txt: -------------------------------------------------------------------------------- 1 | dynamic theme 2 | configurable chunk sizes -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/short_description.txt: -------------------------------------------------------------------------------- 1 | Remove noise and compression from photos -------------------------------------------------------------------------------- /chainner/fbcnn_node.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/chainner/fbcnn_node.png -------------------------------------------------------------------------------- /fastlane/githubassets/dejpeg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/githubassets/dejpeg.png -------------------------------------------------------------------------------- /fastlane/githubassets/obtanium.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/githubassets/obtanium.png -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/252.txt: -------------------------------------------------------------------------------- 1 | - fix share incoming intent 2 | - bump min SDK to 28 (Android 9/Pie) -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/assets/brisquemodels.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/assets/brisquemodels.zip -------------------------------------------------------------------------------- /fastlane/githubassets/IzzyOnDroid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/githubassets/IzzyOnDroid.png -------------------------------------------------------------------------------- /fastlane/githubassets/badge_github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/githubassets/badge_github.png -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/310.txt: -------------------------------------------------------------------------------- 1 | - minor UI fixes 2 | - add image descaling (beta) 3 | - chunk processing fixes -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libc++_shared.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libc++_shared.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libopencv_ml.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libopencv_ml.so -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/metadata/android/en-US/images/icon.png -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libbrisque_jni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libbrisque_jni.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libonnxruntime.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libonnxruntime.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libopencv_core.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libopencv_core.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libopencv_imgproc.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libopencv_imgproc.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libopencv_quality.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libopencv_quality.so -------------------------------------------------------------------------------- /app/src/main/jniLibs/arm64-v8a/libopencv_imgcodecs.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/app/src/main/jniLibs/arm64-v8a/libopencv_imgcodecs.so -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #eeeeee 4 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #1f1f1f 4 | 5 | -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/images/phoneScreenshots/01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/metadata/android/en-US/images/phoneScreenshots/01.png -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/images/phoneScreenshots/02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeeneo/dejpeg/HEAD/fastlane/metadata/android/en-US/images/phoneScreenshots/02.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | *.properties 4 | .DS_Store 5 | /build 6 | /captures 7 | .externalNativeBuild 8 | .cxx 9 | .idea 10 | .kotlin 11 | apks 12 | .git-public 13 | .git-private 14 | opencv -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/250.txt: -------------------------------------------------------------------------------- 1 | fixes for v2.5.0 2 | 3 | 1. notification fixes 4 | 2. rough time estimation (not always accurate) 5 | 3. better multithreading support 6 | 4. small UI improvements and FAQ -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/261.txt: -------------------------------------------------------------------------------- 1 | added time estimation 2 | fixed gaps in large images (and crashing issues with SCUNet) 3 | major dialog changes 4 | prevented images over 8000px which would cause crashes -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/242.txt: -------------------------------------------------------------------------------- 1 | - improved background service and information handling 2 | - added warning for images over 6000px 3 | - fixed the app icon SVG/drawable 4 | - small improvements to the UI and backend code 5 | - other bugfixes -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/220.txt: -------------------------------------------------------------------------------- 1 | added: 2 | 1. add background service for notifications (fixes ghost notifications) 3 | 2. dynamic theme (read from system) 4 | 3. model hashing/verification 5 | 6 | fixes: 7 | 1. removed anti-aliasing (for better viewing) 8 | 2. fixed before/after view issues when panning 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Oct 27 18:22:08 EDT 2025 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip 5 | networkTimeout=10000 6 | validateDistributionUrl=true 7 | zipStoreBase=GRADLE_USER_HOME 8 | zipStorePath=wrapper/dists 9 | -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/230.txt: -------------------------------------------------------------------------------- 1 | fixes: 2 | - prevent system from killing the app (foreground service) 3 | - use bitmap pooling to recycle bitmaps when possible 4 | - removed actionbar for better UI 5 | 6 | added: 7 | - image progress for multiple images/chunks 8 | - model download links on select model window 9 | - notification icons 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/theme/Color.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.ui.theme 2 | 3 | import androidx.compose.ui.graphics.Color 4 | 5 | val Purple80 = Color(0xFFD0BCFF) 6 | val PurpleGrey80 = Color(0xFFCCC2DC) 7 | val Pink80 = Color(0xFFEFB8C8) 8 | 9 | val Purple40 = Color(0xFF6650a4) 10 | val PurpleGrey40 = Color(0xFF625b71) 11 | val Pink40 = Color(0xFF7D5260) -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/320.txt: -------------------------------------------------------------------------------- 1 | - internal changes (smaller size) 2 | - added monochrome app icon 3 | - queue processing fix 4 | - small dialog fixes 5 | - better before/after view 6 | - improve time estimation 7 | - proper cache cleanup 8 | - cache image chunks for processing 9 | - added progress bar 10 | - improved processing notification 11 | - improved sharpness estimation -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/changelogs/251.txt: -------------------------------------------------------------------------------- 1 | proper monochrome dark/light theme support 2 | 3 | - minor dialog changes 4 | - strings fixes 5 | - icon change 6 | - added image size infotext 7 | - added remove all except this (image) option 8 | - fixed crash on very small images when zooming (e.g.: 25px) 9 | - chunk size change (1200px), shouldn't give too many issues unless device is really low end, todo later 10 | - vibration feedback changes -------------------------------------------------------------------------------- /chainner/README.md: -------------------------------------------------------------------------------- 1 | requirements: 2 | 3 | - [chaiNNer](https://github.com/chaiNNer-org/chaiNNer) 0.24.x or newer 4 | - the PyTorch dependency installed beforehand 5 | 6 | then download and copy [fbcnn_node.py](fbcnn_node.py) to your chaiNNer install under `resources/src/packages/chaiNNer_pytorch/pytorch/restoration` 7 | 8 | reopen and the new node should appear under PyTorch > Restoration > FBCNN 9 | 10 | ![screenshot of the FBCNN node](fbcnn_node.png) -------------------------------------------------------------------------------- /app/src/main/res/xml/file_paths.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/xml/backup_rules.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | -------------------------------------------------------------------------------- /app/src/main/assets/faq/what_is_this.md: -------------------------------------------------------------------------------- 1 | ## What is this app for? 2 | 3 | This app is designed to remove image compression, noise, or other unpleasant artifacts 4 | 5 | Note: this isn't "AI" or image upscaling, your images stay the same resolution. 6 | It's meant to provide a cleaner image, which can produce better results if you do use "AI enhancers", but that can make them look uglier or create unpleasant artifacts/blending (my opinion), see the wiki page for [2x++ models when???](https://github.com/jeeneo/dejpeg/wiki/model-requests#2x-models-when) on GitHub for more information. -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google { 4 | content { 5 | includeGroupByRegex("com\\.android.*") 6 | includeGroupByRegex("com\\.google.*") 7 | includeGroupByRegex("androidx.*") 8 | } 9 | } 10 | mavenCentral() 11 | gradlePluginPortal() 12 | } 13 | } 14 | dependencyResolutionManagement { 15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 16 | repositories { 17 | google() 18 | mavenCentral() 19 | } 20 | } 21 | 22 | rootProject.name = "DeJPEG" 23 | include(":app") -------------------------------------------------------------------------------- /app/src/main/res/xml/data_extraction_rules.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 12 | 13 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10 | 14 | -------------------------------------------------------------------------------- /fastlane/metadata/android/en-US/full_description.txt: -------------------------------------------------------------------------------- 1 |

DeJPEG - an open source app for removing noise and compression from photos

2 | 3 |

features:

4 | 12 | 13 |

This is not a "super resolution AI upscaler", but simple non-destructive method for cleaning up/restoring images

14 | 15 |

external models are required (links in-app or on GitHub)

16 | 17 |

limitations:

18 | 22 | 23 |

(note: DeJPEG is not affiliated or related with Topaz DEJPEG or any other similarly named software/project)

-------------------------------------------------------------------------------- /app/src/main/res/layout/dialog_switch_row.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 16 | 17 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/theme/Type.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.ui.theme 2 | 3 | import androidx.compose.material3.Typography 4 | import androidx.compose.ui.text.TextStyle 5 | import androidx.compose.ui.text.font.FontFamily 6 | import androidx.compose.ui.text.font.FontWeight 7 | import androidx.compose.ui.unit.sp 8 | 9 | val Typography = Typography( 10 | bodyLarge = TextStyle( 11 | fontFamily = FontFamily.Default, 12 | fontWeight = FontWeight.Normal, 13 | fontSize = 16.sp, 14 | lineHeight = 24.sp, 15 | letterSpacing = 0.5.sp 16 | ), 17 | titleLarge = TextStyle( 18 | fontFamily = FontFamily.Default, 19 | fontWeight = FontWeight.Normal, 20 | fontSize = 22.sp, 21 | lineHeight = 28.sp, 22 | letterSpacing = 0.sp 23 | ), 24 | labelSmall = TextStyle( 25 | fontFamily = FontFamily.Default, 26 | fontWeight = FontWeight.Medium, 27 | fontSize = 11.sp, 28 | lineHeight = 16.sp, 29 | letterSpacing = 0.5.sp 30 | ) 31 | ) -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_brisque.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 12 | 13 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/DialogDefaults.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.widthIn 4 | import androidx.compose.foundation.shape.RoundedCornerShape 5 | import androidx.compose.runtime.Composable 6 | import androidx.compose.ui.Modifier 7 | import androidx.compose.ui.platform.LocalConfiguration 8 | import androidx.compose.ui.unit.Dp 9 | import androidx.compose.ui.unit.dp 10 | import androidx.compose.ui.window.DialogProperties 11 | 12 | object DialogDefaults { 13 | val MinWidth = 280.dp 14 | val MaxWidthFraction = 0.9f 15 | val MaxWidthMin = 280f 16 | val MaxWidthMax = 560f 17 | val Shape = RoundedCornerShape(28.dp) 18 | val Properties = DialogProperties(usePlatformDefaultWidth = false) 19 | } 20 | 21 | @Composable 22 | fun rememberDialogWidth(): Dp { 23 | val configuration = LocalConfiguration.current 24 | return (configuration.screenWidthDp * DialogDefaults.MaxWidthFraction) 25 | .coerceIn(DialogDefaults.MaxWidthMin, DialogDefaults.MaxWidthMax).dp 26 | } 27 | 28 | fun Modifier.dialogWidth(maxWidth: Dp): Modifier = 29 | widthIn(min = DialogDefaults.MinWidth, max = maxWidth) -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/ImportProgressDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.* 4 | import androidx.compose.material3.* 5 | import androidx.compose.runtime.Composable 6 | import androidx.compose.ui.Alignment 7 | import androidx.compose.ui.Modifier 8 | import androidx.compose.ui.res.stringResource 9 | import androidx.compose.ui.unit.dp 10 | import com.je.dejpeg.R 11 | 12 | @Composable 13 | fun ImportProgressDialog(progress: Int) { 14 | val dialogWidth = rememberDialogWidth() 15 | AlertDialog( 16 | onDismissRequest = {}, 17 | modifier = Modifier.dialogWidth(dialogWidth), 18 | properties = DialogDefaults.Properties, 19 | shape = DialogDefaults.Shape, 20 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 21 | title = { Text(stringResource(R.string.importing_model)) }, 22 | text = { 23 | Column(horizontalAlignment = Alignment.CenterHorizontally) { 24 | LinearProgressIndicator( 25 | progress = { progress / 100f }, 26 | modifier = Modifier.fillMaxWidth() 27 | ) 28 | Spacer(modifier = Modifier.height(8.dp)) 29 | Text(stringResource(R.string.progress_percent, progress)) 30 | } 31 | }, 32 | confirmButton = {} 33 | ) 34 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. For more details, visit 12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Kotlin code style for this project: "official" or "obsolete": 19 | kotlin.code.style=official 20 | # Enables namespacing of each library's R class so that its R class includes only the 21 | # resources declared in the library itself and none from the library's dependencies, 22 | # thereby reducing the size of the R class for that library 23 | android.nonTransitiveRClass=true 24 | android.enableR8.fullMode=true -------------------------------------------------------------------------------- /app/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(brisque_jni) 3 | # Default is OFF (use pre-built binaries from jniLibs/) 4 | # Set BUILD_BRISQUE_JNI=ON to compile 5 | if(DEFINED ENV{BUILD_BRISQUE_JNI}) 6 | set(CMAKE_BUILD_BRISQUE $ENV{BUILD_BRISQUE_JNI}) 7 | else() 8 | set(CMAKE_BUILD_BRISQUE OFF) 9 | endif() 10 | if(CMAKE_BUILD_BRISQUE) 11 | get_filename_component(PROJECT_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../../.." ABSOLUTE) 12 | set(OPENCV_SRC_DIR "${PROJECT_ROOT}/opencv/opencv") 13 | set(OPENCV_CONTRIB_DIR "${PROJECT_ROOT}/opencv/opencv_contrib") 14 | set(OPENCV_BUILD_DIR "${PROJECT_ROOT}/opencv/build_android") 15 | include_directories( 16 | ${OPENCV_SRC_DIR}/modules/core/include 17 | ${OPENCV_SRC_DIR}/modules/imgproc/include 18 | ${OPENCV_SRC_DIR}/modules/imgcodecs/include 19 | ${OPENCV_SRC_DIR}/modules/ml/include 20 | ${OPENCV_CONTRIB_DIR}/modules/quality/include 21 | ${OPENCV_BUILD_DIR} 22 | ${OPENCV_BUILD_DIR}/opencv2 23 | ) 24 | set(OPENCV_LIB_DIR "${OPENCV_BUILD_DIR}/lib/${ANDROID_ABI}") 25 | add_library(brisque_jni SHARED brisque_assessor.cpp) 26 | target_link_directories(brisque_jni PRIVATE ${OPENCV_LIB_DIR}) 27 | target_link_libraries(brisque_jni 28 | opencv_core 29 | opencv_imgproc 30 | opencv_imgcodecs 31 | opencv_quality 32 | log 33 | ) 34 | set_target_properties(brisque_jni PROPERTIES 35 | CXX_STANDARD 17 36 | CXX_STANDARD_REQUIRED ON 37 | LINK_FLAGS "-Wl,-rpath,/system/lib64:/data/data/com.je.dejpeg.debug/lib -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=4096" 38 | ) 39 | else() 40 | message(STATUS "not building brisque_jni") 41 | endif() 42 | -------------------------------------------------------------------------------- /app/src/main/res/layout/preference_switch_row.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 20 | 21 | 27 | 28 | 35 | 36 | 37 | 38 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /app/src/main/assets/faq/which_models.md: -------------------------------------------------------------------------------- 1 | ## Which models to use? 2 | 3 | ### FBCNN 4 | 5 | Use for images that have JPEG compression (e.g. low-res images from Google, Pinterest, Instagram, that random forum, etc). 6 | 7 | The slider is available for FBCNN models only, and affects how much strength goes into removing compression, values around 30/50 for minor compression, and 70+ for heavy removal, afterward it begins to get noticeably smoother. 8 | 9 | The base model is `color`, the `grey` FBCNN models are for black and white images, `grey double` is for images saved and re-saved as JPEG. (edited/resized twice both saving as JPEG) 10 | 11 | ### SCUNet 12 | 13 | `SCUNet` is more adept at removing noise (e.g. ISO noise, grainy looking or speckled). 14 | 15 | It can also remove compression and GIF artifacts, to some degree. 16 | 17 | The "grey 15/25/50" SCUNet models are only for greyscale images as well, with different levels of noise removal. 18 | 19 | Higher the number, the more noise is removed. 20 | 21 | The "PSNR" variant tries to pixel-match the original image as closely as possible, so it looks mathematically correct but may appear overly smooth. 22 | 23 | "GAN" sacrifices pixel-perfect accuracy to add realistic textures or details, which can look more natural. As with most cases, try both and see which one suits your image better. 24 | 25 | ### Other models? 26 | 27 | We (I) support other ONNX models (by essentially guessing the params) to allow you to run your own `1x` models without needing to compile it yourself. 28 | 29 | I (we) have my (our) own library of pre-converted models under the [experimental](https://github.com/jeeneo/dejpeg-experimental) repo on GitHub. 30 | 31 | There's not much documentation for those simply because the original creator(s) didn't provide more than a basic description of what it was trained for, they will be added later on after the initial testing is completed. -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_monochrome.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 11 | 12 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/dejpeg.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 13 | 14 | 15 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-night/dejpeg.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 13 | 14 | 15 | 19 | 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/helpers/ModelRepository.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.helpers 2 | 3 | import android.content.Context 4 | import android.net.Uri 5 | import com.je.dejpeg.compose.ModelManager 6 | import kotlinx.coroutines.Dispatchers 7 | import kotlinx.coroutines.withContext 8 | 9 | class ModelRepository(context: Context) { 10 | 11 | private val modelManager = ModelManager(context) 12 | 13 | suspend fun getInstalledModels(): List = withContext(Dispatchers.IO) { 14 | modelManager.getInstalledModels() 15 | } 16 | fun hasActiveModel(): Boolean = modelManager.hasActiveModel() 17 | fun getActiveModelName(): String? = modelManager.getActiveModelName() 18 | fun setActiveModel(name: String) { 19 | modelManager.setActiveModel(name) 20 | } 21 | fun getModelWarning(modelName: String?): ModelManager.ModelWarning? { 22 | return modelName?.let { modelManager.getModelWarning(it) } 23 | } 24 | fun supportsStrengthAdjustment(): Boolean { 25 | val modelName = getActiveModelName() 26 | return modelName?.contains("fbcnn", ignoreCase = true) == true 27 | } 28 | suspend fun importModel( 29 | uri: Uri, 30 | force: Boolean = false, 31 | onProgress: (Int) -> Unit = {}, 32 | onSuccess: (String) -> Unit = {}, 33 | onError: (String) -> Unit = {}, 34 | onWarning: ((String, ModelManager.ModelWarning) -> Unit)? = null 35 | ) = withContext(Dispatchers.IO) { 36 | try { 37 | modelManager.importModel( 38 | uri, 39 | onProgress, 40 | { modelName -> 41 | modelManager.setActiveModel(modelName) 42 | onSuccess(modelName) 43 | }, 44 | onError, 45 | onWarning, 46 | force 47 | ) 48 | } catch (e: Exception) { 49 | onError(e.message ?: "Unknown error") 50 | } 51 | } 52 | 53 | suspend fun deleteModels(models: List, onDeleted: (String) -> Unit = {}) = withContext(Dispatchers.IO) { 54 | models.forEach { name -> 55 | modelManager.deleteModel(name) 56 | withContext(Dispatchers.Main) { onDeleted(name) } 57 | } 58 | } 59 | fun getModelManager(): ModelManager = modelManager 60 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/BRISQUE/BRISQUEAssesser.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.BRISQUE 2 | 3 | import android.util.Log 4 | import java.io.File 5 | 6 | class BRISQUEAssesser { 7 | companion object { // awww it's cute 8 | private const val TAG = "BRISQUEAssesser" 9 | private var librariesLoaded = false 10 | 11 | fun loadLibraries() { 12 | synchronized(this) { 13 | if (librariesLoaded) return 14 | try { 15 | listOf("opencv_core", "opencv_imgproc", "opencv_imgcodecs", "opencv_quality", "brisque_jni").forEach { loadLib(it) } 16 | librariesLoaded = true 17 | } catch (e: Exception) { 18 | Log.e(TAG, "Failed to load libraries: ${e.message}", e) 19 | } 20 | } 21 | } 22 | 23 | private fun loadLib(name: String) { 24 | try { 25 | Log.d(TAG, "Loading $name...") 26 | System.loadLibrary(name) 27 | } catch (e: UnsatisfiedLinkError) { 28 | Log.w(TAG, "Library $name not found: ${e.message}") 29 | } catch (e: Exception) { 30 | Log.e(TAG, "Error loading $name: ${e.message}", e) 31 | throw e 32 | } 33 | } 34 | 35 | init { 36 | loadLibraries() 37 | } 38 | } 39 | 40 | external fun computeBRISQUEFromFile(imagePath: String, modelPath: String, rangePath: String): Float 41 | 42 | fun assessImageQuality(imagePath: String, modelPath: String, rangePath: String): Float { 43 | loadLibraries() 44 | if (!File(imagePath).exists() || !File(modelPath).exists() || !File(rangePath).exists()) { 45 | Log.e(TAG, "One or more files do not exist") 46 | return -1.0f 47 | } 48 | return try { 49 | Log.d(TAG, "Computing BRISQUE score for image: $imagePath") 50 | computeBRISQUEFromFile(imagePath, modelPath, rangePath).also { 51 | Log.d(TAG, "BRISQUE score computed: $it") 52 | } 53 | } catch (e: UnsatisfiedLinkError) { 54 | Log.e(TAG, "Native method not found: ${e.message}", e) 55 | -2.0f 56 | } catch (e: Exception) { 57 | Log.e(TAG, "Error computing BRISQUE score: ${e.message}", e) 58 | -1.0f 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/ZipExtractor.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import com.je.dejpeg.compose.utils.helpers.ModelMigrationHelper 6 | import java.io.File 7 | import java.util.zip.ZipInputStream 8 | 9 | object ZipExtractor { 10 | private const val TAG = "ZipExtractor" 11 | fun extractFromAssets( 12 | context: Context, 13 | assetFileName: String, 14 | targetDir: File = getBrisqueModelsDir(context) 15 | ): Boolean { 16 | return try { 17 | if (!targetDir.exists()) { 18 | targetDir.mkdirs() 19 | } 20 | 21 | context.assets.open(assetFileName).use { inputStream -> 22 | ZipInputStream(inputStream).use { zipInputStream -> 23 | var entry = zipInputStream.nextEntry 24 | while (entry != null) { 25 | if (!entry.isDirectory) { 26 | val outputFile = File(targetDir, entry.name) 27 | outputFile.parentFile?.mkdirs() 28 | 29 | outputFile.outputStream().use { fileOutputStream -> 30 | zipInputStream.copyTo(fileOutputStream) 31 | } 32 | Log.d(TAG, "Extracted: ${entry.name}") 33 | } 34 | entry = zipInputStream.nextEntry 35 | } 36 | } 37 | } 38 | Log.d(TAG, "Successfully extracted $assetFileName to ${targetDir.absolutePath}") 39 | true 40 | } catch (e: Exception) { 41 | Log.e(TAG, "Error extracting $assetFileName: ${e.message}", e) 42 | false 43 | } 44 | } 45 | 46 | fun modelsExist( 47 | context: Context, 48 | targetDir: File = getBrisqueModelsDir(context) 49 | ): Boolean { 50 | val modelFile = File(targetDir, "brisque_model_live.yml") 51 | val rangeFile = File(targetDir, "brisque_range_live.yml") 52 | return modelFile.exists() && rangeFile.exists() 53 | } 54 | 55 | fun getBrisqueModelsDir(context: Context): File { 56 | return ModelMigrationHelper.getBrisqueModelsDir(context) 57 | } 58 | 59 | fun getModelPath(context: Context, filename: String): String { 60 | return File(getBrisqueModelsDir(context), filename).absolutePath 61 | } 62 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/theme/Theme.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.ui.theme 2 | 3 | import android.app.Activity 4 | import android.os.Build 5 | import androidx.compose.foundation.isSystemInDarkTheme 6 | import androidx.compose.material3.MaterialTheme 7 | import androidx.compose.material3.darkColorScheme 8 | import androidx.compose.material3.dynamicDarkColorScheme 9 | import androidx.compose.material3.dynamicLightColorScheme 10 | import androidx.compose.material3.lightColorScheme 11 | import androidx.compose.runtime.Composable 12 | import androidx.compose.ui.graphics.Color 13 | import androidx.compose.ui.platform.LocalContext 14 | 15 | private val DarkColorScheme = darkColorScheme( 16 | primary = Purple80, 17 | secondary = PurpleGrey80, 18 | tertiary = Pink80, 19 | surface = Color(0xFF1C1B1F), 20 | surfaceContainer = Color(0xFF211F26), 21 | surfaceContainerHigh = Color(0xFF2B2930), 22 | surfaceContainerHighest = Color(0xFF36343B), 23 | surfaceContainerLow = Color(0xFF1C1B1F), 24 | surfaceContainerLowest = Color(0xFF0F0D13) 25 | ) 26 | 27 | private val LightColorScheme = lightColorScheme( 28 | primary = Purple40, 29 | secondary = PurpleGrey40, 30 | tertiary = Pink40, 31 | surface = Color(0xFFFFFBFE), 32 | surfaceContainer = Color(0xFFF3EFF4), 33 | surfaceContainerHigh = Color(0xFFECE9ED), 34 | surfaceContainerHighest = Color(0xFFE6E2E7), 35 | surfaceContainerLow = Color(0xFFF9F5FA), 36 | surfaceContainerLowest = Color(0xFFFFFFFF) 37 | 38 | /* Other default colors to override 39 | background = Color(0xFFFFFBFE), 40 | surface = Color(0xFFFFFBFE), 41 | onPrimary = Color.White, 42 | onSecondary = Color.White, 43 | onTertiary = Color.White, 44 | onBackground = Color(0xFF1C1B1F), 45 | onSurface = Color(0xFF1C1B1F), 46 | */ 47 | ) 48 | 49 | @Composable 50 | fun DeJPEGTheme( 51 | darkTheme: Boolean = isSystemInDarkTheme(), 52 | dynamicColor: Boolean = true, 53 | content: @Composable () -> Unit 54 | ) { 55 | val colorScheme = when { 56 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { 57 | val context = LocalContext.current 58 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) 59 | } 60 | 61 | darkTheme -> DarkColorScheme 62 | else -> LightColorScheme 63 | } 64 | 65 | MaterialTheme( 66 | colorScheme = colorScheme, 67 | typography = Typography, 68 | content = content 69 | ) 70 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 11 | 12 | 16 | 17 | 21 | 22 | 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/helpers/ImagePickerHelper.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.helpers 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.net.Uri 6 | import android.provider.MediaStore 7 | import androidx.activity.result.ActivityResultLauncher 8 | import androidx.core.content.FileProvider 9 | import com.je.dejpeg.compose.utils.CacheManager 10 | import java.io.File 11 | import java.io.IOException 12 | 13 | class ImagePickerHelper( 14 | private val context: Context, 15 | private var launcher: ActivityResultLauncher? = null 16 | ) { 17 | private var currentPhotoUri: Uri? = null 18 | 19 | fun setLauncher(launcher: ActivityResultLauncher) { 20 | this.launcher = launcher 21 | } 22 | 23 | fun launchGalleryPicker() { 24 | launch( 25 | Intent(Intent.ACTION_PICK).apply { 26 | setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*") 27 | putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) 28 | } 29 | ) 30 | } 31 | 32 | fun launchInternalPhotoPicker() { 33 | launch( 34 | Intent(Intent.ACTION_GET_CONTENT).apply { 35 | type = "image/*" 36 | putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) 37 | } 38 | ) 39 | } 40 | 41 | fun launchDocumentsPicker() { 42 | launch( 43 | Intent(Intent.ACTION_OPEN_DOCUMENT).apply { 44 | type = "image/*" 45 | putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) 46 | } 47 | ) 48 | } 49 | 50 | fun launchCamera(): Result { 51 | return try { 52 | val cameraDir = CacheManager.getCameraImportsDir(context) 53 | val tempFile = File( 54 | cameraDir, 55 | "JPEG_${System.currentTimeMillis()}.jpg" 56 | ) 57 | val photoUri = FileProvider.getUriForFile( 58 | context, 59 | "${context.packageName}.provider", 60 | tempFile 61 | ) 62 | currentPhotoUri = photoUri 63 | 64 | launch( 65 | Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply { 66 | putExtra(MediaStore.EXTRA_OUTPUT, photoUri) 67 | } 68 | ) 69 | Result.success(photoUri) 70 | } catch (e: IOException) { 71 | Result.failure(e) 72 | } 73 | } 74 | 75 | fun getCameraPhotoUri(): Uri? = currentPhotoUri 76 | 77 | fun clearCameraPhotoUri() { 78 | currentPhotoUri = null 79 | } 80 | private fun launch(intent: Intent) { 81 | launcher?.launch(intent) 82 | } 83 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 18 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 44 | 47 | 48 | 54 | 55 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/AboutDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import android.content.Intent 4 | import android.net.Uri 5 | import androidx.compose.foundation.layout.* 6 | import androidx.compose.material3.* 7 | import androidx.compose.runtime.Composable 8 | import androidx.compose.ui.Modifier 9 | import androidx.compose.ui.platform.LocalContext 10 | import androidx.compose.ui.res.stringResource 11 | import androidx.compose.ui.text.font.FontWeight 12 | import androidx.compose.ui.unit.dp 13 | import com.je.dejpeg.R 14 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 15 | 16 | @Composable 17 | fun AboutDialog(onDismiss: () -> Unit) { 18 | val context = LocalContext.current 19 | val haptic = rememberHapticFeedback() 20 | val versionName = try { 21 | context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "Unknown" 22 | } catch (e: Exception) { 23 | "Unknown" 24 | } 25 | val dialogWidth = rememberDialogWidth() 26 | AlertDialog( 27 | onDismissRequest = onDismiss, 28 | modifier = Modifier.dialogWidth(dialogWidth), 29 | properties = DialogDefaults.Properties, 30 | shape = DialogDefaults.Shape, 31 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 32 | title = { 33 | Text( 34 | "${stringResource(R.string.dejpeg_title)} v$versionName", 35 | style = MaterialTheme.typography.titleLarge, 36 | fontWeight = FontWeight.Bold 37 | ) 38 | }, 39 | text = { 40 | Column { 41 | Text(stringResource(R.string.non_destructive_restoration)) 42 | Spacer(modifier = Modifier.height(16.dp)) 43 | Text(stringResource(R.string.open_source_app_description)) 44 | Spacer(modifier = Modifier.height(8.dp)) 45 | Text( 46 | stringResource(R.string.license_text), 47 | style = MaterialTheme.typography.bodySmall 48 | ) 49 | } 50 | }, 51 | confirmButton = { 52 | TextButton(onClick = { haptic.light(); onDismiss() }) { 53 | Text(stringResource(R.string.ok)) 54 | } 55 | }, 56 | dismissButton = { 57 | TextButton(onClick = { 58 | haptic.medium() 59 | try { 60 | context.startActivity( 61 | Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/jeeneo/dejpeg")) 62 | ) 63 | } catch (_: Exception) { 64 | } 65 | }) { 66 | Text(stringResource(R.string.github)) 67 | } 68 | } 69 | ) 70 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | -keepclasseswithmembernames class * { 24 | native ; 25 | } 26 | 27 | -keepattributes *Annotation* 28 | -keepattributes SourceFile,LineNumberTable 29 | -keepattributes Signature 30 | -keepattributes Exceptions 31 | -keepattributes InnerClasses 32 | 33 | -keep class ai.onnxruntime.** { *; } 34 | -keep class com.microsoft.onnxruntime.** { *; } 35 | 36 | -keep class ai.onnxruntime.TensorInfo { *; } 37 | -keep class ai.onnxruntime.OnnxTensor { *; } 38 | -keep class ai.onnxruntime.OrtEnvironment { *; } 39 | -keep class ai.onnxruntime.OrtSession { *; } 40 | -keep class ai.onnxruntime.OrtSession$Result { *; } 41 | -keep class ai.onnxruntime.OrtSession$SessionOptions { *; } 42 | -keep class ai.onnxruntime.OnnxValue { *; } 43 | -keep class ai.onnxruntime.OrtException { *; } 44 | 45 | -keepclasseswithmembers class * { 46 | public (long, ai.onnxruntime.OrtEnvironment); 47 | } 48 | 49 | -keepclasseswithmembernames,includedescriptorclasses class * { 50 | native ; 51 | } 52 | 53 | -keep class ai.onnxruntime.OrtEnvironment { 54 | static ai.onnxruntime.OrtEnvironment getEnvironment(); 55 | } 56 | 57 | -keepnames class * implements java.io.Serializable 58 | -keepclassmembers class * implements java.io.Serializable { 59 | static final long serialVersionUID; 60 | private static final java.io.ObjectStreamField[] serialPersistentFields; 61 | !static !transient ; 62 | private void writeObject(java.io.ObjectOutputStream); 63 | private void readObject(java.io.ObjectInputStream); 64 | java.lang.Object writeReplace(); 65 | java.lang.Object readResolve(); 66 | } 67 | 68 | # -optimizationpasses 5 69 | # -allowaccessmodification 70 | # -mergeinterfacesaggressively 71 | 72 | # -assumenosideeffects class android.util.Log { 73 | # public static *** d(...); 74 | # public static *** v(...); 75 | # public static *** i(...); 76 | # public static *** w(...); 77 | # public static *** e(...); 78 | # } 79 | 80 | # -dontwarn kotlin.** 81 | # -dontwarn kotlinx.** -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/LoadingDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.* 4 | import androidx.compose.material3.* 5 | import androidx.compose.runtime.* 6 | import androidx.compose.ui.Alignment 7 | import androidx.compose.ui.Modifier 8 | import androidx.compose.ui.res.stringResource 9 | import androidx.compose.ui.text.font.FontWeight 10 | import androidx.compose.ui.unit.dp 11 | import androidx.compose.ui.window.Dialog 12 | import androidx.compose.ui.window.DialogProperties 13 | import com.je.dejpeg.R 14 | 15 | @Composable 16 | fun LoadingDialog( 17 | title: String, 18 | message: String? = null, 19 | progress: Float? = null, 20 | progressText: String? = null 21 | ) { 22 | val dialogWidth = rememberDialogWidth() 23 | Dialog( 24 | onDismissRequest = { }, 25 | properties = DialogProperties( 26 | dismissOnBackPress = false, 27 | dismissOnClickOutside = false, 28 | usePlatformDefaultWidth = false 29 | ) 30 | ) { 31 | Card( 32 | modifier = Modifier 33 | .dialogWidth(dialogWidth) 34 | .wrapContentHeight(), 35 | shape = DialogDefaults.Shape, 36 | colors = CardDefaults.cardColors( 37 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh 38 | ) 39 | ) { 40 | Column( 41 | modifier = Modifier 42 | .fillMaxWidth() 43 | .padding(24.dp), 44 | horizontalAlignment = Alignment.CenterHorizontally, 45 | verticalArrangement = Arrangement.spacedBy(16.dp) 46 | ) { 47 | Text( 48 | text = title, 49 | style = MaterialTheme.typography.titleLarge, 50 | fontWeight = FontWeight.SemiBold 51 | ) 52 | 53 | if (message != null) { 54 | Text( 55 | text = message, 56 | style = MaterialTheme.typography.bodyMedium, 57 | color = MaterialTheme.colorScheme.onSurfaceVariant 58 | ) 59 | } 60 | 61 | if (progress != null) { 62 | LinearProgressIndicator( 63 | progress = { progress }, 64 | modifier = Modifier.fillMaxWidth() 65 | ) 66 | } else { 67 | CircularProgressIndicator( 68 | modifier = Modifier.size(48.dp) 69 | ) 70 | } 71 | 72 | if (progressText != null) { 73 | Text( 74 | text = progressText, 75 | style = MaterialTheme.typography.bodySmall, 76 | color = MaterialTheme.colorScheme.onSurfaceVariant 77 | ) 78 | } 79 | } 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH= 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.13.1" 3 | coilCompose = "2.7.0" 4 | coreSplashscreen = "1.2.0" 5 | foundation = "1.9.5" 6 | kotlin = "2.2.21" 7 | coreKtx = "1.17.0" 8 | junit = "4.13.2" 9 | junitVersion = "1.3.0" 10 | espressoCore = "3.7.0" 11 | lifecycleRuntimeKtx = "2.10.0" 12 | activityCompose = "1.12.0" 13 | composeBom = "2025.11.01" 14 | material = "1.13.0" 15 | material3 = "1.4.0" 16 | materialIconsExtended = "1.7.8" 17 | navigationCompose = "2.9.6" 18 | onnxruntimeAndroid = "1.23.2" 19 | zoomable = "0.18.0" 20 | exifinterface = "1.4.1" 21 | datastore = "1.2.0" 22 | 23 | [libraries] 24 | androidx-compose-foundation = { module = "androidx.compose.foundation:foundation", version.ref = "foundation" } 25 | androidx-compose-material-icons-extended = { module = "androidx.compose.material:material-icons-extended", version.ref = "materialIconsExtended" } 26 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } 27 | androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "coreSplashscreen" } 28 | androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigationCompose" } 29 | coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" } 30 | google-material = { group = "com.google.android.material", name = "material", version.ref = "material" } 31 | #junit = { group = "junit", name = "junit", version.ref = "junit" } 32 | #androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } 33 | androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } 34 | androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" } 35 | androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } 36 | androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } 37 | androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } 38 | androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" } 39 | #androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } 40 | androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" } 41 | #androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } 42 | androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } 43 | androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" } 44 | androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite" } 45 | onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" } 46 | zoomable = { module = "me.saket.telephoto:zoomable", version.ref = "zoomable" } 47 | androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" } 48 | androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" } 49 | 50 | [plugins] 51 | android-application = { id = "com.android.application", version.ref = "agp" } 52 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 53 | kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/CacheManager.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlinx.coroutines.withContext 7 | import java.io.File 8 | 9 | object CacheManager { 10 | private const val TAG = "CacheManager" 11 | private const val CHUNKS_DIR = "processing_chunks" 12 | private const val CAMERA_IMPORTS_DIR = "cameraimports" 13 | private const val SHARED_IMAGE_NAME = "shared_image.png" 14 | 15 | fun getCameraImportsDir(context: Context): File { 16 | return File(context.cacheDir, CAMERA_IMPORTS_DIR).apply { 17 | if (!exists()) mkdirs() 18 | } 19 | } 20 | 21 | fun getChunksDir(context: Context): File { 22 | return File(context.cacheDir, CHUNKS_DIR).apply { 23 | if (!exists()) mkdirs() 24 | } 25 | } 26 | 27 | suspend fun clearChunks(context: Context) = withContext(Dispatchers.IO) { 28 | val chunksDir = File(context.cacheDir, CHUNKS_DIR) 29 | if (chunksDir.exists()) { 30 | val files = chunksDir.listFiles() 31 | val count = files?.size ?: 0 32 | if (count > 0) { 33 | Log.d(TAG, "Clearing $count chunk files") 34 | chunksDir.deleteRecursively() 35 | } 36 | } 37 | } 38 | 39 | fun clearChunksSync(context: Context) { 40 | val chunksDir = File(context.cacheDir, CHUNKS_DIR) 41 | if (chunksDir.exists()) { 42 | val count = chunksDir.listFiles()?.size ?: 0 43 | if (count > 0) { 44 | chunksDir.deleteRecursively() 45 | Log.d(TAG, "Cleared $count chunks (sync)") 46 | } 47 | } 48 | } 49 | 50 | suspend fun cleanupProcessedImage(context: Context, imageId: String) = withContext(Dispatchers.IO) { 51 | context.cacheDir.listFiles()?.forEach { file -> 52 | if (file.isFile && file.name.contains(imageId) && file.name.endsWith("_processed.png")) { 53 | if (file.delete()) { 54 | Log.d(TAG, "Deleted processed cache: ${file.name}") 55 | } 56 | } 57 | } 58 | } 59 | 60 | fun cleanEntireCacheSync(context: Context) { 61 | var deletedCount = 0 62 | context.cacheDir.listFiles()?.forEach { file -> 63 | if (file.isFile && file.name.endsWith("_processed.png")) { 64 | if (file.delete()) deletedCount++ 65 | } 66 | } 67 | File(context.cacheDir, SHARED_IMAGE_NAME).let { 68 | if (it.exists() && it.delete()) deletedCount++ 69 | } 70 | clearChunksSync(context) 71 | clearCameraImportsSync(context) 72 | context.cacheDir.listFiles()?.forEach { file -> 73 | if (file.isFile && file.name.startsWith("brisque_assess_")) { 74 | if (file.delete()) deletedCount++ 75 | } 76 | } 77 | if (deletedCount > 0) { 78 | Log.d(TAG, "Cleaned entire cache: $deletedCount files") 79 | } 80 | } 81 | 82 | private fun clearCameraImportsSync(context: Context) { 83 | val cameraDir = File(context.cacheDir, CAMERA_IMPORTS_DIR) 84 | if (cameraDir.exists()) { 85 | val count = cameraDir.listFiles()?.size ?: 0 86 | if (count > 0) { 87 | cameraDir.deleteRecursively() 88 | Log.d(TAG, "Cleared $count camera import files") 89 | } 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /chainner/fbcnn_node.py: -------------------------------------------------------------------------------- 1 | from __future__ import annotations 2 | 3 | import sys 4 | from pathlib import Path 5 | 6 | import numpy as np 7 | import torch 8 | from spandrel import ImageModelDescriptor 9 | 10 | from api import KeyInfo, NodeContext 11 | 12 | from nodes.impl.image_utils import to_uint8 13 | from nodes.impl.pytorch.utils import np2tensor, safe_cuda_cache_empty, tensor2np 14 | from nodes.properties.inputs import ImageInput, NumberInput, SrModelInput 15 | from nodes.properties.outputs import ImageOutput 16 | 17 | from ...settings import PyTorchSettings, get_settings 18 | from .. import restoration_group 19 | 20 | 21 | @torch.inference_mode() 22 | def denoise_fbcnn( 23 | img: np.ndarray, 24 | model: ImageModelDescriptor, 25 | qf_factor: float, 26 | exec_options: PyTorchSettings, 27 | device: torch.device, 28 | ) -> np.ndarray: 29 | if model.architecture.id != "FBCNN": 30 | raise ValueError( 31 | f"Expected FBCNN model, got {model.architecture.id}. " 32 | "This node only works with FBCNN models." 33 | ) 34 | 35 | if img.shape[2] == 4: 36 | img = img[:, :, :3] 37 | 38 | img_t = np2tensor(img, bgr2rgb=False, change_range=False, add_batch=True) 39 | img_t = img_t.to(device) 40 | 41 | should_use_fp16 = exec_options.use_fp16 and model.supports_half 42 | if should_use_fp16: 43 | model.model.half() 44 | img_t = img_t.half() 45 | else: 46 | model.model.float() 47 | img_t = img_t.float() 48 | 49 | try: 50 | if qf_factor > 0.0: 51 | qf_input = torch.tensor([[qf_factor]], dtype=torch.float32, device=device) 52 | if should_use_fp16: 53 | qf_input = qf_input.half() 54 | output, predicted_qf = model.model(img_t, qf_input=qf_input) 55 | else: 56 | output, predicted_qf = model.model(img_t) 57 | qf_value = predicted_qf.item() if isinstance(predicted_qf, torch.Tensor) else predicted_qf 58 | output_np = output.detach().cpu().float().squeeze(0).permute(1, 2, 0).numpy() 59 | restored_img = np.clip(output_np, 0, 1).astype(np.float32) 60 | 61 | except Exception as error: 62 | restored_img = img 63 | 64 | safe_cuda_cache_empty() 65 | 66 | return restored_img 67 | @restoration_group.register( 68 | schema_id="chainner:pytorch:fbcnn_denoiser", 69 | name="FBCNN", 70 | description=( 71 | "Towards Flexible Blind JPEG Artifacts Removal (FBCNN) is a JPEG artifact denoising model. This node adds additional support in chaiNNer. " 72 | "The quality factor sets how much artifacts are removed. " 73 | "Set 0 to use chaiNNer's original detection." 74 | ), 75 | icon="PyTorch", 76 | inputs=[ 77 | ImageInput().with_id(1), 78 | SrModelInput("Model").with_id(0), 79 | NumberInput( 80 | "Quality Factor", # i dislike using Title Case but the other nodes case their inputs like this so oh well 81 | default=0.0, 82 | min=0.0, 83 | max=1.0, 84 | step=0.05, 85 | precision=2, 86 | ) 87 | .with_id(2), 88 | ], 89 | outputs=[ 90 | ImageOutput( 91 | "Image", 92 | image_type=""" 93 | Image { 94 | width: Input1.width, 95 | height: Input1.height, 96 | } 97 | """, 98 | channels=3, 99 | ) 100 | ], 101 | key_info=KeyInfo.enum(0), 102 | node_context=True, 103 | ) 104 | def fbcnn_denoiser_node( 105 | context: NodeContext, 106 | img: np.ndarray, 107 | model: ImageModelDescriptor, 108 | qf_factor: float = 0.0, 109 | ) -> np.ndarray: 110 | exec_options = get_settings(context) 111 | device = exec_options.device 112 | 113 | return denoise_fbcnn(img, model, qf_factor, exec_options, device) -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/helpers/ModelMigrationHelper.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.helpers 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import com.je.dejpeg.data.AppPreferences 6 | import kotlinx.coroutines.Dispatchers 7 | import kotlinx.coroutines.withContext 8 | import java.io.File 9 | 10 | object ModelMigrationHelper { 11 | private const val TAG = "ModelMigrationHelper" 12 | fun getOnnxModelsDir(context: Context): File = File(context.filesDir, "models/onnx") 13 | fun getBrisqueModelsDir(context: Context): File = File(context.filesDir, "models/brisque") 14 | suspend fun migrateModelsIfNeeded(context: Context): Boolean = withContext(Dispatchers.IO) { 15 | val appPreferences = AppPreferences.getInstance(context) 16 | val onnxResult = migrateFiles( 17 | label = "ONNX", 18 | sourceDir = context.filesDir, 19 | targetDir = getOnnxModelsDir(context), 20 | fileFilter = { it.isFile && it.name.lowercase().endsWith(".onnx") }, 21 | isComplete = { appPreferences.getCompatModelCleanupImmediate() }, 22 | markComplete = { appPreferences.setCompatModelCleanup(true) } 23 | ) 24 | val brisqueResult = migrateFiles( 25 | label = "BRISQUE", 26 | sourceDir = File(context.filesDir, "models"), 27 | targetDir = getBrisqueModelsDir(context), 28 | fileFilter = { it.isFile && it.name in listOf("brisque_model_live.yml", "brisque_range_live.yml") }, 29 | isComplete = { appPreferences.getCompatBrisqueCleanupImmediate() }, 30 | markComplete = { appPreferences.setCompatBrisqueCleanup(true) } 31 | ) 32 | onnxResult && brisqueResult 33 | } 34 | 35 | private suspend fun migrateFiles( 36 | label: String, 37 | sourceDir: File, 38 | targetDir: File, 39 | fileFilter: (File) -> Boolean, 40 | isComplete: suspend () -> Boolean, 41 | markComplete: suspend () -> Unit 42 | ): Boolean { 43 | if (isComplete()) { 44 | Log.d(TAG, "$label migration already completed, skipping") 45 | return true 46 | } 47 | 48 | return try { 49 | val filesToMigrate = sourceDir.listFiles(fileFilter) ?: emptyArray() 50 | 51 | if (filesToMigrate.isEmpty()) { 52 | Log.d(TAG, "No $label files found, marking migration as complete") 53 | markComplete() 54 | return true 55 | } 56 | 57 | if (!targetDir.exists() && !targetDir.mkdirs()) { 58 | Log.e(TAG, "Failed to create $label directory: ${targetDir.absolutePath}") 59 | return false 60 | } 61 | 62 | var successCount = 0 63 | for (file in filesToMigrate) { 64 | if (moveFile(file, File(targetDir, file.name))) successCount++ 65 | } 66 | 67 | Log.d(TAG, "$label migration complete: $successCount/${filesToMigrate.size} files migrated") 68 | markComplete() 69 | true 70 | } catch (e: Exception) { 71 | Log.e(TAG, "$label migration failed: ${e.message}", e) 72 | false 73 | } 74 | } 75 | 76 | private fun moveFile(source: File, target: File): Boolean { 77 | return try { 78 | if (target.exists()) { 79 | Log.d(TAG, "File already exists in target, deleting old: ${source.name}") 80 | source.delete() 81 | } else if (!source.renameTo(target)) { 82 | source.copyTo(target, overwrite = true) 83 | source.delete() 84 | Log.d(TAG, "Copied and deleted: ${source.name}") 85 | } else { 86 | Log.d(TAG, "Moved: ${source.name}") 87 | } 88 | true 89 | } catch (e: Exception) { 90 | Log.e(TAG, "Failed to migrate ${source.name}: ${e.message}") 91 | false 92 | } 93 | } 94 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/helpers/ImageLoadingHelper.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.helpers 2 | 3 | import android.content.Context 4 | import android.graphics.Bitmap 5 | import android.graphics.BitmapFactory 6 | import android.graphics.Matrix 7 | import android.net.Uri 8 | import android.provider.OpenableColumns 9 | import androidx.exifinterface.media.ExifInterface 10 | 11 | 12 | object ImageLoadingHelper { 13 | private const val THUMBNAIL_SIZE = 256 14 | fun loadBitmapWithRotation(context: Context, uri: Uri): Bitmap? = try { 15 | context.contentResolver.openInputStream(uri)?.use { inputStream -> 16 | val bitmap = BitmapFactory.decodeStream(inputStream) ?: return null 17 | context.contentResolver.openInputStream(uri)?.use { exifStream -> 18 | val exif = ExifInterface(exifStream) 19 | applyExifOrientation(bitmap, exif) 20 | } ?: bitmap 21 | } 22 | } catch (e: Exception) { 23 | null 24 | } 25 | 26 | private fun applyExifOrientation(bitmap: Bitmap, exif: ExifInterface): Bitmap { 27 | return when (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) { 28 | ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90f) 29 | ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180f) 30 | ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270f) 31 | ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> flipBitmap(bitmap, horizontal = true, vertical = false) 32 | ExifInterface.ORIENTATION_FLIP_VERTICAL -> flipBitmap(bitmap, horizontal = false, vertical = true) 33 | ExifInterface.ORIENTATION_TRANSPOSE -> flipBitmap(rotateBitmap(bitmap, 90f), horizontal = true, vertical = false) 34 | ExifInterface.ORIENTATION_TRANSVERSE -> flipBitmap(rotateBitmap(bitmap, 270f), horizontal = true, vertical = false) 35 | else -> bitmap 36 | } 37 | } 38 | 39 | private fun rotateBitmap(bitmap: Bitmap, degrees: Float): Bitmap { 40 | val matrix = Matrix().apply { postRotate(degrees) } 41 | val rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) 42 | if (rotated != bitmap) bitmap.recycle() 43 | return rotated 44 | } 45 | 46 | private fun flipBitmap(bitmap: Bitmap, horizontal: Boolean, vertical: Boolean): Bitmap { 47 | val matrix = Matrix().apply { 48 | postScale( 49 | if (horizontal) -1f else 1f, 50 | if (vertical) -1f else 1f, 51 | bitmap.width / 2f, 52 | bitmap.height / 2f 53 | ) 54 | } 55 | val flipped = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) 56 | if (flipped != bitmap) bitmap.recycle() 57 | return flipped 58 | } 59 | 60 | fun generateThumbnail(bitmap: Bitmap, size: Int = THUMBNAIL_SIZE): Bitmap { 61 | val cropSize = minOf(bitmap.width, bitmap.height) 62 | val x = (bitmap.width - cropSize) / 2 63 | val y = (bitmap.height - cropSize) / 2 64 | val croppedBitmap = Bitmap.createBitmap(cropSize, cropSize, bitmap.config ?: Bitmap.Config.ARGB_8888) 65 | val canvas = android.graphics.Canvas(croppedBitmap) 66 | canvas.drawBitmap(bitmap, -x.toFloat(), -y.toFloat(), null) 67 | val resizedBitmap = Bitmap.createScaledBitmap(croppedBitmap, size, size, true) 68 | croppedBitmap.recycle() 69 | return resizedBitmap 70 | } 71 | 72 | fun getFileNameFromUri(context: Context, uri: Uri): String { 73 | return try { 74 | context.contentResolver.query(uri, null, null, null, null)?.use { cursor -> 75 | if (cursor.moveToFirst()) { 76 | cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) ?: "unknown" 77 | } else { 78 | uri.lastPathSegment ?: "unknown" 79 | } 80 | } ?: uri.lastPathSegment ?: "unknown" 81 | } catch (_: Exception) { 82 | uri.lastPathSegment ?: "unknown" 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /app/src/main/cpp/brisque_assessor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define TAG "BrisqueJNI" 11 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__) 12 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__) 13 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) 14 | 15 | JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { 16 | LOGI("JNI_OnLoad called for libbrisque_jni.so"); 17 | const char* libs[] = { 18 | "libopencv_core.so", 19 | "libopencv_imgproc.so", 20 | "libopencv_imgcodecs.so", 21 | "libopencv_quality.so" 22 | }; 23 | for (const char* lib : libs) { 24 | void* handle = dlopen(lib, RTLD_NOW | RTLD_GLOBAL); 25 | if (!handle) { 26 | LOGE("Failed to load %s with RTLD_GLOBAL: %s", lib, dlerror()); 27 | } else { 28 | LOGD("Successfully loaded %s with RTLD_GLOBAL", lib); 29 | } 30 | } 31 | return JNI_VERSION_1_6; 32 | } 33 | 34 | extern "C" JNIEXPORT jfloat JNICALL 35 | Java_com_je_dejpeg_compose_utils_BRISQUE_BRISQUEAssesser_computeBRISQUEFromFile( 36 | JNIEnv *env, 37 | jobject obj, 38 | jstring imagePath, 39 | jstring modelPath, 40 | jstring rangePath) { 41 | 42 | LOGD("Native method called"); 43 | const char *imagePathStr = env->GetStringUTFChars(imagePath, nullptr); 44 | const char *modelPathStr = env->GetStringUTFChars(modelPath, nullptr); 45 | const char *rangePathStr = env->GetStringUTFChars(rangePath, nullptr); 46 | 47 | try { 48 | LOGD("Loading image from: %s", imagePathStr); 49 | cv::Mat image = cv::imread(imagePathStr); 50 | 51 | if (image.empty()) { 52 | LOGE("Error: Could not load image from %s", imagePathStr); 53 | env->ReleaseStringUTFChars(imagePath, imagePathStr); 54 | env->ReleaseStringUTFChars(modelPath, modelPathStr); 55 | env->ReleaseStringUTFChars(rangePath, rangePathStr); 56 | return -1.0f; 57 | } 58 | LOGD("Image loaded successfully: %d x %d, channels: %d", image.cols, image.rows, image.channels()); 59 | cv::Mat grayImage; 60 | if (image.channels() == 3) { 61 | LOGD("Converting BGR to GRAY"); 62 | cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY); 63 | } else if (image.channels() == 4) { 64 | LOGD("Converting BGRA to GRAY"); 65 | cv::cvtColor(image, grayImage, cv::COLOR_BGRA2GRAY); 66 | } else { 67 | grayImage = image.clone(); 68 | } 69 | if (grayImage.type() != CV_8U) { 70 | LOGD("Converting image to CV_8U"); 71 | grayImage.convertTo(grayImage, CV_8U); 72 | } 73 | LOGD("Computing BRISQUE score using model: %s", modelPathStr); 74 | cv::Scalar scoreScalar = cv::quality::QualityBRISQUE::compute( 75 | grayImage, 76 | cv::String(modelPathStr), 77 | cv::String(rangePathStr) 78 | ); 79 | float brisqueScore = static_cast(scoreScalar[0]); 80 | LOGD("BRISQUE Score computed successfully: %f", brisqueScore); 81 | image.release(); 82 | grayImage.release(); 83 | env->ReleaseStringUTFChars(imagePath, imagePathStr); 84 | env->ReleaseStringUTFChars(modelPath, modelPathStr); 85 | env->ReleaseStringUTFChars(rangePath, rangePathStr); 86 | return brisqueScore; 87 | } catch (const std::exception& e) { 88 | LOGE("Error computing BRISQUE: %s", e.what()); 89 | env->ReleaseStringUTFChars(imagePath, imagePathStr); 90 | env->ReleaseStringUTFChars(modelPath, modelPathStr); 91 | env->ReleaseStringUTFChars(rangePath, rangePathStr); 92 | return -1.0f; 93 | } catch (...) { 94 | LOGE("Unknown error computing BRISQUE"); 95 | env->ReleaseStringUTFChars(imagePath, imagePathStr); 96 | env->ReleaseStringUTFChars(modelPath, modelPathStr); 97 | env->ReleaseStringUTFChars(rangePath, rangePathStr); 98 | return -1.0f; 99 | } 100 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/NotificationHelper.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg 2 | 3 | import android.app.Notification 4 | import android.app.NotificationChannel 5 | import android.app.NotificationManager 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.os.Build 9 | import androidx.core.app.NotificationCompat 10 | 11 | object NotificationHelper { 12 | const val CHANNEL_ID = "processing_channel" 13 | const val CHANNEL_NAME = "Image processing" 14 | const val NOTIFICATION_ID = 1001 15 | const val ACTION_CANCEL = "com.je.dejpeg.action.CANCEL" 16 | 17 | fun checkChannel(context: Context) { 18 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 19 | val mgr = context.getSystemService(NotificationManager::class.java) 20 | val existing = mgr?.getNotificationChannel(CHANNEL_ID) 21 | if (existing == null) { 22 | val channel = NotificationChannel( 23 | CHANNEL_ID, 24 | CHANNEL_NAME, 25 | NotificationManager.IMPORTANCE_LOW 26 | ).apply { 27 | description = "Shows progress of image processing" 28 | setShowBadge(false) 29 | } 30 | mgr?.createNotificationChannel(channel) 31 | } 32 | } 33 | } 34 | 35 | private fun baseBuilder(context: Context): NotificationCompat.Builder { 36 | checkChannel(context) 37 | val launchIntent = Intent(context, MainActivity::class.java).apply { 38 | flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP 39 | } 40 | val contentPendingIntent = android.app.PendingIntent.getActivity( 41 | context, 42 | 0, 43 | launchIntent, 44 | android.app.PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) android.app.PendingIntent.FLAG_IMMUTABLE else 0) 45 | ) 46 | return NotificationCompat.Builder(context, CHANNEL_ID) 47 | .setSmallIcon(android.R.drawable.ic_dialog_info) 48 | .setPriority(NotificationCompat.PRIORITY_LOW) 49 | .setOngoing(true) 50 | .setContentIntent(contentPendingIntent) 51 | } 52 | 53 | fun build(context: Context, message: String): Notification { 54 | return baseBuilder(context) 55 | .setContentTitle("Processing") 56 | .setContentText(message) 57 | .build() 58 | } 59 | 60 | fun show(context: Context, message: String) { 61 | val mgr = context.getSystemService(NotificationManager::class.java) 62 | mgr?.notify(NOTIFICATION_ID, build(context, message)) 63 | } 64 | 65 | fun showProgress( 66 | context: Context, 67 | message: String, 68 | timeRemainingMillis: Long? = null, 69 | progressPercent: Int? = null, 70 | cancellable: Boolean = true 71 | ) { 72 | val builder = baseBuilder(context) 73 | .setContentTitle("Processing") 74 | .setContentText(message) 75 | 76 | if (progressPercent != null) { 77 | builder.setProgress(100, progressPercent.coerceIn(0, 100), false) 78 | } else { 79 | builder.setProgress(0, 0, true) 80 | } 81 | 82 | timeRemainingMillis?.let { remaining -> 83 | builder.setSubText(TimeEstimator.formatTimeRemaining(remaining)) 84 | } 85 | 86 | if (cancellable) { 87 | val cancelIntent = Intent(context, ProcessingService::class.java).setAction(ACTION_CANCEL) 88 | val pendingCancel = android.app.PendingIntent.getService( 89 | context, 90 | 0, 91 | cancelIntent, 92 | android.app.PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) android.app.PendingIntent.FLAG_IMMUTABLE else 0) 93 | ) 94 | builder.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Cancel", pendingCancel) 95 | } 96 | 97 | val mgr = context.getSystemService(NotificationManager::class.java) 98 | mgr?.notify(NOTIFICATION_ID, builder.build()) 99 | } 100 | 101 | fun cancel(context: Context) { 102 | val mgr = context.getSystemService(NotificationManager::class.java) 103 | mgr?.cancel(NOTIFICATION_ID) 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/PreferenceComponents.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.clickable 4 | import androidx.compose.foundation.layout.* 5 | import androidx.compose.foundation.shape.RoundedCornerShape 6 | import androidx.compose.material.icons.Icons 7 | import androidx.compose.material.icons.filled.ChevronRight 8 | import androidx.compose.material3.* 9 | import androidx.compose.runtime.Composable 10 | import androidx.compose.ui.Alignment 11 | import androidx.compose.ui.Modifier 12 | import androidx.compose.ui.draw.clip 13 | import androidx.compose.ui.text.font.FontWeight 14 | import androidx.compose.ui.unit.dp 15 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 16 | 17 | @Composable 18 | fun PreferenceItem( 19 | title: String, 20 | summary: String, 21 | modifier: Modifier = Modifier, 22 | enabled: Boolean = true, 23 | showChevron: Boolean = true, 24 | onClick: () -> Unit 25 | ) { 26 | val haptic = rememberHapticFeedback() 27 | Row( 28 | modifier = modifier 29 | .fillMaxWidth() 30 | .clip(RoundedCornerShape(12.dp)) 31 | .clickable(enabled = enabled) { haptic.light(); onClick() } 32 | .padding(horizontal = 12.dp, vertical = 14.dp), 33 | horizontalArrangement = Arrangement.SpaceBetween, 34 | verticalAlignment = Alignment.CenterVertically 35 | ) { 36 | Column(modifier = Modifier.weight(1f)) { 37 | Text( 38 | title, 39 | style = MaterialTheme.typography.bodyMedium, 40 | fontWeight = FontWeight.Medium, 41 | color = if (enabled) MaterialTheme.colorScheme.onSurface 42 | else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) 43 | ) 44 | Spacer(modifier = Modifier.height(2.dp)) 45 | Text( 46 | summary, 47 | style = MaterialTheme.typography.bodySmall, 48 | color = if (enabled) MaterialTheme.colorScheme.onSurfaceVariant 49 | else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f) 50 | ) 51 | } 52 | if (showChevron) { 53 | Icon( 54 | Icons.Filled.ChevronRight, 55 | contentDescription = null, 56 | tint = if (enabled) MaterialTheme.colorScheme.onSurfaceVariant 57 | else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f), 58 | modifier = Modifier.size(18.dp) 59 | ) 60 | } 61 | } 62 | } 63 | 64 | @Composable 65 | fun PreferenceSection( 66 | title: String, 67 | modifier: Modifier = Modifier, 68 | content: @Composable ColumnScope.() -> Unit 69 | ) { 70 | Column(modifier = modifier.fillMaxWidth()) { 71 | Text( 72 | title, 73 | fontWeight = FontWeight.Bold, 74 | style = MaterialTheme.typography.bodyLarge, 75 | modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp) 76 | ) 77 | content() 78 | } 79 | } 80 | 81 | @Composable 82 | fun ActionPreference( 83 | title: String, 84 | currentValue: String, 85 | buttonText: String, 86 | onButtonClick: () -> Unit, 87 | modifier: Modifier = Modifier, 88 | showButton: Boolean = true, 89 | infoText: String? = null 90 | ) { 91 | val haptic = rememberHapticFeedback() 92 | Column( 93 | modifier = modifier 94 | .fillMaxWidth() 95 | .padding(horizontal = 12.dp, vertical = 8.dp) 96 | ) { 97 | Text( 98 | currentValue, 99 | style = MaterialTheme.typography.bodyMedium 100 | ) 101 | Spacer(modifier = Modifier.height(8.dp)) 102 | if (showButton) { 103 | Button( 104 | onClick = { 105 | haptic.medium() 106 | onButtonClick() 107 | }, 108 | modifier = Modifier.fillMaxWidth() 109 | ) { 110 | Text(buttonText) 111 | } 112 | } else if (infoText != null) { 113 | Text( 114 | infoText, 115 | style = MaterialTheme.typography.bodySmall, 116 | color = MaterialTheme.colorScheme.onSurfaceVariant 117 | ) 118 | } 119 | } 120 | } 121 | 122 | @Composable 123 | fun PreferenceDivider(modifier: Modifier = Modifier) { 124 | Column(modifier = modifier) { 125 | Spacer(modifier = Modifier.height(16.dp)) 126 | HorizontalDivider() 127 | Spacer(modifier = Modifier.height(16.dp)) 128 | } 129 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/PreferencesDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.* 4 | import androidx.compose.foundation.rememberScrollState 5 | import androidx.compose.foundation.verticalScroll 6 | import androidx.compose.material3.* 7 | import androidx.compose.runtime.* 8 | import androidx.compose.ui.Modifier 9 | import androidx.compose.ui.res.stringResource 10 | import androidx.compose.ui.unit.dp 11 | import com.je.dejpeg.R 12 | import com.je.dejpeg.compose.ui.components.ActionPreference 13 | import com.je.dejpeg.compose.ui.components.PreferenceDivider 14 | import com.je.dejpeg.compose.ui.components.PreferenceSection 15 | import com.je.dejpeg.compose.utils.HapticFeedback 16 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 17 | import com.je.dejpeg.data.AppPreferences 18 | import androidx.compose.ui.platform.LocalView 19 | import kotlinx.coroutines.launch 20 | 21 | @Composable 22 | fun PreferencesDialog( 23 | context: android.content.Context, 24 | onDismiss: () -> Unit 25 | ) { 26 | val appPreferences = remember { AppPreferences(context) } 27 | val scope = rememberCoroutineScope() 28 | 29 | val skipSaveDialog by appPreferences.skipSaveDialog.collectAsState(initial = false) 30 | val defaultImageSource by appPreferences.defaultImageSource.collectAsState(initial = null) 31 | val hapticFeedbackEnabled by appPreferences.hapticFeedbackEnabled.collectAsState(initial = true) 32 | val haptic = rememberHapticFeedback() 33 | val view = LocalView.current 34 | 35 | val dialogWidth = rememberDialogWidth() 36 | AlertDialog( 37 | onDismissRequest = onDismiss, 38 | modifier = Modifier.dialogWidth(dialogWidth), 39 | properties = DialogDefaults.Properties, 40 | shape = DialogDefaults.Shape, 41 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 42 | title = { Text(stringResource(R.string.preferences)) }, 43 | text = { 44 | Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState())) { 45 | PreferenceSection(title = stringResource(R.string.haptic_feedback)) { 46 | MaterialSwitchPreference( 47 | title = stringResource(R.string.vibration_on_touch), 48 | summary = stringResource(R.string.haptic_feedback_desc), 49 | checked = hapticFeedbackEnabled, 50 | onCheckedChange = { enabled -> 51 | if (enabled) { 52 | HapticFeedback.light(view, isEnabled = true) 53 | } 54 | scope.launch { appPreferences.setHapticFeedbackEnabled(enabled) } 55 | } 56 | ) 57 | } 58 | PreferenceDivider() 59 | PreferenceSection(title = stringResource(R.string.save_dialog)) { 60 | ActionPreference( 61 | title = stringResource(R.string.save_dialog), 62 | currentValue = stringResource( 63 | R.string.currently, 64 | stringResource(if (skipSaveDialog) R.string.hidden else R.string.shown) 65 | ).lowercase(), 66 | buttonText = stringResource(R.string.show_save_dialog), 67 | onButtonClick = { 68 | scope.launch { appPreferences.setSkipSaveDialog(false) } 69 | }, 70 | showButton = skipSaveDialog, 71 | infoText = stringResource(R.string.save_dialog_shown) 72 | ) 73 | } 74 | PreferenceDivider() 75 | PreferenceSection(title = stringResource(R.string.default_image_source)) { 76 | ActionPreference( 77 | title = stringResource(R.string.default_image_source), 78 | currentValue = stringResource( 79 | R.string.currently, 80 | defaultImageSource?.let { 81 | when (it) { 82 | "gallery" -> stringResource(R.string.gallery) 83 | "internal" -> stringResource(R.string.photos) 84 | "documents" -> stringResource(R.string.documents) 85 | "camera" -> stringResource(R.string.camera) 86 | else -> stringResource(R.string.none) 87 | } 88 | } ?: stringResource(R.string.none) 89 | ).lowercase(), 90 | buttonText = stringResource(R.string.clear_default_source), 91 | onButtonClick = { 92 | scope.launch { appPreferences.clearDefaultImageSource() } 93 | }, 94 | showButton = defaultImageSource != null, 95 | infoText = stringResource(R.string.no_default_source) 96 | ) 97 | } 98 | } 99 | }, 100 | confirmButton = { 101 | TextButton(onClick = { haptic.light(); onDismiss() }) { 102 | Text(stringResource(R.string.close)) 103 | } 104 | } 105 | ) 106 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/HapticFeedback.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils 2 | 3 | import android.content.Context 4 | import android.os.Build 5 | import android.view.HapticFeedbackConstants 6 | import android.view.View 7 | import androidx.compose.runtime.Composable 8 | import androidx.compose.runtime.collectAsState 9 | import androidx.compose.runtime.getValue 10 | import androidx.compose.runtime.remember 11 | import androidx.compose.ui.platform.LocalContext 12 | import androidx.compose.ui.platform.LocalView 13 | import com.je.dejpeg.data.AppPreferences 14 | 15 | object HapticFeedback { 16 | 17 | fun light(view: View, isEnabled: Boolean) { 18 | if (!isEnabled) return 19 | 20 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 21 | view.performHapticFeedback(HapticFeedbackConstants.GESTURE_START) 22 | } else { 23 | view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) 24 | } 25 | } 26 | 27 | fun medium(view: View, isEnabled: Boolean) { 28 | if (!isEnabled) return 29 | 30 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 31 | view.performHapticFeedback(HapticFeedbackConstants.CONFIRM) 32 | } else { 33 | view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) 34 | } 35 | } 36 | 37 | fun heavy(view: View, isEnabled: Boolean) { 38 | if (!isEnabled) return 39 | 40 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 41 | view.performHapticFeedback(HapticFeedbackConstants.REJECT) 42 | } else { 43 | view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) 44 | } 45 | } 46 | 47 | fun click(view: View, isEnabled: Boolean) { 48 | if (!isEnabled) return 49 | 50 | view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) 51 | } 52 | 53 | fun longPress(view: View, isEnabled: Boolean) { 54 | if (!isEnabled) return 55 | 56 | view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) 57 | } 58 | 59 | fun reject(view: View, isEnabled: Boolean) { 60 | if (!isEnabled) return 61 | 62 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 63 | view.performHapticFeedback(HapticFeedbackConstants.REJECT) 64 | } else { 65 | view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) 66 | } 67 | } 68 | 69 | fun confirm(view: View, isEnabled: Boolean) { 70 | if (!isEnabled) return 71 | 72 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 73 | view.performHapticFeedback(HapticFeedbackConstants.CONFIRM) 74 | } else { 75 | view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) 76 | } 77 | } 78 | 79 | fun error(view: View, isEnabled: Boolean) { 80 | if (!isEnabled) return 81 | 82 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 83 | view.performHapticFeedback(HapticFeedbackConstants.REJECT) 84 | } else { 85 | view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) 86 | } 87 | } 88 | 89 | fun success(view: View, isEnabled: Boolean) { 90 | if (!isEnabled) return 91 | 92 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 93 | view.performHapticFeedback(HapticFeedbackConstants.CONFIRM) 94 | } else { 95 | view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) 96 | } 97 | } 98 | 99 | fun gestureStart(view: View, isEnabled: Boolean) { 100 | if (!isEnabled) return 101 | 102 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 103 | view.performHapticFeedback(HapticFeedbackConstants.GESTURE_START) 104 | } else { 105 | view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) 106 | } 107 | } 108 | 109 | fun gestureEnd(view: View, isEnabled: Boolean) { 110 | if (!isEnabled) return 111 | 112 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { 113 | view.performHapticFeedback(HapticFeedbackConstants.GESTURE_END) 114 | } else { 115 | view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY) 116 | } 117 | } 118 | } 119 | 120 | @Composable 121 | fun rememberHapticFeedback(): HapticFeedbackPerformer { 122 | val view = LocalView.current 123 | val context = LocalContext.current 124 | val appPreferences = remember { AppPreferences.getInstance(context) } 125 | val isEnabled by appPreferences.hapticFeedbackEnabled.collectAsState(initial = true) 126 | 127 | return remember(view, isEnabled) { HapticFeedbackPerformer(view, isEnabled) } 128 | } 129 | 130 | class HapticFeedbackPerformer(private val view: View, private val isEnabled: Boolean) { 131 | fun light() = HapticFeedback.light(view, isEnabled) 132 | fun medium() = HapticFeedback.medium(view, isEnabled) 133 | fun heavy() = HapticFeedback.heavy(view, isEnabled) 134 | fun click() = HapticFeedback.click(view, isEnabled) 135 | fun longPress() = HapticFeedback.longPress(view, isEnabled) 136 | fun reject() = HapticFeedback.reject(view, isEnabled) 137 | fun confirm() = HapticFeedback.confirm(view, isEnabled) 138 | fun error() = HapticFeedback.error(view, isEnabled) 139 | fun success() = HapticFeedback.success(view, isEnabled) 140 | fun gestureStart() = HapticFeedback.gestureStart(view, isEnabled) 141 | fun gestureEnd() = HapticFeedback.gestureEnd(view, isEnabled) 142 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/MaterialSwitchViews.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import android.content.res.ColorStateList 4 | import android.view.LayoutInflater 5 | import android.widget.LinearLayout 6 | import android.widget.TextView 7 | import androidx.compose.material3.MaterialTheme 8 | import androidx.compose.runtime.Composable 9 | import androidx.compose.ui.Modifier 10 | import androidx.compose.ui.graphics.toArgb 11 | import androidx.compose.ui.viewinterop.AndroidView 12 | import com.google.android.material.materialswitch.MaterialSwitch 13 | import com.je.dejpeg.R 14 | 15 | /* 16 | * helper composables to use Material XML Switches in Jetpack Compose cause XML switches give a better UX (ur finger go brrr) 17 | */ 18 | 19 | @Composable 20 | fun MaterialSwitchRow( 21 | label: String, 22 | checked: Boolean, 23 | onCheckedChange: (Boolean) -> Unit, 24 | modifier: Modifier = Modifier 25 | ) { 26 | val primaryColor = MaterialTheme.colorScheme.primary.toArgb() 27 | val onPrimaryColor = MaterialTheme.colorScheme.onPrimary.toArgb() 28 | val surfaceVariantColor = MaterialTheme.colorScheme.surfaceVariant.toArgb() 29 | val outlineColor = MaterialTheme.colorScheme.outline.toArgb() 30 | val onSurfaceColor = MaterialTheme.colorScheme.onSurface.toArgb() 31 | val onSurfaceVariantColor = MaterialTheme.colorScheme.onSurfaceVariant.toArgb() 32 | 33 | AndroidView( 34 | modifier = modifier, 35 | factory = { context -> 36 | LayoutInflater.from(context).inflate(R.layout.dialog_switch_row, null) as LinearLayout 37 | }, 38 | update = { view -> 39 | val labelView = view.findViewById(R.id.switch_label) 40 | val switchView = view.findViewById(R.id.material_switch) 41 | 42 | labelView.text = label 43 | labelView.setTextColor(onSurfaceColor) 44 | applySwitchColors(switchView, primaryColor, onPrimaryColor, surfaceVariantColor, outlineColor, onSurfaceVariantColor) 45 | 46 | switchView.isChecked = checked 47 | switchView.setOnCheckedChangeListener { _, isChecked -> 48 | onCheckedChange(isChecked) 49 | } 50 | view.setOnClickListener { 51 | switchView.isChecked = !switchView.isChecked 52 | } 53 | } 54 | ) 55 | } 56 | 57 | @Composable 58 | fun MaterialSwitchPreference( 59 | title: String, 60 | summary: String, 61 | checked: Boolean, 62 | onCheckedChange: (Boolean) -> Unit, 63 | modifier: Modifier = Modifier, 64 | enabled: Boolean = true 65 | ) { 66 | val primaryColor = MaterialTheme.colorScheme.primary.toArgb() 67 | val onPrimaryColor = MaterialTheme.colorScheme.onPrimary.toArgb() 68 | val surfaceVariantColor = MaterialTheme.colorScheme.surfaceVariant.toArgb() 69 | val outlineColor = MaterialTheme.colorScheme.outline.toArgb() 70 | val onSurfaceColor = MaterialTheme.colorScheme.onSurface.toArgb() 71 | val onSurfaceVariantColor = MaterialTheme.colorScheme.onSurfaceVariant.toArgb() 72 | 73 | AndroidView( 74 | modifier = modifier, 75 | factory = { context -> 76 | LayoutInflater.from(context).inflate(R.layout.preference_switch_row, null) as LinearLayout 77 | }, 78 | update = { view -> 79 | val titleView = view.findViewById(R.id.preference_title) 80 | val summaryView = view.findViewById(R.id.preference_summary) 81 | val switchView = view.findViewById(R.id.preference_switch) 82 | 83 | titleView.text = title 84 | titleView.setTextColor(onSurfaceColor) 85 | summaryView.text = summary 86 | summaryView.setTextColor(onSurfaceVariantColor) 87 | applySwitchColors(switchView, primaryColor, onPrimaryColor, surfaceVariantColor, outlineColor, onSurfaceVariantColor) 88 | 89 | switchView.isChecked = checked 90 | switchView.isEnabled = enabled 91 | 92 | view.isEnabled = enabled 93 | view.alpha = if (enabled) 1f else 0.38f 94 | 95 | switchView.setOnCheckedChangeListener { _, isChecked -> 96 | if (enabled) { 97 | onCheckedChange(isChecked) 98 | } 99 | } 100 | view.setOnClickListener { 101 | if (enabled) { 102 | switchView.isChecked = !switchView.isChecked 103 | } 104 | } 105 | } 106 | ) 107 | } 108 | 109 | private fun applySwitchColors( 110 | switchView: MaterialSwitch, 111 | primaryColor: Int, 112 | onPrimaryColor: Int, 113 | surfaceVariantColor: Int, 114 | outlineColor: Int, 115 | onSurfaceVariantColor: Int 116 | ) { 117 | switchView.trackTintList = ColorStateList( 118 | arrayOf( 119 | intArrayOf(android.R.attr.state_checked), 120 | intArrayOf(-android.R.attr.state_checked) 121 | ), 122 | intArrayOf(primaryColor, surfaceVariantColor) 123 | ) 124 | switchView.thumbTintList = ColorStateList( 125 | arrayOf( 126 | intArrayOf(android.R.attr.state_checked), 127 | intArrayOf(-android.R.attr.state_checked) 128 | ), 129 | intArrayOf(onPrimaryColor, outlineColor) 130 | ) 131 | switchView.trackDecorationTintList = ColorStateList( 132 | arrayOf( 133 | intArrayOf(android.R.attr.state_checked), 134 | intArrayOf(-android.R.attr.state_checked) 135 | ), 136 | intArrayOf(primaryColor, outlineColor) 137 | ) 138 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg 2 | 3 | import android.Manifest 4 | import android.content.Intent 5 | import android.content.pm.PackageManager 6 | import android.net.Uri 7 | import android.os.Build 8 | import android.os.Bundle 9 | import androidx.activity.ComponentActivity 10 | import androidx.activity.SystemBarStyle 11 | import androidx.activity.compose.setContent 12 | import androidx.activity.enableEdgeToEdge 13 | import androidx.activity.result.contract.ActivityResultContracts 14 | import androidx.compose.foundation.isSystemInDarkTheme 15 | import androidx.compose.foundation.layout.fillMaxSize 16 | import androidx.compose.material3.MaterialTheme 17 | import androidx.compose.material3.Surface 18 | import androidx.compose.runtime.SideEffect 19 | import androidx.compose.ui.Modifier 20 | import androidx.core.content.ContextCompat 21 | import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen 22 | import com.je.dejpeg.compose.utils.CacheManager 23 | import com.je.dejpeg.ui.MainScreen 24 | import com.je.dejpeg.ui.theme.DeJPEGTheme 25 | 26 | class MainActivity : ComponentActivity() { 27 | private val sharedUrisState = androidx.compose.runtime.mutableStateListOf() 28 | 29 | private val notificationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission() 30 | ) { isGranted -> 31 | if (isGranted) { 32 | // granted 33 | } else { 34 | // denied - nothing shown cause its annoying 35 | } 36 | } 37 | 38 | override fun onCreate(savedInstanceState: Bundle?) { 39 | installSplashScreen() 40 | super.onCreate(savedInstanceState) 41 | if (savedInstanceState == null) { 42 | CacheManager.cleanEntireCacheSync(this) 43 | } 44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 45 | if (ContextCompat.checkSelfPermission( 46 | this, 47 | Manifest.permission.POST_NOTIFICATIONS 48 | ) != PackageManager.PERMISSION_GRANTED 49 | ) { 50 | notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) 51 | } 52 | } 53 | handleShareIntent(intent) 54 | 55 | // https://stackoverflow.com/a/79267436 56 | setContent { 57 | val isDarkTheme = isSystemInDarkTheme() 58 | SideEffect { 59 | if (!isDarkTheme) { 60 | val lightTransparentStyle = SystemBarStyle.light( 61 | scrim = android.graphics.Color.TRANSPARENT, 62 | darkScrim = android.graphics.Color.TRANSPARENT 63 | ) 64 | enableEdgeToEdge( 65 | statusBarStyle = lightTransparentStyle, 66 | navigationBarStyle = lightTransparentStyle 67 | ) 68 | } else { 69 | val darkTransparentStyle = SystemBarStyle.dark( 70 | scrim = android.graphics.Color.TRANSPARENT 71 | ) 72 | enableEdgeToEdge( 73 | statusBarStyle = darkTransparentStyle, 74 | navigationBarStyle = darkTransparentStyle 75 | ) 76 | } 77 | } 78 | DeJPEGTheme { 79 | Surface( 80 | modifier = Modifier.fillMaxSize(), 81 | color = MaterialTheme.colorScheme.background 82 | ) { 83 | MainScreen(sharedUris = sharedUrisState) 84 | } 85 | } 86 | } 87 | } 88 | 89 | override fun onNewIntent(intent: Intent) { 90 | super.onNewIntent(intent) 91 | setIntent(intent) 92 | handleShareIntent(intent) 93 | } 94 | 95 | private fun handleShareIntent(intent: Intent?) { 96 | if (intent == null) return 97 | when (intent.action) { 98 | Intent.ACTION_SEND -> { 99 | val uri: Uri? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 100 | intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) 101 | } else { 102 | @Suppress("DEPRECATION") 103 | intent.getParcelableExtra(Intent.EXTRA_STREAM) 104 | } 105 | uri?.let { addSharedUri(it, intent.flags) } 106 | } 107 | Intent.ACTION_SEND_MULTIPLE -> { 108 | val uris: List = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 109 | intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM, Uri::class.java) ?: emptyList() 110 | } else { 111 | @Suppress("DEPRECATION") 112 | intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) ?: emptyList() 113 | } 114 | uris.forEach { addSharedUri(it, intent.flags) } 115 | } 116 | } 117 | } 118 | 119 | private fun addSharedUri(uri: Uri, flags: Int) { 120 | if (sharedUrisState.any { it == uri }) return 121 | try { 122 | val takeFlags = flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) 123 | contentResolver.takePersistableUriPermission(uri, takeFlags and Intent.FLAG_GRANT_READ_URI_PERMISSION) 124 | } catch (_: Exception) { /* o */ } 125 | sharedUrisState.add(uri) 126 | } 127 | 128 | override fun onDestroy() { 129 | super.onDestroy() 130 | CacheManager.cleanEntireCacheSync(this) 131 | } 132 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/ChunkDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.* 4 | import androidx.compose.foundation.rememberScrollState 5 | import androidx.compose.foundation.verticalScroll 6 | import androidx.compose.material3.* 7 | import androidx.compose.runtime.* 8 | import androidx.compose.ui.Modifier 9 | import androidx.compose.ui.res.stringResource 10 | import androidx.compose.ui.text.font.FontWeight 11 | import androidx.compose.ui.unit.dp 12 | import com.je.dejpeg.R 13 | import kotlin.math.roundToInt 14 | 15 | @Composable 16 | fun ChunkDialog( 17 | chunk: Int, 18 | overlap: Int, 19 | onChunkChange: (Int) -> Unit, 20 | onOverlapChange: (Int) -> Unit, 21 | onDismiss: () -> Unit 22 | ) { 23 | var chunkSize by remember { mutableIntStateOf(chunk) } 24 | var overlapSize by remember { mutableIntStateOf(overlap) } 25 | val haptic = com.je.dejpeg.compose.utils.rememberHapticFeedback() 26 | val chunkPowers = generateSequence(16) { it * 2 }.takeWhile { it <= 2048 }.toList() 27 | val overlapPowers = generateSequence(8) { it * 2 }.takeWhile { it <= 256 }.toList() 28 | 29 | @Composable 30 | fun powerSlider( 31 | label: String, 32 | value: Int, 33 | powers: List, 34 | maxAllowed: Int = Int.MAX_VALUE, 35 | onChange: (Int) -> Unit 36 | ) { 37 | val availablePowers = powers.filter { it < maxAllowed } 38 | val effectivePowers = if (availablePowers.isEmpty()) listOf(powers.first()) else availablePowers 39 | val clampedValue = value.coerceAtMost(effectivePowers.last()) 40 | var index by remember(clampedValue, effectivePowers) { 41 | mutableIntStateOf(effectivePowers.indexOf(clampedValue).coerceAtLeast(0)) 42 | } 43 | LaunchedEffect(maxAllowed) { 44 | if (value >= maxAllowed && effectivePowers.isNotEmpty()) { 45 | onChange(effectivePowers.last()) 46 | } 47 | } 48 | 49 | Column { 50 | Text(label, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Medium) 51 | Slider( 52 | value = index.toFloat(), 53 | onValueChange = { 54 | val newIdx = it.roundToInt().coerceIn(effectivePowers.indices) 55 | if (newIdx != index) { 56 | index = newIdx 57 | haptic.light() 58 | onChange(effectivePowers[newIdx]) 59 | } 60 | }, 61 | valueRange = 0f..(effectivePowers.lastIndex.toFloat().coerceAtLeast(0f)), 62 | steps = (effectivePowers.size - 2).coerceAtLeast(0), 63 | enabled = effectivePowers.size > 1 64 | ) 65 | Row { 66 | Text( 67 | "${effectivePowers[index]}px", 68 | style = MaterialTheme.typography.labelLarge, 69 | fontWeight = FontWeight.SemiBold, 70 | color = MaterialTheme.colorScheme.primary 71 | ) 72 | } 73 | } 74 | } 75 | 76 | val dialogWidth = rememberDialogWidth() 77 | AlertDialog( 78 | onDismissRequest = onDismiss, 79 | modifier = Modifier.dialogWidth(dialogWidth), 80 | properties = DialogDefaults.Properties, 81 | shape = DialogDefaults.Shape, 82 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 83 | title = { Text(stringResource(R.string.chunk_settings)) }, 84 | text = { 85 | Column(Modifier.verticalScroll(rememberScrollState())) { 86 | powerSlider(stringResource(R.string.chunk_size), chunkSize, chunkPowers) { chunkSize = it } 87 | if (chunkSize >= 2048) { 88 | Text( 89 | stringResource(R.string.large_chunk_warning, chunkSize), 90 | style = MaterialTheme.typography.bodySmall, 91 | color = MaterialTheme.colorScheme.error, 92 | modifier = Modifier.padding(vertical = 8.dp) 93 | ) 94 | } 95 | Spacer(Modifier.height(16.dp)) 96 | powerSlider( 97 | label = stringResource(R.string.overlap_size), 98 | value = overlapSize, 99 | powers = overlapPowers, 100 | maxAllowed = chunkSize, 101 | onChange = { overlapSize = it } 102 | ) 103 | Spacer(Modifier.height(16.dp)) 104 | Card( 105 | modifier = Modifier.fillMaxWidth(), 106 | colors = CardDefaults.cardColors( 107 | containerColor = MaterialTheme.colorScheme.secondaryContainer 108 | ) 109 | ) { 110 | Text( 111 | stringResource(R.string.note_chunk_info, chunkSize), 112 | style = MaterialTheme.typography.bodySmall, 113 | color = MaterialTheme.colorScheme.onSecondaryContainer, 114 | modifier = Modifier.padding(12.dp) 115 | ) 116 | } 117 | } 118 | }, 119 | confirmButton = { 120 | TextButton(onClick = { 121 | haptic.medium() 122 | onChunkChange(chunkSize) 123 | onOverlapChange(overlapSize) 124 | onDismiss() 125 | }) { 126 | Text(stringResource(R.string.save)) 127 | } 128 | }, 129 | dismissButton = { 130 | TextButton(onClick = { haptic.light(); onDismiss() }) { 131 | Text(stringResource(R.string.cancel)) 132 | } 133 | } 134 | ) 135 | } -------------------------------------------------------------------------------- /app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | // ./gradlew clean assembleRelease -PsignApk=true 2 | 3 | plugins { 4 | alias(libs.plugins.android.application) 5 | alias(libs.plugins.kotlin.android) 6 | alias(libs.plugins.kotlin.compose) 7 | } 8 | 9 | android { 10 | namespace = "com.je.dejpeg" 11 | compileSdk { 12 | version = release(36) 13 | } 14 | defaultConfig { 15 | applicationId = "com.je.dejpeg" 16 | minSdk = 24 17 | targetSdk = 36 18 | versionCode = 320 19 | versionName = "3.2.0" 20 | } 21 | signingConfigs { 22 | if (project.hasProperty("signApk") && project.property("signApk") == "true") { 23 | create("release") { 24 | storeFile = file(System.getenv("KEYSTORE_PATH") ?: "") 25 | storePassword = System.getenv("KEYSTORE_PASSWORD") ?: "" 26 | keyAlias = System.getenv("KEYSTORE_ALIAS") ?: "" 27 | keyPassword = System.getenv("KEY_PASSWORD") ?: "" 28 | } 29 | } 30 | } 31 | buildTypes { 32 | getByName("release") { 33 | isMinifyEnabled = true 34 | isShrinkResources = true 35 | isDebuggable = false 36 | proguardFiles( 37 | getDefaultProguardFile("proguard-android-optimize.txt"), 38 | "proguard-rules.pro" 39 | ) 40 | if (project.hasProperty("signApk") && project.property("signApk") == "true") { 41 | signingConfig = signingConfigs.getByName("release") 42 | } 43 | } 44 | getByName("debug") { 45 | isDebuggable = true 46 | applicationIdSuffix = ".debug" 47 | versionNameSuffix = "-debug" 48 | } 49 | } 50 | splits { 51 | abi { 52 | isEnable = true 53 | reset() 54 | if (project.hasProperty("targetAbi")) { 55 | include(project.property("targetAbi") as String) 56 | } else { 57 | include("arm64-v8a") 58 | } 59 | isUniversalApk = false 60 | } 61 | applicationVariants.all { 62 | outputs.all { 63 | val output = this 64 | val appName = "dejpeg" 65 | val abiFilter = output.filters.find { it.filterType == com.android.build.api.variant.FilterConfiguration.FilterType.ABI.name }?.identifier 66 | val variantName = name 67 | val debugSuffix = if (variantName.contains("debug", ignoreCase = true)) "-debug" else "" 68 | val apkName = if (abiFilter != null) "$appName-$abiFilter$debugSuffix.apk" else "$appName-universal$debugSuffix.apk" 69 | if (output is com.android.build.gradle.internal.api.BaseVariantOutputImpl) { 70 | output.outputFileName = apkName 71 | } 72 | } 73 | } 74 | } 75 | compileOptions { 76 | sourceCompatibility = JavaVersion.VERSION_17 77 | targetCompatibility = JavaVersion.VERSION_17 78 | } 79 | kotlin { 80 | compilerOptions { 81 | jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) 82 | } 83 | } 84 | buildFeatures { 85 | compose = true 86 | } 87 | if (System.getenv("BUILD_BRISQUE_JNI") == "ON") { 88 | externalNativeBuild { 89 | cmake { 90 | path = file("src/main/cpp/CMakeLists.txt") 91 | version = "3.22.1" 92 | } 93 | } 94 | } 95 | ndkVersion = "27.3.13750724" 96 | sourceSets { 97 | getByName("main") { 98 | jniLibs.srcDir("src/main/jniLibs") 99 | } 100 | } 101 | packaging { 102 | jniLibs { 103 | pickFirsts += "lib/*/libonnxruntime.so" 104 | } 105 | } 106 | } 107 | 108 | dependencies { 109 | implementation(libs.androidx.core.ktx) 110 | implementation(libs.androidx.lifecycle.runtime.ktx) 111 | implementation(libs.androidx.activity.compose) 112 | implementation(platform(libs.androidx.compose.bom)) 113 | implementation(libs.androidx.compose.ui) 114 | implementation(libs.androidx.compose.ui.graphics) 115 | implementation(libs.androidx.compose.ui.tooling.preview) 116 | implementation(libs.androidx.compose.material3) 117 | implementation(libs.androidx.compose.material3.adaptive.navigation.suite) 118 | implementation(libs.androidx.navigation.compose) 119 | implementation(libs.androidx.compose.foundation) 120 | implementation(libs.androidx.compose.material.icons.extended) 121 | implementation(libs.google.material) 122 | implementation(libs.onnxruntime.android) 123 | implementation(libs.zoomable) 124 | implementation(libs.androidx.exifinterface) 125 | implementation(libs.androidx.core.splashscreen) 126 | implementation(libs.androidx.datastore.preferences) 127 | } 128 | 129 | tasks.register("cleandir") { 130 | group = "build" 131 | description = "clean ./apks directory before build." 132 | doFirst { 133 | val destDir = file("${rootProject.rootDir}/apks") 134 | if (destDir.exists()) { 135 | destDir.deleteRecursively() 136 | println("deleted $destDir") 137 | } 138 | } 139 | } 140 | 141 | if (project.hasProperty("signApk") && project.property("signApk") == "true") { 142 | tasks.register("move") { 143 | group = "build" 144 | description = "move apks to the root ./apks directory." 145 | doLast { 146 | val apkDir = file("${layout.buildDirectory.get()}/outputs/apk") 147 | val destDir = file("${rootProject.rootDir}/apks") 148 | if (!destDir.exists()) destDir.mkdirs() 149 | apkDir.walkTopDown().filter { it.isFile && it.extension == "apk" }.forEach { apk -> 150 | apk.copyTo(destDir.resolve(apk.name), overwrite = true) 151 | } 152 | println("moved apks to $destDir") 153 | } 154 | } 155 | } 156 | 157 | tasks.matching { it.name.startsWith("assemble") }.configureEach { 158 | dependsOn("cleandir") 159 | if (project.hasProperty("signApk") && project.property("signApk") == "true") { 160 | finalizedBy("move") 161 | } 162 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/ImageActions.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils 2 | 3 | import android.content.Context 4 | import android.content.Intent 5 | import android.graphics.Bitmap 6 | import android.media.MediaScannerConnection 7 | import android.os.Environment 8 | import android.widget.Toast 9 | import androidx.core.content.FileProvider 10 | import java.io.File 11 | import java.io.FileOutputStream 12 | import java.text.SimpleDateFormat 13 | import java.util.* 14 | import kotlinx.coroutines.DelicateCoroutinesApi 15 | import kotlinx.coroutines.Dispatchers 16 | import kotlinx.coroutines.GlobalScope 17 | import kotlinx.coroutines.launch 18 | import kotlinx.coroutines.withContext 19 | import android.content.ClipData 20 | import com.je.dejpeg.R 21 | 22 | object ImageActions { 23 | fun checkFileExists(context: Context, filename: String): Boolean { 24 | val fileNameRaw = filename.takeIf { it.isNotBlank() } ?: return false 25 | val fileName = fileNameRaw.substringBeforeLast('.', fileNameRaw) 26 | val picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) 27 | val outputFile = File(picturesDir, "$fileName.png") 28 | return outputFile.exists() 29 | } 30 | 31 | fun saveImage(context: Context, bitmap: Bitmap, filename: String? = null, onSuccess: () -> Unit = {}, onError: (String) -> Unit = {}) { 32 | @OptIn(DelicateCoroutinesApi::class) 33 | GlobalScope.launch(Dispatchers.IO) { 34 | try { 35 | val fileNameRaw = filename?.takeIf { it.isNotBlank() } ?: "DeJPEG_${SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())}" 36 | val fileName = fileNameRaw.substringBeforeLast('.', fileNameRaw) 37 | val picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) 38 | val outputFile = File(picturesDir, "$fileName.png") 39 | if (outputFile.exists()) outputFile.delete() 40 | FileOutputStream(outputFile).use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } 41 | withContext(Dispatchers.Main) { 42 | MediaScannerConnection.scanFile(context, arrayOf(outputFile.toString()), null, null) 43 | Toast.makeText(context, context.getString(R.string.image_saved_to_gallery), Toast.LENGTH_SHORT).show() 44 | onSuccess() 45 | } 46 | } catch (e: Exception) { 47 | val errorMsg = context.getString(R.string.error_saving_image, e.message) 48 | withContext(Dispatchers.Main) { 49 | Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show() 50 | onError(errorMsg) 51 | } 52 | } 53 | } 54 | } 55 | 56 | fun shareImage(context: Context, bitmap: Bitmap, onError: (String) -> Unit = {}) { 57 | try { 58 | val cachePath = File(context.cacheDir, "shared_image.png") 59 | FileOutputStream(cachePath).use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } 60 | val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.provider", cachePath) 61 | val shareIntent = Intent(Intent.ACTION_SEND).apply { 62 | setType("image/png") 63 | putExtra(Intent.EXTRA_STREAM, contentUri) 64 | addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) 65 | clipData = ClipData.newRawUri(null, contentUri) 66 | } 67 | context.startActivity(Intent.createChooser(shareIntent, context.getString(R.string.share_image))) 68 | } catch (e: Exception) { 69 | val errorMsg = context.getString(R.string.error_sharing_image, e.message) 70 | Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show() 71 | onError(errorMsg) 72 | } 73 | } 74 | 75 | fun saveAllImages(context: Context, images: List>, baseFilename: String? = null, onProgress: (Int, Int) -> Unit = { _, _ -> }, onComplete: () -> Unit = {}, onError: (String) -> Unit = {}) { 76 | @OptIn(DelicateCoroutinesApi::class) 77 | GlobalScope.launch(Dispatchers.IO) { 78 | try { 79 | val usedFilenames = mutableSetOf() 80 | images.forEachIndexed { index, (originalFilename, bitmap) -> 81 | val preferredFilenameRaw = if (images.size > 1) originalFilename.ifBlank { "${baseFilename ?: "DeJPEG"}_${index + 1}" } else originalFilename.ifBlank { baseFilename ?: "DeJPEG" } 82 | val preferredFilename = preferredFilenameRaw.substringBeforeLast('.', preferredFilenameRaw) 83 | val fileName = generateUniqueFilename(preferredFilename, usedFilenames) 84 | usedFilenames.add(fileName) 85 | val outputFile = saveBitmapToPictures(fileName, bitmap) 86 | MediaScannerConnection.scanFile(context, arrayOf(outputFile.toString()), null, null) 87 | withContext(Dispatchers.Main) { 88 | onProgress(index + 1, images.size) 89 | } 90 | } 91 | withContext(Dispatchers.Main) { 92 | Toast.makeText(context, context.getString(R.string.all_images_saved_to_gallery, images.size), Toast.LENGTH_SHORT).show() 93 | onComplete() 94 | } 95 | } catch (e: Exception) { 96 | val errorMsg = context.getString(R.string.error_saving_images, e.message) 97 | withContext(Dispatchers.Main) { 98 | Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show() 99 | onError(errorMsg) 100 | } 101 | } 102 | } 103 | } 104 | 105 | private fun saveBitmapToPictures(baseName: String, bitmap: Bitmap): File { 106 | val outputFile = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "$baseName.png") 107 | FileOutputStream(outputFile).use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } 108 | return outputFile 109 | } 110 | 111 | private fun generateUniqueFilename(base: String, existing: Set): String { 112 | if (!existing.contains(base)) return base 113 | var counter = 1 114 | var newName = "${base}_$counter" 115 | while (existing.contains(newName)) { counter++; newName = "${base}_$counter" } 116 | return newName 117 | } 118 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/DownloadModelDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import android.content.Intent 4 | import android.widget.Toast 5 | import androidx.compose.foundation.layout.* 6 | import androidx.compose.foundation.rememberScrollState 7 | import androidx.compose.foundation.shape.RoundedCornerShape 8 | import androidx.compose.foundation.verticalScroll 9 | import androidx.compose.material.icons.Icons 10 | import androidx.compose.material.icons.filled.Download 11 | import androidx.compose.material3.* 12 | import androidx.compose.runtime.Composable 13 | import androidx.compose.ui.Modifier 14 | import androidx.compose.ui.platform.LocalContext 15 | import androidx.compose.ui.res.stringResource 16 | import androidx.compose.ui.text.font.FontWeight 17 | import androidx.compose.ui.unit.dp 18 | import androidx.core.net.toUri 19 | import com.je.dejpeg.R 20 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 21 | 22 | data class ModelDownloadItem( 23 | val name: String, 24 | val url: String, 25 | val description: String = "" 26 | ) 27 | 28 | @Composable 29 | fun DownloadModelDialog( 30 | onDismiss: () -> Unit, 31 | onSuccess: (String) -> Unit = {} 32 | ) { 33 | val context = LocalContext.current 34 | val haptic = rememberHapticFeedback() 35 | val dialogWidth = rememberDialogWidth() 36 | val models = listOf( 37 | ModelDownloadItem( 38 | stringResource(R.string.fbcnn_model), 39 | "https://github.com/jeeneo/fbcnn-mobile/releases/latest", 40 | "JPEG restoration" 41 | ), 42 | ModelDownloadItem( 43 | stringResource(R.string.scunet_model), 44 | "https://github.com/jeeneo/scunet-mobile/releases/latest", 45 | "Image denoising" 46 | ), 47 | ModelDownloadItem( 48 | stringResource(R.string.experimental_models), 49 | "https://github.com/jeeneo/dejpeg-experimental/releases/latest", 50 | "Untested other models" 51 | ) 52 | ) 53 | 54 | AlertDialog( 55 | onDismissRequest = onDismiss, 56 | modifier = Modifier.dialogWidth(dialogWidth), 57 | properties = DialogDefaults.Properties, 58 | shape = DialogDefaults.Shape, 59 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 60 | title = { 61 | Text( 62 | stringResource(R.string.download_models), 63 | style = MaterialTheme.typography.titleLarge, 64 | fontWeight = FontWeight.Bold 65 | ) 66 | }, 67 | text = { 68 | Column( 69 | modifier = Modifier 70 | .fillMaxWidth() 71 | .verticalScroll(rememberScrollState()) 72 | ) { 73 | Text( 74 | stringResource(R.string.choose_model_to_download), 75 | style = MaterialTheme.typography.bodyMedium, 76 | color = MaterialTheme.colorScheme.onSurfaceVariant, 77 | modifier = Modifier.padding(bottom = 16.dp) 78 | ) 79 | models.forEach { model -> 80 | ModelDownloadCard( 81 | model = model, 82 | onDownloadClick = { 83 | try { 84 | context.startActivity( 85 | Intent(Intent.ACTION_VIEW, model.url.toUri()) 86 | ) 87 | onSuccess(model.name) 88 | } catch (_: Exception) { 89 | Toast.makeText( 90 | context, 91 | context.getString(R.string.cannot_open_link), 92 | Toast.LENGTH_SHORT 93 | ).show() 94 | } 95 | } 96 | ) 97 | Spacer(modifier = Modifier.height(12.dp)) 98 | } 99 | } 100 | }, 101 | confirmButton = { 102 | TextButton(onClick = { haptic.light(); onDismiss() }) { 103 | Text(stringResource(R.string.close)) 104 | } 105 | } 106 | ) 107 | } 108 | 109 | @Composable 110 | private fun ModelDownloadCard( 111 | model: ModelDownloadItem, 112 | onDownloadClick: () -> Unit 113 | ) { 114 | val haptic = rememberHapticFeedback() 115 | ElevatedCard( 116 | modifier = Modifier.fillMaxWidth(), 117 | shape = RoundedCornerShape(12.dp), 118 | colors = CardDefaults.elevatedCardColors( 119 | containerColor = MaterialTheme.colorScheme.surfaceContainerLow 120 | ), 121 | elevation = CardDefaults.elevatedCardElevation( 122 | defaultElevation = 2.dp 123 | ) 124 | ) { 125 | Column( 126 | modifier = Modifier 127 | .fillMaxWidth() 128 | .padding(16.dp) 129 | ) { 130 | Text( 131 | text = model.name, 132 | style = MaterialTheme.typography.bodyLarge, 133 | fontWeight = FontWeight.SemiBold, 134 | color = MaterialTheme.colorScheme.onSurface 135 | ) 136 | 137 | if (model.description.isNotEmpty()) { 138 | Spacer(modifier = Modifier.height(4.dp)) 139 | Text( 140 | text = model.description, 141 | style = MaterialTheme.typography.bodySmall, 142 | color = MaterialTheme.colorScheme.onSurfaceVariant 143 | ) 144 | } 145 | 146 | Spacer(modifier = Modifier.height(12.dp)) 147 | 148 | FilledTonalButton( 149 | onClick = { 150 | haptic.medium() 151 | onDownloadClick() 152 | }, 153 | modifier = Modifier 154 | .fillMaxWidth() 155 | .height(40.dp), 156 | shape = RoundedCornerShape(8.dp) 157 | ) { 158 | Icon( 159 | imageVector = Icons.Filled.Download, 160 | contentDescription = null, 161 | modifier = Modifier.size(18.dp) 162 | ) 163 | Spacer(modifier = Modifier.width(8.dp)) 164 | Text(stringResource(R.string.download)) 165 | } 166 | } 167 | } 168 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/TimeEstimator.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg 2 | 3 | import android.content.Context 4 | import com.je.dejpeg.data.dataStore 5 | import androidx.datastore.preferences.core.edit 6 | import androidx.datastore.preferences.core.longPreferencesKey 7 | import kotlinx.coroutines.Dispatchers 8 | import kotlinx.coroutines.GlobalScope 9 | import kotlinx.coroutines.flow.first 10 | import kotlinx.coroutines.flow.map 11 | import kotlinx.coroutines.launch 12 | import kotlinx.coroutines.runBlocking 13 | 14 | class TimeEstimator( 15 | private val context: Context, 16 | private val modelName: String, 17 | private val chunkSize: Int = DEFAULT_CHUNK_SIZE 18 | ) { 19 | companion object { 20 | private const val DEFAULT_CHUNK_SIZE = 512 21 | private const val REFERENCE_CHUNK_SIZE = 512 22 | 23 | fun formatTimeRemaining(millis: Long, finishingUpText: String = "Finishing up..."): String { 24 | if (millis < 0) return "" 25 | val seconds = (millis / 1000).coerceAtLeast(0) 26 | return when { 27 | seconds <= 0 -> finishingUpText 28 | seconds < 60 -> "$seconds s" 29 | seconds < 3600 -> { 30 | val minutes = seconds / 60 31 | val remainingSeconds = seconds % 60 32 | if (remainingSeconds == 0L) { 33 | if (minutes == 1L) "1 minute" else "$minutes m" 34 | } else { 35 | if (minutes == 1L) "1m, $remainingSeconds s" else "$minutes m, $remainingSeconds s" 36 | } 37 | } 38 | else -> { 39 | val hours = seconds / 3600 40 | val remainingMinutes = (seconds % 3600) / 60 41 | if (remainingMinutes == 0L) { 42 | if (hours == 1L) "1 h" else "$hours h" 43 | } else { 44 | if (hours == 1L) "1 h, $remainingMinutes m" else "$hours h, $remainingMinutes m" 45 | } 46 | } 47 | } 48 | } 49 | } 50 | 51 | private val avgTimeKey = longPreferencesKey("time_avg_normalized_${modelName}") 52 | private var chunkStartTime: Long = 0 53 | private val chunkTimes = mutableListOf() 54 | private var inMemoryAverage: Long = 0 55 | private var cachedStoredAverage: Long? = null 56 | private var hasStoredHistory: Boolean = false 57 | private val chunkScaleFactor: Double 58 | get() { 59 | val currentArea = chunkSize.toLong() * chunkSize 60 | val referenceArea = REFERENCE_CHUNK_SIZE.toLong() * REFERENCE_CHUNK_SIZE 61 | return currentArea.toDouble() / referenceArea 62 | } 63 | 64 | fun getStoredAverageTime(): Long? { 65 | if (cachedStoredAverage != null) return cachedStoredAverage 66 | return runBlocking { 67 | context.dataStore.data.map { prefs -> 68 | prefs[avgTimeKey]?.also { hasStoredHistory = true } 69 | }.first().also { cachedStoredAverage = it } 70 | } 71 | } 72 | 73 | private fun getScaledStoredAverage(): Long? { 74 | val normalizedAvg = getStoredAverageTime() ?: return null 75 | return (normalizedAvg * chunkScaleFactor).toLong() 76 | } 77 | 78 | fun hasHistory(): Boolean { 79 | if (cachedStoredAverage == null) { 80 | getStoredAverageTime() 81 | } 82 | return hasStoredHistory || chunkTimes.isNotEmpty() 83 | } 84 | 85 | private suspend fun saveAverageTimeAsync(avgTime: Long) { 86 | cachedStoredAverage = avgTime 87 | context.dataStore.edit { prefs -> 88 | prefs[avgTimeKey] = avgTime 89 | } 90 | } 91 | 92 | private fun saveAverageTime(avgTime: Long) { 93 | cachedStoredAverage = avgTime 94 | GlobalScope.launch(Dispatchers.IO) { 95 | saveAverageTimeAsync(avgTime) 96 | } 97 | } 98 | 99 | fun startProcessing() { 100 | chunkTimes.clear() 101 | if (inMemoryAverage == 0L) { 102 | inMemoryAverage = getScaledStoredAverage() ?: 0L 103 | } 104 | } 105 | 106 | fun startChunk() { 107 | chunkStartTime = System.currentTimeMillis() 108 | } 109 | 110 | fun endChunk() { 111 | if (chunkStartTime > 0) { 112 | val chunkTime = System.currentTimeMillis() - chunkStartTime 113 | chunkTimes.add(chunkTime) 114 | updateAverageTime() 115 | chunkStartTime = 0 116 | } 117 | } 118 | 119 | private fun updateAverageTime() { 120 | if (chunkTimes.isEmpty()) return 121 | val newChunkTime = chunkTimes.last() 122 | val normalizedNewTime = (newChunkTime / chunkScaleFactor).toLong() 123 | val currentNormalizedAverage = getStoredAverageTime() 124 | val updatedNormalizedAverage = if (currentNormalizedAverage != null && currentNormalizedAverage > 0) { 125 | (currentNormalizedAverage * 0.8 + normalizedNewTime * 0.2).toLong() 126 | } else { 127 | normalizedNewTime 128 | } 129 | inMemoryAverage = (updatedNormalizedAverage * chunkScaleFactor).toLong() 130 | saveAverageTime(updatedNormalizedAverage) 131 | } 132 | 133 | fun getEstimatedTimeRemaining(completedChunks: Int, totalChunks: Int): Long { 134 | if (totalChunks <= 0 || completedChunks >= totalChunks) return 0 135 | val remainingChunks = totalChunks - completedChunks 136 | 137 | val perChunkMs: Double = if (chunkTimes.isNotEmpty()) { 138 | val recentTimes = chunkTimes.takeLast(3) 139 | recentTimes.average() 140 | } else if (inMemoryAverage > 0) { 141 | inMemoryAverage.toDouble() 142 | } else { 143 | val scaled = getScaledStoredAverage() 144 | if (scaled != null && scaled > 0) scaled.toDouble() else return -1L 145 | } 146 | 147 | return if (chunkStartTime > 0) { 148 | val currentChunkElapsed = System.currentTimeMillis() - chunkStartTime 149 | val currentChunkRemaining = (perChunkMs - currentChunkElapsed).coerceAtLeast(0.0) 150 | val futureChunksTime = perChunkMs * (remainingChunks - 1).coerceAtLeast(0) 151 | (currentChunkRemaining + futureChunksTime).toLong() 152 | } else { 153 | (perChunkMs * remainingChunks).toLong() 154 | } 155 | } 156 | 157 | fun getInitialEstimate(totalChunks: Int): Long { 158 | if (totalChunks <= 0) return -1L 159 | 160 | val perChunkMs: Long = when { 161 | chunkTimes.isNotEmpty() -> chunkTimes.average().toLong() 162 | inMemoryAverage > 0 -> inMemoryAverage 163 | else -> getScaledStoredAverage() ?: return -1L 164 | } 165 | 166 | return perChunkMs * totalChunks 167 | } 168 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/utils/helpers/ServiceCommunicationHelper.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.utils.helpers 2 | 3 | import android.annotation.SuppressLint 4 | import android.content.BroadcastReceiver 5 | import android.content.Context 6 | import android.content.Intent 7 | import android.content.IntentFilter 8 | import android.os.Build 9 | import android.util.Log 10 | import androidx.core.content.ContextCompat 11 | import com.je.dejpeg.NotificationHelper 12 | import com.je.dejpeg.ProcessingService 13 | 14 | class ServiceCommunicationHelper( 15 | private val context: Context, 16 | private val callbacks: ServiceCallbacks 17 | ) { 18 | interface ServiceCallbacks { 19 | fun onPidReceived(pid: Int) 20 | fun onProgress(imageId: String, message: String) 21 | fun onTimeEstimate(imageId: String, timeMillis: Long) 22 | fun onComplete(imageId: String, path: String) 23 | fun onError(imageId: String?, message: String) 24 | } 25 | 26 | private var serviceProcessPid: Int? = null 27 | private var isRegistered = false 28 | 29 | private val receiver = object : BroadcastReceiver() { 30 | override fun onReceive(ctx: Context?, intent: Intent?) { 31 | val action = intent?.action ?: return 32 | val imageId = intent.getStringExtra(ProcessingService.EXTRA_IMAGE_ID) 33 | 34 | when (action) { 35 | ProcessingService.PID_ACTION -> { 36 | intent.getIntExtra(ProcessingService.PID_EXTRA_VALUE, -1) 37 | .takeIf { it != -1 } 38 | ?.let { 39 | serviceProcessPid = it 40 | callbacks.onPidReceived(it) 41 | } 42 | } 43 | ProcessingService.PROGRESS_ACTION -> { 44 | intent.getStringExtra(ProcessingService.PROGRESS_EXTRA_MESSAGE)?.let { message -> 45 | imageId?.let { callbacks.onProgress(it, message) } 46 | } 47 | } 48 | ProcessingService.TIME_ESTIMATE_ACTION -> { 49 | val timeEstimate = intent.getLongExtra(ProcessingService.TIME_ESTIMATE_EXTRA_MILLIS, 0L) 50 | imageId?.let { callbacks.onTimeEstimate(it, timeEstimate) } 51 | } 52 | ProcessingService.COMPLETE_ACTION -> { 53 | val path = intent.getStringExtra(ProcessingService.COMPLETE_EXTRA_PATH) 54 | if (path != null && !imageId.isNullOrEmpty()) { 55 | callbacks.onComplete(imageId, path) 56 | } 57 | } 58 | ProcessingService.ERROR_ACTION -> { 59 | val message = intent.getStringExtra(ProcessingService.ERROR_EXTRA_MESSAGE) ?: "Error" 60 | callbacks.onError(imageId, message) 61 | } 62 | } 63 | } 64 | } 65 | 66 | @SuppressLint("UnspecifiedRegisterReceiverFlag") 67 | fun register() { 68 | if (isRegistered) return 69 | 70 | val filter = IntentFilter().apply { 71 | addAction(ProcessingService.PID_ACTION) 72 | addAction(ProcessingService.PROGRESS_ACTION) 73 | addAction(ProcessingService.TIME_ESTIMATE_ACTION) 74 | addAction(ProcessingService.COMPLETE_ACTION) 75 | addAction(ProcessingService.ERROR_ACTION) 76 | } 77 | 78 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 79 | context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED) 80 | } else { 81 | context.registerReceiver(receiver, filter) 82 | } 83 | isRegistered = true 84 | } 85 | 86 | fun unregister() { 87 | if (!isRegistered) return 88 | try { 89 | context.unregisterReceiver(receiver) 90 | } catch (_: Exception) { } 91 | isRegistered = false 92 | } 93 | 94 | fun startProcessing( 95 | imageId: String, 96 | uriString: String, 97 | filename: String, 98 | strength: Float, 99 | chunkSize: Int, 100 | overlapSize: Int 101 | ) { 102 | NotificationHelper.show(context, "Preparing...") 103 | startService(ProcessingService.ACTION_PROCESS) { 104 | putExtra(ProcessingService.EXTRA_URI, uriString) 105 | putExtra(ProcessingService.EXTRA_FILENAME, filename) 106 | putExtra(ProcessingService.EXTRA_IMAGE_ID, imageId) 107 | putExtra(ProcessingService.EXTRA_STRENGTH, strength) 108 | putExtra(ProcessingService.EXTRA_CHUNK_SIZE, chunkSize) 109 | putExtra(ProcessingService.EXTRA_OVERLAP_SIZE, overlapSize) 110 | } 111 | } 112 | 113 | fun cancelProcessing(onCleanup: () -> Unit): Boolean { 114 | NotificationHelper.cancel(context) 115 | 116 | val pid = serviceProcessPid 117 | if (pid != null && pid > 0) { 118 | try { 119 | android.os.Process.killProcess(pid) 120 | serviceProcessPid = null 121 | onCleanup() 122 | return true 123 | } catch (e: Exception) { 124 | Log.e("ServiceCommunicationHelper", "Failed to kill service process: ${e.message}") 125 | } 126 | } 127 | 128 | Log.w("ServiceCommunicationHelper", "No valid service PID available, sending cancel intent") 129 | startService(ProcessingService.ACTION_CANCEL) { } 130 | return false 131 | } 132 | 133 | private fun startService(action: String, configure: Intent.() -> Unit): Boolean { 134 | val intent = Intent(context, ProcessingService::class.java).apply { 135 | this.action = action 136 | configure() 137 | } 138 | 139 | return try { 140 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 141 | ContextCompat.startForegroundService(context, intent) 142 | } else { 143 | context.startService(intent) 144 | } 145 | true 146 | } catch (e: Exception) { 147 | Log.e("ServiceCommunicationHelper", "Failed to start service: ${e.javaClass.simpleName} - ${e.message}") 148 | false 149 | } 150 | } 151 | 152 | fun isForegroundServiceStartException(e: Exception): Boolean { 153 | return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && 154 | e is android.app.ForegroundServiceStartNotAllowedException) || 155 | (Build.VERSION.SDK_INT < Build.VERSION_CODES.S && ( 156 | e.javaClass.simpleName.contains("ForegroundServiceStartNotAllowed", true) || 157 | e.message?.contains("startForeground", true) == true || 158 | e.message?.contains("background", true) == true 159 | )) 160 | } 161 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | An open source app for removing noise and compression from photos 5 |

6 | 8 | 10 | 12 |

13 |

14 | IzzyOnDroid 15 | Obtanium 16 | Get it on GitHub 17 |

18 |

19 |
20 | 21 | ## features: 22 | - batch processing 23 | - supports most image formats 24 | - before/after view 25 | - [fully offline](https://github.com/jeeneo/dejpeg/blob/main/app/src/main/AndroidManifest.xml) 26 | - custom models (beta) 27 | - image descaling (beta) 28 | 29 | this is not a "super resolution AI upscaler", but simple non-destructive method for cleaning up/restoring images 30 | 31 | ## models (required): 32 | [FBCNN](https://github.com/jeeneo/FBCNN-mobile/releases/latest) (JPEG artifacts) 33 | 34 | [SCUNet](https://github.com/jeeneo/SCUNet-mobile/releases/latest) (noise/grain) 35 | 36 | Info [here](https://github.com/jeeneo/dejpeg/wiki/model-types) (see in-app FAQ also) 37 | 38 | you can also run other experimental models, more info [here](https://github.com/jeeneo/dejpeg-experimental) 39 | 40 | ## limitations: 41 | - processed locally, minimum 4gb ram and 4 threads recommended 42 | - very large images can cause crashes 43 | - TIFF and other special image formats are not supported. 44 | - GIF animations are not supported but planned. 45 | 46 | See the [wiki](https://github.com/jeeneo/dejpeg/wiki) for more information 47 | 48 | ## other platforms 49 | please use [chaiNNer](https://github.com/chaiNNer-org/chaiNNer) which should work well with these models (regardless if PyTorch or ONNX) 50 | 51 | for FBCNN, which chaiNNer does support but in a limited fashion, install [this custom node](chainner/README.md) and use the [original PyTorch models](https://github.com/jiaxi-jiang/FBCNN/releases/latest), not the mobile onnx. 52 | 53 |
54 |

building

55 | 56 | this app includes OpenCV with [BRISQUE analysis for descaling an image](https://github.com/jeeneo/dejpeg/issues/24), which is experimental but ive occasionally found it useful. 57 | 58 | required: 59 | - android NDK 27.3.x 60 | - cmake 3.x or newer 61 | - git 62 | - opencv + contrib 63 | 64 | create a directory called `opencv` after cloning dejpeg, then clone opencv + contrib inside that folder 65 | ```bash 66 | git clone https://github.com/opencv/opencv.git 67 | git clone https://github.com/opencv/opencv_contrib.git 68 | ``` 69 | and make a folder called `build_android` 70 | 71 | ```bash 72 | cd opencv 73 | mkdir build_android && cd build_android 74 | ``` 75 | 76 | structure should be like this 77 | 78 | ``` 79 | $ tree -L 2 80 | ... 81 | ├── opencv 82 | │ ├── build_android 83 | │ ├── opencv 84 | │ ├── opencv_contrib 85 | ... 86 | ``` 87 | 88 | ```bash 89 | cmake \ 90 | -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ 91 | -DANDROID_ABI=arm64-v8a \ 92 | -DANDROID_NATIVE_API_LEVEL=21 \ 93 | -DANDROID_STL=c++_shared \ 94 | -DCMAKE_BUILD_TYPE=MinSizeRel \ 95 | -DCMAKE_CXX_FLAGS_MINSIZEREL="-Os -DNDEBUG -fvisibility=hidden -fvisibility-inlines-hidden -ffunction-sections -fdata-sections" \ 96 | -DCMAKE_C_FLAGS_MINSIZEREL="-Os -DNDEBUG -fvisibility=hidden -fvisibility-inlines-hidden -ffunction-sections -fdata-sections" \ 97 | -DCMAKE_SHARED_LINKER_FLAGS="-Wl,--gc-sections -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=4096" \ 98 | -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules \ 99 | -DBUILD_SHARED_LIBS=ON \ 100 | -DBUILD_LIST=core,imgproc,imgcodecs,ml,quality \ 101 | -DBUILD_TESTS=OFF -DBUILD_PERF_TESTS=OFF -DBUILD_ANDROID_EXAMPLES=OFF -DBUILD_DOCS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_PACKAGE=OFF -DBUILD_opencv_java=OFF \ 102 | -DWITH_JPEG=ON -DWITH_PNG=ON -DWITH_TIFF=OFF -DWITH_WEBP=OFF -DWITH_OPENEXR=OFF \ 103 | -DWITH_IPP=OFF -DWITH_EIGEN=OFF -DWITH_LAPACK=OFF -DWITH_TBB=OFF -DWITH_PTHREADS_PF=ON \ 104 | -DWITH_GSTREAMER=OFF -DWITH_V4L=OFF -DWITH_GTK=OFF -DWITH_QT=OFF -DWITH_OPENCL=OFF -DWITH_CUDA=OFF -DWITH_VTK=OFF \ 105 | -DBUILD_PROTOBUF=OFF -DBUILD_TBB=OFF -DBUILD_IPP_IW=OFF -DBUILD_ITT=OFF \ 106 | ../opencv && make -j$(nproc) 107 | ``` 108 | 109 | you can skip stripping and just copy the libs from `lib/arm64-v8a` to there and the next operation will strip them but you'll need to build a `Release` instead of `Debug` (and sign) 110 | 111 | copy: 112 | ```bash 113 | cp -r lib/arm64-v8a ../../app/src/main/jniLibs && cd ../../app/src/main/jniLibs/arm64-v8a 114 | ``` 115 | 116 | strip debug symbols: 117 | 118 | ```bash 119 | llvm-strip libopencv_{core,imgproc,ml,imgcodecs,quality}.so 120 | ``` 121 | 122 | build: 123 | ```bash 124 | rm app/src/main/jniLibs/arm64-v8a/libbrisque_jni.so 125 | BUILD_BRISQUE_JNI=ON ./gradlew clean assembleDebug 126 | ``` 127 | 128 | note: due to IzzyOnDroid's apk filesize limit to 30mb or less, the native binaries in the official release are compressed using `upx --best --lzma --android-shlib` after being stripped of debug symbols (excluding `libc++_shared.so`). you can skip this step if needed. 129 | 130 | compress: 131 | ```bash 132 | upx --best --lzma --android-shlib libopencv_{core,imgproc,ml,imgcodecs,quality}.so 133 | ``` 134 | 135 | additionally, i also compress `libonnxruntime.so` with UPX as well (using `upx --ultra-brute --android-shlib`), so to get the original version, extract `libonnxruntime.so` from your compiled version after you've comment out the following config, then extract from the apk, copy to jniLibs, pack using UPX, uncomment and build. this is how i make all releases as to not exceed IzzyOnDroid's 30mb apk size limit but only needs to be done once unless i change something with opencv/brisque. 136 | 137 | ```kotlin 138 | ... 139 | packaging { 140 | jniLibs { 141 | pickFirsts += "lib/*/libonnxruntime.so" 142 | } 143 | } 144 | ... 145 | ``` 146 |
147 | 148 |
149 |

credits and license

150 | 151 | [@adrianerrea](https://github.com/adrianerrea/fromPytorchtoMobile) for the base application, [FBCNN](https://github.com/jiaxi-jiang/FBCNN) and [SCUNet](https://github.com/cszn/SCUNet) creators plus all other model owners. 152 | 153 | this is a GUI for a select amount of `1x` ONNX processing models. All are used under their respective licenses. You are free to embed parts of this app in your own project as long as it remains free/non-paywalled and must abide to the GPL v3 license 154 | 155 | ### disclaimer: 156 | De*JPEG* is not affiliated or related with Topaz `DEJPEG` or any other similarly named software/project. although ive wondered if the term 'JPEG' is copyrighted/trademarked due to it literally being the acronym for Joint Photographic Experts Group, for this reason i might need to change the app's name if legal issues start to occur. 157 |
-------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/MainScreen.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.ui 2 | 3 | import androidx.compose.foundation.layout.Box 4 | import androidx.compose.foundation.layout.fillMaxSize 5 | import androidx.compose.foundation.layout.padding 6 | import androidx.compose.material.icons.Icons 7 | import androidx.compose.material.icons.filled.Settings 8 | import androidx.compose.material.icons.filled.Image 9 | import androidx.compose.material3.* 10 | import androidx.compose.runtime.* 11 | import androidx.compose.ui.Modifier 12 | import android.net.Uri 13 | import androidx.lifecycle.viewmodel.compose.viewModel 14 | import androidx.compose.ui.res.stringResource 15 | import androidx.navigation.compose.NavHost 16 | import androidx.navigation.compose.composable 17 | import androidx.navigation.compose.currentBackStackEntryAsState 18 | import androidx.navigation.compose.rememberNavController 19 | import androidx.navigation.navArgument 20 | import androidx.navigation.NavType 21 | import com.je.dejpeg.compose.ui.screens.ProcessingScreen 22 | import com.je.dejpeg.compose.ui.screens.SettingsScreen 23 | import com.je.dejpeg.compose.ui.screens.BeforeAfterScreen 24 | import com.je.dejpeg.compose.ui.screens.BRISQUEScreen 25 | import com.je.dejpeg.compose.ui.viewmodel.ProcessingViewModel 26 | import com.je.dejpeg.R 27 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 28 | 29 | sealed class Screen(val route: String, val title: String) { 30 | object Processing : Screen("processing", "Processing") 31 | object Settings : Screen("settings", "Settings") 32 | object BeforeAfter : Screen("beforeafter/{imageId}", "Before/After") { 33 | fun createRoute(imageId: String) = "beforeafter/$imageId" 34 | } 35 | object BRISQUE : Screen("brisque/{imageId}", "BRISQUE") { 36 | fun createRoute(imageId: String) = "brisque/$imageId" 37 | } 38 | } 39 | 40 | @OptIn(ExperimentalMaterial3Api::class) 41 | @Composable 42 | fun MainScreen(sharedUris: List = emptyList()) { 43 | val navController = rememberNavController() 44 | val viewModel: ProcessingViewModel = viewModel() 45 | val haptic = rememberHapticFeedback() 46 | val navBackStackEntry by navController.currentBackStackEntryAsState() 47 | val currentRoute = navBackStackEntry?.destination?.route 48 | val isBeforeAfterScreen = currentRoute?.startsWith("beforeafter") ?: false 49 | val isBRISQUEScreen = currentRoute?.startsWith("brisque") ?: false 50 | val isFullscreenScreen = isBeforeAfterScreen || isBRISQUEScreen 51 | 52 | Scaffold( 53 | topBar = { 54 | if (!isFullscreenScreen) { 55 | TopAppBar( 56 | title = { 57 | Text(when(currentRoute) { 58 | Screen.Settings.route -> stringResource(R.string.settings) 59 | else -> stringResource(R.string.app_name) 60 | }) 61 | }, 62 | colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface) 63 | ) 64 | } 65 | }, 66 | bottomBar = { 67 | if (!isFullscreenScreen) { 68 | NavigationBar { 69 | NavigationBarItem( 70 | icon = { 71 | TooltipBox( 72 | positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), 73 | tooltip = { PlainTooltip { Text(stringResource(R.string.processing)) } }, 74 | state = rememberTooltipState() 75 | ) { 76 | Icon(Icons.Filled.Image, contentDescription = stringResource(R.string.processing)) 77 | } 78 | }, 79 | label = { Text(stringResource(R.string.processing)) }, 80 | selected = currentRoute == Screen.Processing.route, 81 | onClick = { 82 | haptic.light() 83 | if (currentRoute != Screen.Processing.route) { 84 | navController.navigate(Screen.Processing.route) { 85 | popUpTo(navController.graph.startDestinationId) { 86 | saveState = true 87 | } 88 | launchSingleTop = true 89 | restoreState = true 90 | } 91 | } 92 | } 93 | ) 94 | NavigationBarItem( 95 | icon = { 96 | TooltipBox( 97 | positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), 98 | tooltip = { PlainTooltip { Text(stringResource(R.string.settings)) } }, 99 | state = rememberTooltipState() 100 | ) { 101 | Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings)) 102 | } 103 | }, 104 | label = { Text(stringResource(R.string.settings)) }, 105 | selected = currentRoute == Screen.Settings.route, 106 | onClick = { 107 | haptic.light() 108 | if (currentRoute != Screen.Settings.route) { 109 | navController.navigate(Screen.Settings.route) { 110 | popUpTo(navController.graph.startDestinationId) { 111 | saveState = true 112 | } 113 | launchSingleTop = true 114 | restoreState = true 115 | } 116 | } 117 | } 118 | ) 119 | } 120 | } 121 | } 122 | ) { paddingValues -> 123 | NavHost( 124 | navController = navController, 125 | startDestination = Screen.Processing.route, 126 | modifier = Modifier.fillMaxSize() 127 | ) { 128 | composable(Screen.Processing.route) { 129 | Box(Modifier.padding(paddingValues)) { 130 | ProcessingScreen(viewModel, navController, sharedUris, onRemoveSharedUri = { uri -> (sharedUris as? MutableList)?.remove(uri) }) 131 | } 132 | } 133 | composable(Screen.Settings.route) { 134 | Box(Modifier.padding(paddingValues)) { 135 | SettingsScreen(viewModel) 136 | } 137 | } 138 | composable( 139 | Screen.BeforeAfter.route, 140 | arguments = listOf(navArgument("imageId") { type = NavType.StringType }) 141 | ) { backStackEntry -> 142 | val imageId = backStackEntry.arguments?.getString("imageId") 143 | if (imageId != null) { 144 | BeforeAfterScreen(viewModel, imageId, navController) 145 | } 146 | } 147 | composable( 148 | Screen.BRISQUE.route, 149 | arguments = listOf(navArgument("imageId") { type = NavType.StringType }) 150 | ) { backStackEntry -> 151 | val imageId = backStackEntry.arguments?.getString("imageId") 152 | if (imageId != null) { 153 | BRISQUEScreen(viewModel, imageId, navController) 154 | } 155 | } 156 | } 157 | } 158 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/DialogManager.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import androidx.compose.foundation.layout.* 4 | import androidx.compose.material3.* 5 | import androidx.compose.runtime.* 6 | import androidx.compose.ui.Alignment 7 | import androidx.compose.ui.Modifier 8 | import androidx.compose.ui.text.input.TextFieldValue 9 | import androidx.compose.ui.text.TextRange 10 | import androidx.compose.ui.unit.dp 11 | import androidx.compose.ui.res.stringResource 12 | import com.je.dejpeg.R 13 | 14 | @Composable 15 | fun SaveImageDialog( 16 | defaultFilename: String, 17 | showSaveAllOption: Boolean = false, 18 | initialSaveAll: Boolean = false, 19 | hideOptions: Boolean = false, 20 | onDismissRequest: () -> Unit, 21 | onSave: (String, Boolean, Boolean) -> Unit 22 | ) { 23 | val lastDot = defaultFilename.lastIndexOf('.') 24 | var textState by remember { mutableStateOf(TextFieldValue(defaultFilename, TextRange(0, if (lastDot > 0) lastDot else defaultFilename.length))) } 25 | var saveAll by remember { mutableStateOf(initialSaveAll) } 26 | var skipNext by remember { mutableStateOf(false) } 27 | val haptic = com.je.dejpeg.compose.utils.rememberHapticFeedback() 28 | val dialogWidth = rememberDialogWidth() 29 | AlertDialog( 30 | onDismissRequest = onDismissRequest, 31 | modifier = Modifier.dialogWidth(dialogWidth), 32 | properties = DialogDefaults.Properties, 33 | title = { Text(stringResource(if (hideOptions) R.string.overwrite_image else R.string.save_image)) }, 34 | text = { 35 | Column { 36 | if (hideOptions) Text(stringResource(R.string.already_exists), Modifier.padding(bottom = 12.dp)) 37 | OutlinedTextField( 38 | textState, { textState = it }, Modifier.fillMaxWidth(), 39 | singleLine = true, label = { Text(stringResource(R.string.filename)) } 40 | ) 41 | if (!hideOptions) { 42 | Spacer(Modifier.height(12.dp)) 43 | if (showSaveAllOption) { 44 | MaterialSwitchRow( 45 | label = stringResource(R.string.save_all), 46 | checked = saveAll, 47 | onCheckedChange = { 48 | haptic.light() 49 | saveAll = it 50 | }, 51 | modifier = Modifier.fillMaxWidth() 52 | ) 53 | } 54 | MaterialSwitchRow( 55 | label = stringResource(R.string.dont_show_dialog), 56 | checked = skipNext, 57 | onCheckedChange = { 58 | haptic.light() 59 | skipNext = it 60 | }, 61 | modifier = Modifier.fillMaxWidth() 62 | ) 63 | } 64 | } 65 | }, 66 | confirmButton = { 67 | Row( 68 | Modifier.fillMaxWidth(), 69 | verticalAlignment = Alignment.CenterVertically 70 | ) { 71 | TextButton( 72 | onClick = { haptic.light(); onDismissRequest() }, 73 | modifier = Modifier.align(Alignment.CenterVertically) 74 | ) { 75 | Text(stringResource(R.string.cancel)) 76 | } 77 | Spacer(Modifier.weight(1f)) 78 | Button({ 79 | haptic.medium() 80 | onSave(textState.text.trim(), saveAll, skipNext) 81 | onDismissRequest() 82 | }) { Text(stringResource(R.string.save)) } 83 | } 84 | }, 85 | dismissButton = {} 86 | ) 87 | } 88 | 89 | @Composable 90 | fun RemoveImageDialog( 91 | imageFilename: String, 92 | hasOutput: Boolean, 93 | onDismissRequest: () -> Unit, 94 | onRemove: () -> Unit, 95 | onSaveAndRemove: () -> Unit 96 | ) { 97 | val haptic = com.je.dejpeg.compose.utils.rememberHapticFeedback() 98 | val dialogWidth = rememberDialogWidth() 99 | AlertDialog( 100 | onDismissRequest = onDismissRequest, 101 | modifier = Modifier.dialogWidth(dialogWidth), 102 | properties = DialogDefaults.Properties, 103 | title = { Text(stringResource(R.string.remove_image_title)) }, 104 | text = { Text(stringResource(R.string.remove_image_question, imageFilename)) }, 105 | confirmButton = { 106 | Row( 107 | Modifier.fillMaxWidth(), 108 | verticalAlignment = Alignment.CenterVertically 109 | ) { 110 | TextButton({ haptic.light(); onDismissRequest() }) { 111 | Text(stringResource(R.string.nope)) 112 | } 113 | Spacer(Modifier.weight(0.4f)) 114 | TextButton({ haptic.heavy(); onRemove(); onDismissRequest() }) { 115 | Text( 116 | stringResource(R.string.remove), 117 | color = MaterialTheme.colorScheme.error 118 | ) 119 | } 120 | Spacer(Modifier.weight(0.1f)) 121 | if (hasOutput) { 122 | Button({ haptic.medium(); onSaveAndRemove(); onDismissRequest() }) { 123 | Text(stringResource(R.string.save)) 124 | } 125 | } 126 | } 127 | }, 128 | dismissButton = {} 129 | ) 130 | } 131 | 132 | @Composable 133 | fun CancelProcessingDialog(imageFilename: String, onDismissRequest: () -> Unit, onConfirm: () -> Unit) { 134 | val haptic = com.je.dejpeg.compose.utils.rememberHapticFeedback() 135 | val dialogWidth = rememberDialogWidth() 136 | AlertDialog( 137 | onDismissRequest = onDismissRequest, 138 | modifier = Modifier.dialogWidth(dialogWidth), 139 | properties = DialogDefaults.Properties, 140 | title = { Text(stringResource(R.string.stop_processing_title)) }, 141 | text = { Text(stringResource(R.string.stop_processing_question, imageFilename)) }, 142 | confirmButton = { 143 | Row( 144 | Modifier.fillMaxWidth(), 145 | horizontalArrangement = Arrangement.SpaceBetween, 146 | verticalAlignment = Alignment.CenterVertically 147 | ) { 148 | TextButton({ haptic.light(); onDismissRequest() }) { 149 | Text(stringResource(R.string.nope)) 150 | } 151 | TextButton({ haptic.heavy(); onConfirm(); onDismissRequest() }) { 152 | Text(stringResource(R.string.yes_stop), color = MaterialTheme.colorScheme.error) 153 | } 154 | } 155 | }, 156 | dismissButton = {} 157 | ) 158 | } 159 | 160 | @Composable 161 | fun BatteryOptimizationDialog(onDismissRequest: () -> Unit, onOpenSettings: () -> Unit) { 162 | val haptic = com.je.dejpeg.compose.utils.rememberHapticFeedback() 163 | val dialogWidth = rememberDialogWidth() 164 | AlertDialog( 165 | onDismissRequest = onDismissRequest, 166 | modifier = Modifier.dialogWidth(dialogWidth), 167 | properties = DialogDefaults.Properties, 168 | title = { Text(stringResource(R.string.background_service_error)) }, 169 | text = { 170 | Column { 171 | Text(stringResource(R.string.battery_optimization_explanation), Modifier.padding(bottom = 8.dp)) 172 | Text(stringResource(R.string.open_battery_optimization_settings), style = MaterialTheme.typography.bodyMedium) 173 | } 174 | }, 175 | dismissButton = { TextButton({ haptic.light(); onDismissRequest() }) { Text(stringResource(R.string.cancel)) } }, 176 | confirmButton = { Button({ haptic.medium(); onOpenSettings(); onDismissRequest() }) { Text(stringResource(R.string.open_settings)) } } 177 | ) 178 | } -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/data/AppPreferences.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.data 2 | 3 | import android.content.Context 4 | import androidx.datastore.core.DataStore 5 | import androidx.datastore.preferences.core.Preferences 6 | import androidx.datastore.preferences.core.booleanPreferencesKey 7 | import androidx.datastore.preferences.core.edit 8 | import androidx.datastore.preferences.core.floatPreferencesKey 9 | import androidx.datastore.preferences.core.intPreferencesKey 10 | import androidx.datastore.preferences.core.stringPreferencesKey 11 | import androidx.datastore.preferences.preferencesDataStore 12 | import kotlinx.coroutines.flow.Flow 13 | import kotlinx.coroutines.flow.first 14 | import kotlinx.coroutines.flow.map 15 | 16 | val Context.dataStore: DataStore by preferencesDataStore(name = "app_prefs") 17 | 18 | object PreferenceKeys { 19 | val SKIP_SAVE_DIALOG = booleanPreferencesKey("skipSaveDialog") 20 | val DEFAULT_IMAGE_SOURCE = stringPreferencesKey("defaultImageSource") 21 | val HAPTIC_FEEDBACK_ENABLED = booleanPreferencesKey("hapticFeedbackEnabled") 22 | val COMPAT_MODEL_CLEANUP = booleanPreferencesKey("compatModelCleanup") 23 | val COMPAT_BRISQUE_CLEANUP = booleanPreferencesKey("compatBrisqueCleanup") 24 | val CHUNK_SIZE = intPreferencesKey("chunk_size") 25 | val OVERLAP_SIZE = intPreferencesKey("overlap_size") 26 | val GLOBAL_STRENGTH = floatPreferencesKey("global_strength") 27 | val BRISQUE_COARSE_STEP = intPreferencesKey("brisque_coarse_step") 28 | val BRISQUE_FINE_STEP = intPreferencesKey("brisque_fine_step") 29 | val BRISQUE_FINE_RANGE = intPreferencesKey("brisque_fine_range") 30 | val BRISQUE_MIN_WIDTH_RATIO = floatPreferencesKey("brisque_min_width_ratio") 31 | val BRISQUE_WEIGHT = floatPreferencesKey("brisque_weight") 32 | val BRISQUE_SHARPNESS_WEIGHT = floatPreferencesKey("brisque_sharpness_weight") 33 | } 34 | 35 | data class BrisqueSettings( 36 | val coarseStep: Int = DEFAULT_BRISQUE_COARSE_STEP, 37 | val fineStep: Int = DEFAULT_BRISQUE_FINE_STEP, 38 | val fineRange: Int = DEFAULT_BRISQUE_FINE_RANGE, 39 | val minWidthRatio: Float = DEFAULT_BRISQUE_MIN_WIDTH_RATIO, 40 | val brisqueWeight: Float = DEFAULT_BRISQUE_WEIGHT, 41 | val sharpnessWeight: Float = DEFAULT_BRISQUE_SHARPNESS_WEIGHT 42 | ) 43 | 44 | private const val DEFAULT_BRISQUE_COARSE_STEP = 20 45 | private const val DEFAULT_BRISQUE_FINE_STEP = 5 46 | private const val DEFAULT_BRISQUE_FINE_RANGE = 30 47 | private const val DEFAULT_BRISQUE_MIN_WIDTH_RATIO = 0.5f 48 | private const val DEFAULT_BRISQUE_WEIGHT = 0.7f 49 | private const val DEFAULT_BRISQUE_SHARPNESS_WEIGHT = 0.3f 50 | 51 | class AppPreferences(private val context: Context) { 52 | 53 | companion object { 54 | const val DEFAULT_CHUNK_SIZE = 512 55 | const val DEFAULT_OVERLAP_SIZE = 8 56 | const val DEFAULT_GLOBAL_STRENGTH = 50f 57 | 58 | @Volatile 59 | private var instance: AppPreferences? = null 60 | 61 | fun getInstance(context: Context): AppPreferences { 62 | return instance ?: synchronized(this) { 63 | instance ?: AppPreferences(context.applicationContext).also { instance = it } 64 | } 65 | } 66 | } 67 | 68 | val skipSaveDialog: Flow = context.dataStore.data.map { prefs -> 69 | prefs[PreferenceKeys.SKIP_SAVE_DIALOG] ?: false 70 | } 71 | 72 | val defaultImageSource: Flow = context.dataStore.data.map { prefs -> 73 | prefs[PreferenceKeys.DEFAULT_IMAGE_SOURCE] 74 | } 75 | 76 | val hapticFeedbackEnabled: Flow = context.dataStore.data.map { prefs -> 77 | prefs[PreferenceKeys.HAPTIC_FEEDBACK_ENABLED] ?: true 78 | } 79 | 80 | val compatModelCleanup: Flow = context.dataStore.data.map { prefs -> 81 | prefs[PreferenceKeys.COMPAT_MODEL_CLEANUP] ?: false 82 | } 83 | 84 | val compatBrisqueCleanup: Flow = context.dataStore.data.map { prefs -> 85 | prefs[PreferenceKeys.COMPAT_BRISQUE_CLEANUP] ?: false 86 | } 87 | 88 | val chunkSize: Flow = context.dataStore.data.map { prefs -> 89 | prefs[PreferenceKeys.CHUNK_SIZE] ?: DEFAULT_CHUNK_SIZE 90 | } 91 | 92 | val overlapSize: Flow = context.dataStore.data.map { prefs -> 93 | prefs[PreferenceKeys.OVERLAP_SIZE] ?: DEFAULT_OVERLAP_SIZE 94 | } 95 | 96 | val globalStrength: Flow = context.dataStore.data.map { prefs -> 97 | prefs[PreferenceKeys.GLOBAL_STRENGTH] ?: DEFAULT_GLOBAL_STRENGTH 98 | } 99 | val brisqueSettings: Flow = context.dataStore.data.map { prefs -> 100 | BrisqueSettings( 101 | coarseStep = prefs[PreferenceKeys.BRISQUE_COARSE_STEP] ?: DEFAULT_BRISQUE_COARSE_STEP, 102 | fineStep = prefs[PreferenceKeys.BRISQUE_FINE_STEP] ?: DEFAULT_BRISQUE_FINE_STEP, 103 | fineRange = prefs[PreferenceKeys.BRISQUE_FINE_RANGE] ?: DEFAULT_BRISQUE_FINE_RANGE, 104 | minWidthRatio = prefs[PreferenceKeys.BRISQUE_MIN_WIDTH_RATIO] ?: DEFAULT_BRISQUE_MIN_WIDTH_RATIO, 105 | brisqueWeight = prefs[PreferenceKeys.BRISQUE_WEIGHT] ?: DEFAULT_BRISQUE_WEIGHT, 106 | sharpnessWeight = prefs[PreferenceKeys.BRISQUE_SHARPNESS_WEIGHT] ?: DEFAULT_BRISQUE_SHARPNESS_WEIGHT 107 | ) 108 | } 109 | 110 | suspend fun setSkipSaveDialog(skip: Boolean) { 111 | context.dataStore.edit { prefs -> 112 | prefs[PreferenceKeys.SKIP_SAVE_DIALOG] = skip 113 | } 114 | } 115 | 116 | suspend fun setDefaultImageSource(source: String?) { 117 | context.dataStore.edit { prefs -> 118 | if (source == null) { 119 | prefs.remove(PreferenceKeys.DEFAULT_IMAGE_SOURCE) 120 | } else { 121 | prefs[PreferenceKeys.DEFAULT_IMAGE_SOURCE] = source 122 | } 123 | } 124 | } 125 | 126 | suspend fun setHapticFeedbackEnabled(enabled: Boolean) { 127 | context.dataStore.edit { prefs -> 128 | prefs[PreferenceKeys.HAPTIC_FEEDBACK_ENABLED] = enabled 129 | } 130 | } 131 | 132 | suspend fun clearDefaultImageSource() { 133 | context.dataStore.edit { prefs -> 134 | prefs.remove(PreferenceKeys.DEFAULT_IMAGE_SOURCE) 135 | } 136 | } 137 | 138 | suspend fun setCompatModelCleanup(completed: Boolean) { 139 | context.dataStore.edit { prefs -> 140 | prefs[PreferenceKeys.COMPAT_MODEL_CLEANUP] = completed 141 | } 142 | } 143 | 144 | suspend fun getCompatModelCleanupImmediate(): Boolean = compatModelCleanup.first() 145 | 146 | suspend fun setCompatBrisqueCleanup(completed: Boolean) { 147 | context.dataStore.edit { prefs -> 148 | prefs[PreferenceKeys.COMPAT_BRISQUE_CLEANUP] = completed 149 | } 150 | } 151 | 152 | suspend fun getCompatBrisqueCleanupImmediate(): Boolean = compatBrisqueCleanup.first() 153 | 154 | suspend fun setChunkSize(size: Int) { 155 | context.dataStore.edit { prefs -> 156 | prefs[PreferenceKeys.CHUNK_SIZE] = size 157 | } 158 | } 159 | 160 | suspend fun setOverlapSize(size: Int) { 161 | context.dataStore.edit { prefs -> 162 | prefs[PreferenceKeys.OVERLAP_SIZE] = size 163 | } 164 | } 165 | 166 | suspend fun setGlobalStrength(strength: Float) { 167 | context.dataStore.edit { prefs -> 168 | prefs[PreferenceKeys.GLOBAL_STRENGTH] = strength 169 | } 170 | } 171 | 172 | suspend fun setBrisqueSettings(settings: BrisqueSettings) { 173 | context.dataStore.edit { prefs -> 174 | prefs[PreferenceKeys.BRISQUE_COARSE_STEP] = settings.coarseStep 175 | prefs[PreferenceKeys.BRISQUE_FINE_STEP] = settings.fineStep 176 | prefs[PreferenceKeys.BRISQUE_FINE_RANGE] = settings.fineRange 177 | prefs[PreferenceKeys.BRISQUE_MIN_WIDTH_RATIO] = settings.minWidthRatio 178 | prefs[PreferenceKeys.BRISQUE_WEIGHT] = settings.brisqueWeight 179 | prefs[PreferenceKeys.BRISQUE_SHARPNESS_WEIGHT] = settings.sharpnessWeight 180 | } 181 | } 182 | 183 | suspend fun getChunkSizeImmediate(): Int = chunkSize.first() 184 | suspend fun getOverlapSizeImmediate(): Int = overlapSize.first() 185 | suspend fun getGlobalStrengthImmediate(): Float = globalStrength.first() 186 | suspend fun getSkipSaveDialogImmediate(): Boolean = skipSaveDialog.first() 187 | suspend fun getDefaultImageSourceImmediate(): String? = defaultImageSource.first() 188 | suspend fun getHapticFeedbackEnabledImmediate(): Boolean = hapticFeedbackEnabled.first() 189 | suspend fun getBrisqueSettingsImmediate(): BrisqueSettings = brisqueSettings.first() 190 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH="\\\"\\\"" 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | if ! command -v java >/dev/null 2>&1 137 | then 138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 139 | 140 | Please set the JAVA_HOME variable in your environment to match the 141 | location of your Java installation." 142 | fi 143 | fi 144 | 145 | # Increase the maximum file descriptors if we can. 146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 147 | case $MAX_FD in #( 148 | max*) 149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 150 | # shellcheck disable=SC2039,SC3045 151 | MAX_FD=$( ulimit -H -n ) || 152 | warn "Could not query maximum file descriptor limit" 153 | esac 154 | case $MAX_FD in #( 155 | '' | soft) :;; #( 156 | *) 157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 158 | # shellcheck disable=SC2039,SC3045 159 | ulimit -n "$MAX_FD" || 160 | warn "Could not set maximum file descriptor limit to $MAX_FD" 161 | esac 162 | fi 163 | 164 | # Collect all arguments for the java command, stacking in reverse order: 165 | # * args from the command line 166 | # * the main class name 167 | # * -classpath 168 | # * -D...appname settings 169 | # * --module-path (only if needed) 170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 171 | 172 | # For Cygwin or MSYS, switch paths to Windows format before running java 173 | if "$cygwin" || "$msys" ; then 174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 176 | 177 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 178 | 179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 180 | for arg do 181 | if 182 | case $arg in #( 183 | -*) false ;; # don't mess with options #( 184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 185 | [ -e "$t" ] ;; #( 186 | *) false ;; 187 | esac 188 | then 189 | arg=$( cygpath --path --ignore --mixed "$arg" ) 190 | fi 191 | # Roll the args list around exactly as many times as the number of 192 | # args, so each arg winds up back in the position where it started, but 193 | # possibly modified. 194 | # 195 | # NB: a `for` loop captures its iteration list before it begins, so 196 | # changing the positional parameters here affects neither the number of 197 | # iterations, nor the values presented in `arg`. 198 | shift # remove old arg 199 | set -- "$@" "$arg" # push replacement arg 200 | done 201 | fi 202 | 203 | 204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 206 | 207 | # Collect all arguments for the java command: 208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 209 | # and any embedded shellness will be escaped. 210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 211 | # treated as '${Hostname}' itself on the command line. 212 | 213 | set -- \ 214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 215 | -classpath "$CLASSPATH" \ 216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 217 | "$@" 218 | 219 | # Stop when "xargs" is not available. 220 | if ! command -v xargs >/dev/null 2>&1 221 | then 222 | die "xargs is not available" 223 | fi 224 | 225 | # Use "xargs" to parse quoted args. 226 | # 227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 228 | # 229 | # In Bash we could simply go: 230 | # 231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 232 | # set -- "${ARGS[@]}" "$@" 233 | # 234 | # but POSIX shell has neither arrays nor command substitution, so instead we 235 | # post-process each arg (as a line of input to sed) to backslash-escape any 236 | # character that might be a shell metacharacter, then use eval to reverse 237 | # that process (while maintaining the separation between arguments), and wrap 238 | # the whole thing up as a single "set" statement. 239 | # 240 | # This will of course break if any of these variables contains a newline or 241 | # an unmatched quote. 242 | # 243 | 244 | eval "set -- $( 245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 246 | xargs -n1 | 247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 248 | tr '\n' ' ' 249 | )" '"$@"' 250 | 251 | exec "$JAVACMD" "$@" 252 | -------------------------------------------------------------------------------- /app/src/main/java/com/je/dejpeg/compose/ui/components/FAQDialog.kt: -------------------------------------------------------------------------------- 1 | package com.je.dejpeg.compose.ui.components 2 | 3 | import android.content.Intent 4 | import androidx.compose.foundation.clickable 5 | import androidx.compose.foundation.layout.* 6 | import androidx.compose.foundation.lazy.LazyColumn 7 | import androidx.compose.material.icons.Icons 8 | import androidx.compose.material.icons.filled.ExpandMore 9 | import androidx.compose.material3.* 10 | import androidx.compose.runtime.* 11 | import androidx.compose.ui.Alignment 12 | import androidx.compose.ui.Modifier 13 | import androidx.compose.ui.draw.rotate 14 | import androidx.compose.ui.platform.LocalContext 15 | import androidx.compose.ui.res.stringResource 16 | import androidx.compose.ui.text.LinkAnnotation 17 | import androidx.compose.ui.text.SpanStyle 18 | import androidx.compose.ui.text.buildAnnotatedString 19 | import androidx.compose.ui.text.font.FontFamily 20 | import androidx.compose.ui.text.font.FontWeight 21 | import androidx.compose.ui.text.style.TextDecoration 22 | import androidx.compose.ui.unit.dp 23 | import androidx.core.net.toUri 24 | import com.je.dejpeg.R 25 | import com.je.dejpeg.compose.utils.rememberHapticFeedback 26 | 27 | data class FAQSectionData( 28 | val title: String, 29 | val content: String?, 30 | val subSections: List>? 31 | ) 32 | 33 | @Composable 34 | fun FAQDialog(onDismiss: () -> Unit) { 35 | val context = LocalContext.current 36 | val faqSections = remember { loadFAQSections(context) } 37 | val haptic = rememberHapticFeedback() 38 | val dialogWidth = rememberDialogWidth() 39 | AlertDialog( 40 | onDismissRequest = onDismiss, 41 | modifier = Modifier.dialogWidth(dialogWidth), 42 | properties = DialogDefaults.Properties, 43 | shape = DialogDefaults.Shape, 44 | containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, 45 | title = { 46 | Text( 47 | stringResource(R.string.faqs), 48 | style = MaterialTheme.typography.titleLarge, 49 | fontWeight = FontWeight.Bold 50 | ) 51 | }, 52 | text = { 53 | LazyColumn(modifier = Modifier.fillMaxWidth()) { 54 | items(faqSections.size) { 55 | FAQSection( 56 | faqSections[it].title, 57 | faqSections[it].content, 58 | faqSections[it].subSections 59 | ) 60 | } 61 | } 62 | }, 63 | confirmButton = { 64 | TextButton(onClick = { haptic.light(); onDismiss() }) { 65 | Text(stringResource(R.string.close)) 66 | } 67 | } 68 | ) 69 | } 70 | 71 | @Composable 72 | fun FAQSection(title: String, content: String?, subSections: List>? = null) { 73 | var expanded by remember { mutableStateOf(false) } 74 | val context = LocalContext.current 75 | val haptic = rememberHapticFeedback() 76 | Column(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { 77 | Row( 78 | modifier = Modifier 79 | .fillMaxWidth() 80 | .clickable { haptic.light(); expanded = !expanded } 81 | .padding(vertical = 8.dp), 82 | horizontalArrangement = Arrangement.SpaceBetween, 83 | verticalAlignment = Alignment.CenterVertically 84 | ) { 85 | Text(title, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f)) 86 | Icon( 87 | Icons.Filled.ExpandMore, 88 | contentDescription = if (expanded) stringResource(R.string.collapse) else stringResource(R.string.expand), 89 | modifier = Modifier.rotate(if (expanded) 180f else 0f) 90 | ) 91 | } 92 | if (expanded) { 93 | Column(modifier = Modifier.padding(start = 8.dp, bottom = 8.dp)) { 94 | content?.let { 95 | MarkdownText( 96 | it, 97 | MaterialTheme.typography.bodyMedium, 98 | MaterialTheme.colorScheme.onSurfaceVariant, 99 | context 100 | ) 101 | } 102 | subSections?.forEach { (subTitle, subContent) -> 103 | Spacer(modifier = Modifier.height(12.dp)) 104 | Text( 105 | subTitle, 106 | fontWeight = FontWeight.SemiBold, 107 | style = MaterialTheme.typography.bodyLarge 108 | ) 109 | Spacer(modifier = Modifier.height(4.dp)) 110 | MarkdownText( 111 | subContent, 112 | MaterialTheme.typography.bodyMedium, 113 | MaterialTheme.colorScheme.onSurfaceVariant, 114 | context 115 | ) 116 | } 117 | } 118 | } 119 | HorizontalDivider() 120 | } 121 | } 122 | 123 | @Composable 124 | fun MarkdownText( 125 | text: String, 126 | style: androidx.compose.ui.text.TextStyle, 127 | color: androidx.compose.ui.graphics.Color, 128 | context: android.content.Context 129 | ) { 130 | val codeBackground = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.1f) 131 | val annotatedString = buildAnnotatedString { 132 | val regex = """(`[^`]+`|\[([^]]+)]\(([^)]+)\))""".toRegex() 133 | var lastIndex = 0 134 | regex.findAll(text).forEach { m -> 135 | append(text.substring(lastIndex, m.range.first)) 136 | val matchedText = m.value 137 | if (matchedText.startsWith("`") && matchedText.endsWith("`")) { 138 | val codeText = matchedText.removeSurrounding("`") 139 | val start = length 140 | append(codeText) 141 | addStyle( 142 | SpanStyle( 143 | fontFamily = FontFamily.Monospace, 144 | background = codeBackground 145 | ), 146 | start, 147 | length 148 | ) 149 | } else { 150 | val start = length 151 | append(m.groupValues[2]) 152 | val url = m.groupValues[3] 153 | addStyle(SpanStyle(color = color, textDecoration = TextDecoration.Underline), start, length) 154 | addLink( 155 | LinkAnnotation.Clickable( 156 | tag = "URL", 157 | linkInteractionListener = { 158 | try { 159 | context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri())) 160 | } catch (_: Exception) { 161 | android.widget.Toast.makeText( 162 | context, 163 | context.getString(R.string.cannot_open_link_detail, url), 164 | android.widget.Toast.LENGTH_SHORT 165 | ).show() 166 | } 167 | } 168 | ), 169 | start, 170 | length 171 | ) 172 | } 173 | lastIndex = m.range.last + 1 174 | } 175 | if (lastIndex < text.length) append(text.substring(lastIndex)) 176 | } 177 | Text( 178 | text = annotatedString, 179 | style = style.copy(color = color) 180 | ) 181 | } 182 | 183 | fun loadFAQSections(context: android.content.Context): List { 184 | val sections = mutableListOf() 185 | try { 186 | context.assets.list("faq")?.filter { it.endsWith(".md") }?.forEach { fileName -> 187 | val lines = context.assets.open("faq/$fileName").bufferedReader().readText().lines() 188 | var title: String? = null 189 | var content = StringBuilder() 190 | var subSections = mutableListOf>() 191 | var subTitle: String? = null 192 | var subContent = StringBuilder() 193 | lines.forEach { line -> 194 | when { 195 | line.startsWith("## ") -> { 196 | title?.let { 197 | sections.add( 198 | FAQSectionData( 199 | it, 200 | content.toString().trim().ifEmpty { null }, 201 | subSections.ifEmpty { null } 202 | ) 203 | ) 204 | } 205 | title = line.removePrefix("## ").trim() 206 | content = StringBuilder() 207 | subSections = mutableListOf() 208 | subTitle = null 209 | subContent = StringBuilder() 210 | } 211 | line.startsWith("### ") -> { 212 | subTitle?.let { subSections.add(it to subContent.toString().trim()) } 213 | subTitle = line.removePrefix("### ").trim() 214 | subContent = StringBuilder() 215 | } 216 | else -> if (subTitle != null) subContent.appendLine(line) else content.appendLine(line) 217 | } 218 | } 219 | title?.let { mainTitle -> 220 | subTitle?.let { subT -> subSections.add(subT to subContent.toString().trim()) } 221 | sections.add( 222 | FAQSectionData( 223 | mainTitle, 224 | content.toString().trim().ifEmpty { null }, 225 | subSections.ifEmpty { null } 226 | ) 227 | ) 228 | } 229 | } 230 | } catch (e: Exception) { 231 | e.printStackTrace() 232 | } 233 | return sections 234 | } -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | DeJPEG 3 | Close 4 | Image 5 | Share 6 | Save 7 | Before 8 | After 9 | Save image 10 | Overwrite image? 11 | That image already exists. Overwrite? 12 | Filename 13 | Save all 14 | Don\'t show this dialog 15 | Cancel 16 | 17 | 18 | all images 19 | 20 | Remove image? 21 | You haven\'t saved %1$s yet, do you want to remove it? 22 | Remove 23 | Stop processing? 24 | Are you sure you want to stop processing %1$s? 25 | Nope 26 | Yes, stop 27 | Background service error 28 | The background processing service has encountered an error and needs to stop. Please try again. 29 | Error saving image 30 | Error saving image: %1$s 31 | Image saved to gallery 32 | Share Image 33 | Error sharing image: %1$s 34 | All %1$d images saved to gallery 35 | Error saving images: %1$s 36 | To process images in the background, this app needs to be exempted from battery optimization. 37 | Would you like to open battery optimization settings? 38 | Open settings 39 | Select image source 40 | Remember this choice 41 | Gallery 42 | Gallery picker 43 | Uses your device\'s or 3rd-party gallery app to select images. This method is recommended and works on most devices and supports filenames. 44 | Photo picker 45 | Internal photo picker 46 | Uses Android\'s built-in photo picker, more privacy aware but restricts filenames. 47 | Documents 48 | Documents provider 49 | Opens the standard SAF picker. Useful for accessing images in folders or other locations/providers. 50 | Camera 51 | Camera 52 | Opens your device\'s camera, photos taken will be imported automatically. 53 | Set as default 54 | Help 55 | OK 56 | Images (%1$d) 57 | Strength: %1$d 58 | No images yet 59 | Tap + to add images 60 | No model installed 61 | You need to import a model before you can process images. Would you like to go to settings to import one? 62 | Go to settings 63 | Active model: %1$s 64 | Import error 65 | Model management 66 | No models installed. Import a model to get started. 67 | Active 68 | Download 69 | Delete 70 | Delete models 71 | Download Models 72 | Choose a model to download: 73 | Importing model 74 | Chunk settings 75 | Chunk size 76 | Overlap size 77 | Images over %1$d px will be sliced and processed in chunks, overlap blends these to prevent visible seams. 78 | Large sizes can cause instability with low-end devices. 79 | Preferences 80 | Haptic feedback 81 | Vibration on touch 82 | Enable small vibrations for actions and gestures 83 | Unknown model 84 | FAQs 85 | Processing 86 | Finishing up... 87 | Preparing... 88 | Complete 89 | complete - tap to view 90 | Cancelled 91 | Canceling... 92 | queued 93 | Settings 94 | Add Images 95 | Process 96 | Cancel 97 | Process all 98 | BRISQUE assessment and descaling 99 | No model loaded 100 | %1$d px 101 | %1$d px 102 | App 103 | Manage save dialog and image source 104 | About 105 | Version info and license 106 | Show frequently asked questions 107 | Imported %1$s 108 | Deleted %1$s 109 | 110 | Import anyway 111 | Use anyway 112 | This model may be incompatible. Import anyway? 113 | Model: %1$s\n\n%2$s 114 | Warning 115 | Import 116 | Import model 117 | %1$d%% 118 | px 119 | DeJPEG 120 | Non-destructive restoration 121 | An open source app for removing noise and compression from photos 122 | Licensed under GPLv3 123 | GitHub 124 | Save dialog 125 | Currently: %1$s 126 | shown 127 | hidden 128 | Show save dialog 129 | Save dialog is shown 130 | Default image source 131 | none 132 | Photos 133 | Clear 134 | Not set 135 | Cannot open link 136 | Cannot open link: %1$s 137 | Expand 138 | Collapse 139 | FBCNN 140 | SCUNet 141 | Experimental models 142 | 143 | 144 | Performance warning 145 | DitherDeleterV3 is resource-intensive and not recommended, it will take a long time to process images over 500px on even high-end devices 146 | Bandage-Smooth is resource-intensive and not recommended, it will take a long time to process images over 500px on even high-end devices 147 | Outdated model 148 | This is an older f32 model. A newer/faster f16 version is available, check model management\'s download button 149 | 150 | 151 | Failed to load model 152 | Processing cancelled 153 | Processing chunk %1$d/%2$d 154 | Preparing %1$d chunks... 155 | 156 | 157 | Loading images... 158 | Loading %1$d of %2$d 159 | Saving images... 160 | Saving %1$d of %2$d 161 | --------------------------------------------------------------------------------