diff --git a/.github/actions/cache-windows-rust-tools/action.yml b/.github/actions/cache-windows-rust-tools/action.yml index 5a18bb0..951545d 100644 --- a/.github/actions/cache-windows-rust-tools/action.yml +++ b/.github/actions/cache-windows-rust-tools/action.yml @@ -16,8 +16,7 @@ runs: ~/.cargo/registry ~/.cargo/git app/desktop/windows-setup/target - key: windows-rust-${{ runner.os }}-${{ runner.arch }}-v4-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }} + key: windows-rust-${{ runner.os }}-${{ runner.arch }}-v5-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }} restore-keys: | - windows-rust-${{ runner.os }}-${{ runner.arch }}-v4- - windows-rust-${{ runner.os }}-${{ runner.arch }}-v3- + windows-rust-${{ runner.os }}-${{ runner.arch }}-v5- cargo-registry-${{ runner.os }}- diff --git a/.github/actions/restore-jvm-compile-outputs/action.yml b/.github/actions/restore-jvm-compile-outputs/action.yml new file mode 100644 index 0000000..e8a03f0 --- /dev/null +++ b/.github/actions/restore-jvm-compile-outputs/action.yml @@ -0,0 +1,27 @@ +name: Restore JVM compile outputs +description: Verify JVM compile outputs from the Build JAR artifact are present before packaging + +runs: + using: composite + steps: + - name: Verify JVM compile outputs + shell: bash + run: | + set -euo pipefail + missing=false + for path in \ + app/shared/build/classes/kotlin/jvm/main \ + app/shared/build/generated/sources/appBuildInfo/kotlin \ + utils/shared/build/classes/kotlin/jvm/main \ + app/desktop/build/classes/kotlin/main + do + if [[ ! -d "$path" ]]; then + echo "Missing $path" >&2 + missing=true + fi + done + if [[ "$missing" == "true" ]]; then + echo "JVM compile outputs artifact is incomplete" >&2 + exit 1 + fi + echo "JVM compile outputs verified" diff --git a/.github/actions/save-gradle-build-cache/action.yml b/.github/actions/save-gradle-build-cache/action.yml index 81b504c..be97a61 100644 --- a/.github/actions/save-gradle-build-cache/action.yml +++ b/.github/actions/save-gradle-build-cache/action.yml @@ -42,8 +42,29 @@ runs: !app/desktop/build/distributions !app/desktop/build/ci !app/desktop/build/compose/binaries - - name: Save Gradle build cache - if: inputs.scope != 'android' && inputs.scope != 'build-jar' + # Restore-only for the desktop packaging scopes (linux-*, windows-package-*, + # macos-*): measurements showed their build trees are ~1.3–2 GB each and are + # dominated by installer outputs (deb/rpm/AppImage/DMG/Setup.exe), the jpackage + # runtime image copied up to four times, and staged ProGuard jars — all of which + # regenerate from the Build JAR artifact in a few minutes. Saving six 1.3–2 GB + # entries per run kept the repo pinned at the 10 GB cache cap and LRU-evicted + # the entries that actually matter (build-jar, android, windows-rust) within + # minutes. Their restores now fall back to the build-jar scope via restore-keys. + # (Note: actions/cache negated path patterns cannot exclude subtrees of an + # included parent directory — actions/toolkit#713 — so "!distributions" style + # exclusions are no-ops here; not saving at all is the only reliable trim.) + - name: Save Gradle build cache (windows-tools only) + if: >- + inputs.scope != 'android' && inputs.scope != 'build-jar' && + !startsWith(inputs.scope, 'linux-') && + !startsWith(inputs.scope, 'windows-package-') && + !startsWith(inputs.scope, 'macos-') + # Path list must stay byte-identical to the generic restore list in + # cache-gradle-build: actions/cache refuses to save when the restore and save + # paths differ, and the version stamp (hash of the path list) gates any later + # restore — including cross-scope restore-key fallbacks. compose/tmp is kept + # here on purpose (holds ProGuard's output jars; small); see the matching + # comment in cache-gradle-build. uses: actions/cache/save@v5 continue-on-error: true with: @@ -57,4 +78,3 @@ runs: !app/desktop/build/distributions !app/desktop/build/ci !app/desktop/build/compose/binaries - !app/desktop/build/compose/tmp diff --git a/.github/actions/save-windows-rust-cache/action.yml b/.github/actions/save-windows-rust-cache/action.yml index 8ff50e2..09f17ce 100644 --- a/.github/actions/save-windows-rust-cache/action.yml +++ b/.github/actions/save-windows-rust-cache/action.yml @@ -4,10 +4,15 @@ description: Save Cargo registry, git checkouts, and the windows-setup target di runs: using: composite steps: + # The save key MUST match cache-windows-rust-tools' exact restore key byte for byte: it has to + # carry runner.arch — the two matrix legs race to save the same key otherwise (actions/cache + # rejects the second with "another job may be creating this cache"), and a saved entry without + # the arch can never be restored because no restore key matches its shape. v3 was an archless + # relic: every entry it ever wrote was dead on arrival. - uses: actions/cache/save@v5 continue-on-error: true with: - key: windows-rust-${{ runner.os }}-v3-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }} + key: windows-rust-${{ runner.os }}-${{ runner.arch }}-v5-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }} path: | ~/.cargo/registry ~/.cargo/git diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a38435a..ed27b45 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -174,6 +174,7 @@ jobs: timeout-minutes: 45 env: FROMCHAT_PREBUILT_PROGUARD: "0" + ORG_GRADLE_PROJECT_org.gradle.workers.max: "4" steps: - uses: actions/checkout@v5 - uses: ./.github/actions/restore-git-mtimes @@ -199,6 +200,16 @@ jobs: path: app/desktop/build/ci/proguard/ if-no-files-found: error retention-days: 3 + - uses: actions/upload-artifact@v5 + with: + name: jvm-compile-outputs + path: | + app/shared/build + utils/shared/build + app/desktop/build/classes + app/desktop/build/libs + if-no-files-found: error + retention-days: 3 windows-tools: name: Windows tools (${{ matrix.label }}) @@ -285,6 +296,7 @@ jobs: if: needs.check-build.outputs.should_build == 'true' env: FROMCHAT_PREBUILT_PROGUARD: "1" + FROMCHAT_PREBUILT_JVM: "1" strategy: fail-fast: false matrix: @@ -328,6 +340,11 @@ jobs: with: name: desktop-proguard path: app/desktop/build/prebuilt/main-release/proguard + - uses: actions/download-artifact@v5 + with: + name: jvm-compile-outputs + path: . + - uses: ./.github/actions/restore-jvm-compile-outputs # Tooling for this architecture, built natively by the windows-tools matrix leg. The two # architectures must not share: fromchat-pack selects the embedded payload with # std::env::consts::ARCH, so an x64 stub on ARM64 reports "x86_64" and finds no x86_64 @@ -369,15 +386,20 @@ jobs: if: needs.check-build.outputs.should_build == 'true' env: FROMCHAT_PREBUILT_PROGUARD: "1" + FROMCHAT_PREBUILT_JVM: "1" strategy: fail-fast: false matrix: include: - arch: arm64 label: Apple Silicon + runner: macos-latest + # jpackage cannot cross-build: on an arm64 runner this job silently ships + # arm64 binaries under the -intel.dmg name (beta18 did exactly that). - arch: x64 label: Intel - runs-on: macos-latest + runner: macos-26-intel + runs-on: ${{ matrix.runner }} timeout-minutes: 60 steps: - uses: actions/checkout@v5 @@ -402,28 +424,56 @@ jobs: with: name: desktop-proguard path: app/desktop/build/prebuilt/main-release/proguard + - uses: actions/download-artifact@v5 + with: + name: jvm-compile-outputs + path: . + - uses: ./.github/actions/restore-jvm-compile-outputs - name: Cache DMG background tooling uses: actions/cache@v5 with: path: | app/desktop/dmg-background/node_modules - ~/.cache/ms-playwright + app/desktop/dmg-background/.playwright-browsers key: dmg-tools-${{ runner.arch }}-${{ hashFiles('app/desktop/dmg-background/package-lock.json') }} restore-keys: dmg-tools-${{ runner.arch }}- + - name: Cache DMG export output + uses: actions/cache@v5 + with: + path: app/desktop/build/dmg-background/dist + key: dmg-export-${{ runner.arch }}-${{ hashFiles('app/desktop/dmg-background/**', 'app/shared/src/commonMain/composeResources/drawable/logo_square.png') }} + restore-keys: dmg-export-${{ runner.arch }}- - name: Install macOS packaging tools + env: + PLAYWRIGHT_BROWSERS_PATH: ${{ github.workspace }}/app/desktop/dmg-background/.playwright-browsers run: | if ! command -v create-dmg >/dev/null 2>&1; then brew install create-dmg fi DMG_DIR="app/desktop/dmg-background" + mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" if [[ ! -f "$DMG_DIR/node_modules/playwright/package.json" ]]; then npm --prefix "$DMG_DIR" ci --no-fund --no-audit fi npm --prefix "$DMG_DIR" exec playwright install chromium + echo "FROMCHAT_DMG_TOOLS_READY=1" >> "$GITHUB_ENV" + echo "PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH" >> "$GITHUB_ENV" - name: Package macOS ${{ matrix.arch }} run: | export FROMCHAT_PACKAGING_JDK="$JAVA_HOME" ./gradlew :app:desktop:packageReleaseMac -PdesktopArch=${{ matrix.arch }} --no-daemon --console=plain + # jpackage only reports its error text in files on the runner surface — surface them. + - name: Dump jpackage logs on failure + if: failure() + run: | + for t in createReleaseDistributable createDmgOther; do + D="app/desktop/build/compose/logs/$t" + [[ -d "$D" ]] || continue + for f in "$D"/*.txt; do + echo "===== $f" + cat "$f" + done + done - uses: actions/upload-artifact@v5 with: name: macos-${{ matrix.arch }} @@ -440,6 +490,7 @@ jobs: if: needs.check-build.outputs.should_build == 'true' env: FROMCHAT_PREBUILT_PROGUARD: "1" + FROMCHAT_PREBUILT_JVM: "1" strategy: fail-fast: false matrix: @@ -472,6 +523,11 @@ jobs: with: name: desktop-proguard path: app/desktop/build/prebuilt/main-release/proguard + - uses: actions/download-artifact@v5 + with: + name: jvm-compile-outputs + path: . + - uses: ./.github/actions/restore-jvm-compile-outputs - name: Install Linux packaging tools run: | sudo apt-get update @@ -489,6 +545,9 @@ jobs: run: | # Keep the jmods-capable JDK the setup action exported; fall back to JAVA_HOME. export FROMCHAT_PACKAGING_JDK="${FROMCHAT_PACKAGING_JDK:-$JAVA_HOME}" + # packageReleaseDeb/rpm are the slow, quiet parts of this invocation (profiled 2026-10-20: + # ~45s/~23s single-threaded jpackage compression) — candidates for parallel-invocation + # packaging if we ever want to shorten this leg. ./gradlew :app:desktop:packageReleaseLinux -PdesktopArch=${{ matrix.arch }} --no-daemon --console=plain - uses: actions/upload-artifact@v5 with: diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 2f43577..ae96709 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -8,6 +8,6 @@ - + \ No newline at end of file diff --git a/README.en.md b/README.en.md index 8f8f208..3367f1a 100644 --- a/README.en.md +++ b/README.en.md @@ -42,7 +42,7 @@ Build release packages on the matching OS (or via CI): Outputs land under `app/desktop/build/distributions/release/`. -**CI:** `.github/workflows/desktop-release.yml` runs on `v*` tags and `workflow_dispatch` (required `version` input), then uploads assets to a GitHub Release. +**CI:** `.github/workflows/release.yml` runs on `workflow_dispatch` only (required `version` input; the `v*` tag does not need to exist beforehand — the publish step creates it), then uploads assets to a GitHub Release. **Windows portable:** extracts into a folder where only `FromChat Portable.exe` is visible; other runtime files are Hidden. Data is stored in a Hidden `fromchat-data/` next to that EXE (`-Dfromchat.portable=true`). diff --git a/README.md b/README.md index b39ddbc..226ad56 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ Desktop заменяет бывший Electron-клиент в репозито Результаты: `app/desktop/build/distributions/release/`. -**CI:** `.github/workflows/desktop-release.yml` на тегах `v*` и `workflow_dispatch` (обязательный input `version`), затем загрузка в GitHub Release. +**CI:** `.github/workflows/release.yml` запускается только через `workflow_dispatch` (обязательный input `version`; тег `v*` создавать заранее не нужно — publish создаёт его сам), затем загрузка в GitHub Release. **Windows portable:** в папке виден только `FromChat Portable.exe`; остальной runtime — Hidden. Данные в Hidden `fromchat-data/` рядом с EXE. diff --git a/app/desktop/build.gradle.kts b/app/desktop/build.gradle.kts index 49f2805..4c78b25 100644 --- a/app/desktop/build.gradle.kts +++ b/app/desktop/build.gradle.kts @@ -2,6 +2,7 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.file.Files +import java.nio.file.Path import java.util.zip.ZipFile plugins { @@ -778,16 +779,24 @@ private fun openjfxClassifier(): String { val runningOnMacOs = System.getProperty("os.name").orEmpty().lowercase().contains("mac") +private val ciDmgToolsReady = + providers.environmentVariable("FROMCHAT_DMG_TOOLS_READY").map { it == "1" }.orElse(false) + +val dmgPlaywrightBrowsersDir = dmgBackgroundDir.dir(".playwright-browsers") + val installDmgBackgroundTools = tasks.register("installDmgBackgroundTools") { - onlyIf { runningOnMacOs } + onlyIf { runningOnMacOs && !ciDmgToolsReady.get() } workingDir = dmgBackgroundDir.asFile inputs.file(dmgBackgroundDir.file("package.json")) inputs.file(dmgBackgroundDir.file("package-lock.json")) outputs.dir(dmgBackgroundDir.dir("node_modules/playwright")) + outputs.dir(dmgPlaywrightBrowsersDir) commandLine( "bash", "-lc", """ + export PLAYWRIGHT_BROWSERS_PATH="${dmgPlaywrightBrowsersDir.asFile.absolutePath}" + mkdir -p "${'$'}PLAYWRIGHT_BROWSERS_PATH" if [ ! -f node_modules/playwright/package.json ]; then npm install --no-fund --no-audit fi @@ -825,11 +834,18 @@ val exportDmgBackground = tasks.register("exportDmgBackground") { val stage = dmgStageDir.get().asFile.absolutePath val dist = dmgDistDir.get().asFile.absolutePath inputs.dir(dmgStageDir) + inputs.file(dmgBackgroundDir.file("export.mjs")) + inputs.file(dmgBackgroundDir.file("dmg-config.json")) outputs.dir(dmgDistDir) + outputs.file(dmgDistDir.map { it.file("icon-positions.json") }) + outputs.file(dmgDistDir.map { it.file("dmg-background@2x.png") }) commandLine( "bash", "-lc", - "node export.mjs '${stage}' '${dist}'", + """ + export PLAYWRIGHT_BROWSERS_PATH="${dmgPlaywrightBrowsersDir.asFile.absolutePath}" + node export.mjs '${stage}' '${dist}' + """.trimIndent(), ) } @@ -963,6 +979,39 @@ if (runningOnLinux && skikoVirglWorkaround.get()) { } +/** AppDir icons for appimagetool (file manager + embedded AppImage icon). */ +private fun stageLinuxAppImageIcons(stage: File, iconSrc: File) { + if (!iconSrc.isFile) { + logger.warn("AppImage icon missing at ${iconSrc.absolutePath}") + return + } + val rootIcon = stage.resolve("fromchat.png") + iconSrc.copyTo(rootIcon, overwrite = true) + stage.resolve(".DirIcon").let { link -> + link.delete() + Files.createSymbolicLink(link.toPath(), Path.of("fromchat.png")) + } + for (size in listOf("256x256", "512x512")) { + val dest = stage.resolve("usr/share/icons/hicolor/$size/apps/fromchat.png") + dest.parentFile.mkdirs() + iconSrc.copyTo(dest, overwrite = true) + } +} + +private fun writeLinuxAppImageDesktopFile(stage: File) { + stage.resolve("fromchat.desktop").writeText( + """ + [Desktop Entry] + Name=FromChat + Exec=AppRun + Icon=fromchat + Type=Application + Categories=Network;InstantMessaging; + StartupWMClass=FromChat + """.trimIndent() + "\n", + ) +} + val releaseAppImageDir = layout.buildDirectory.dir("compose/binaries/main-release/app/FromChat") val debugAppImageDir = layout.buildDirectory.dir("compose/binaries/main/app/FromChat") val linuxAppImageOutput = desktopDistDir.map { @@ -1086,28 +1135,23 @@ val packageLinuxAppImage = tasks.register("packageLinuxAppImage") { val appRun = stage.resolve("AppRun") val rel = stage.toPath().relativize(nestedExe.toPath()).toString() appRun.writeText( - $$""" + """ #!/bin/sh - SELF="$(dirname "$(readlink -f "$0")")" - exec "$SELF/$$rel" "$@" + SELF="${'$'}(dirname "${'$'}(readlink -f "${'$'}0")")" + case "${'$'}(uname -m)" in + aarch64|arm64) + if [ -z "${'$'}MESA_GL_VERSION_OVERRIDE" ]; then + export MESA_GL_VERSION_OVERRIDE=3.0 + fi + ;; + esac + exec "${'$'}SELF/$rel" "${'$'}@" """.trimIndent() + "\n", ) appRun.setExecutable(true) nestedExe.setExecutable(true) - stage.resolve("fromchat.desktop").writeText( - """ - [Desktop Entry] - Name=FromChat - Exec=AppRun - Icon=fromchat - Type=Application - Categories=Network;InstantMessaging; - """.trimIndent() + "\n", - ) - val iconSrc = desktopWindowIconPng.asFile - if (iconSrc.isFile) { - iconSrc.copyTo(stage.resolve("fromchat.png"), overwrite = true) - } + writeLinuxAppImageDesktopFile(stage) + stageLinuxAppImageIcons(stage, desktopWindowIconPng.asFile) commandLine( "bash", "-lc", diff --git a/app/desktop/proguard-rules.pro b/app/desktop/proguard-rules.pro index c1c5911..8c70895 100644 --- a/app/desktop/proguard-rules.pro +++ b/app/desktop/proguard-rules.pro @@ -14,6 +14,18 @@ } -keep class org.sqlite.** { *; } +# JNA resolves some Java methods *from native code* by name (jnidispatch looks up +# com.sun.jna.Native#dispose via GetStaticMethodID during initIDs), and the app's +# Win32 mappings / WindowProc callbacks / Structures are loaded reflectively. +# ProGuard must not strip or rename any of it — stripping Native#dispose made every +# Windows package die at JVM start with "Failed to launch JVM" +# (UnsatisfiedLinkError: Can't obtain static method dispose from class com.sun.jna.Native, +# thrown from com.sun.jna.platform.win32.Shell32. in Main.kt; Linux/macOS never +# load Shell32, which is why only the Windows builds were affected). +-keep class com.sun.jna.** { *; } +-keep class * extends com.sun.jna.** { *; } +-keep class * implements com.sun.jna.** { *; } + # BouncyCastle security providers (ServiceLoader java.security.Provider). -keep class org.bouncycastle.jce.provider.BouncyCastleProvider { *; } -keep class org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider { *; } diff --git a/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChrome.kt b/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChrome.kt index 86f67a9..1342df7 100644 --- a/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChrome.kt +++ b/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChrome.kt @@ -2,6 +2,7 @@ package ru.fromchat.desktop import ru.fromchat.config.Settings import ru.fromchat.ui.Theme +import ru.fromchat.ui.jvmPlatformSystemDarkTheme import javax.swing.JRootPane internal fun isMacOs(): Boolean = @@ -38,117 +39,10 @@ internal fun desktopAppDarkTheme(): Boolean = when (runCatching { Settings.theme }.getOrDefault(Theme.AsSystem)) { Theme.Dark -> true Theme.Light -> false - Theme.AsSystem -> desktopSystemDarkTheme() + Theme.AsSystem -> jvmPlatformSystemDarkTheme() } -internal fun desktopSystemDarkTheme(): Boolean = runCatching { - when { - isMacOs() -> - ProcessBuilder("defaults", "read", "-g", "AppleInterfaceStyle") - .redirectErrorStream(true) - .start() - .inputStream - .bufferedReader() - .readText() - .trim() - .equals("Dark", ignoreCase = true) - isWindowsOs() -> isWindowsAppsDarkTheme() - isLinuxOs() -> isLinuxAppsDarkTheme() - else -> false - } -}.getOrDefault(false) - -private fun isLinuxAppsDarkTheme(): Boolean { - readGsettingsValue("org.gnome.desktop.interface", "color-scheme")?.let { scheme -> - when { - scheme.contains("dark", ignoreCase = true) -> return true - scheme.contains("light", ignoreCase = true) -> return false - } - } - readGsettingsValue("org.gnome.desktop.interface", "gtk-theme")?.let { theme -> - if (theme.contains("dark", ignoreCase = true)) return true - if (theme.contains("light", ignoreCase = true)) return false - } - readPortalColorScheme()?.let { value -> - return when (value) { - 1 -> true - 2 -> false - else -> false - } - } - readKdeColorScheme()?.let { scheme -> - if (scheme.contains("dark", ignoreCase = true)) return true - } - return false -} - -private fun readGsettingsValue(schema: String, key: String): String? { - val process = ProcessBuilder("gsettings", "get", schema, key) - .redirectErrorStream(true) - .start() - val output = process.inputStream.bufferedReader().readText().trim() - process.waitFor() - if (process.exitValue() != 0 || output.isEmpty() || output == "@as []") return null - return output.trim('"') -} - -private fun readPortalColorScheme(): Int? = runCatching { - val process = ProcessBuilder( - "gdbus", - "call", - "--session", - "--dest", - "org.freedesktop.portal.Desktop", - "--object-path", - "/org/freedesktop/portal/desktop", - "--method", - "org.freedesktop.portal.Settings.Read", - "org.freedesktop.appearance", - "color-scheme", - ) - .redirectErrorStream(true) - .start() - val output = process.inputStream.bufferedReader().readText() - process.waitFor() - if (process.exitValue() != 0) return null - Regex("""\(\s*<(\d+)>\s*,\s*""").find(output)?.groupValues?.getOrNull(1)?.toIntOrNull() -}.getOrNull() - -private fun readKdeColorScheme(): String? = runCatching { - val process = ProcessBuilder( - "kreadconfig6", - "--file", - "kdeglobals", - "--group", - "General", - "--key", - "ColorScheme", - ) - .redirectErrorStream(true) - .start() - val output = process.inputStream.bufferedReader().readText().trim() - process.waitFor() - if (process.exitValue() != 0 || output.isEmpty()) null else output -}.getOrNull() - -private fun isWindowsAppsDarkTheme(): Boolean { - val process = ProcessBuilder( - "reg", - "query", - "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", - "/v", - "AppsUseLightTheme", - ) - .redirectErrorStream(true) - .start() - val output = process.inputStream.bufferedReader().readText() - process.waitFor() - return when { - "0x0" in output -> true - "0x1" in output -> false - else -> false - } -} +internal fun desktopSystemDarkTheme(): Boolean = jvmPlatformSystemDarkTheme() /** Enables drawing under the system title bar on macOS. */ internal fun applyDesktopEdgeToEdgeChrome(rootPane: JRootPane) { diff --git a/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChromeSetup.kt b/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChromeSetup.kt index ed72781..dc5277b 100644 --- a/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChromeSetup.kt +++ b/app/desktop/src/main/kotlin/ru/fromchat/desktop/DesktopWindowChromeSetup.kt @@ -25,10 +25,11 @@ import ru.fromchat.api.local.db.isSqliteBusy import ru.fromchat.ui.FromChatTheme import ru.fromchat.ui.LocalExtraStatusBarTop import ru.fromchat.ui.getColorScheme +import ru.fromchat.ui.isAppInDarkTheme import java.awt.image.BufferedImage -internal fun desktopThemeBackgroundCompose(): Color = - if (desktopAppDarkTheme()) Color(0xFF1C1B1F) else Color(0xFFFFFBFE) +internal fun desktopThemeBackgroundCompose(darkTheme: Boolean): Color = + if (darkTheme) Color(0xFF1C1B1F) else Color(0xFFFFFBFE) @OptIn(ExperimentalComposeUiApi::class) internal fun installDesktopWindowExceptionHandler(window: ComposeWindow) { @@ -53,7 +54,8 @@ internal fun FrameWindowScope.DesktopRootSurface( onCloseRequest: () -> Unit, content: @Composable () -> Unit, ) { - val windowChrome = desktopThemeBackgroundCompose() + val appInDarkTheme = isAppInDarkTheme() + val windowChrome = desktopThemeBackgroundCompose(appInDarkTheme) LaunchedEffect(window, appName, windowChrome) { window.title = appName @@ -81,7 +83,7 @@ internal fun FrameWindowScope.DesktopRootSurface( onDispose {} } - FromChatTheme(darkTheme = desktopAppDarkTheme()) { + FromChatTheme(darkTheme = appInDarkTheme) { CompositionLocalProvider( LocalExtraStatusBarTop provides when { customFrame -> WindowsTitleBarHeight @@ -95,7 +97,7 @@ internal fun FrameWindowScope.DesktopRootSurface( ) { content() if (customFrame) { - MaterialTheme(colorScheme = getColorScheme(desktopAppDarkTheme(), dynamicColor = false)) { + MaterialTheme(colorScheme = getColorScheme(appInDarkTheme, dynamicColor = false)) { WindowsDesktopTitleBar( title = appName, windowIcon = windowIcon, diff --git a/app/desktop/src/main/kotlin/ru/fromchat/desktop/Main.kt b/app/desktop/src/main/kotlin/ru/fromchat/desktop/Main.kt index 7ea7168..f166601 100644 --- a/app/desktop/src/main/kotlin/ru/fromchat/desktop/Main.kt +++ b/app/desktop/src/main/kotlin/ru/fromchat/desktop/Main.kt @@ -48,6 +48,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import com.sun.jna.Library +import com.sun.jna.Native import org.jetbrains.compose.resources.stringResource import ru.fromchat.AppBuildInfo import ru.fromchat.AppForeground @@ -93,6 +95,7 @@ import ru.fromchat.ui.App import ru.fromchat.ui.LocalExtraStatusBarTop import ru.fromchat.ui.Theme import ru.fromchat.ui.getColorScheme +import ru.fromchat.ui.isAppInDarkTheme import java.awt.Desktop import java.awt.Image import java.awt.KeyboardFocusManager @@ -280,6 +283,7 @@ private object DesktopProtocolRegistration { } fun main(args: Array) { + LinuxArm64MesaEnvironment.applyIfNeeded() Thread.setDefaultUncaughtExceptionHandler { thread, throwable -> if (isSqliteBusy(throwable)) { if (!DatabaseLockGate.onSqliteBusy(throwable)) { @@ -466,7 +470,8 @@ fun main(args: Array) { TrayConnectionStatus.Connecting -> stringResource(Res.string.status_connecting) } - val windowChrome = remember { desktopThemeBackgroundCompose() } + val appInDarkTheme = isAppInDarkTheme() + val windowChrome = desktopThemeBackgroundCompose(appInDarkTheme) // Armed once the restored geometry has had time to settle; until then nothing is // persisted. See the LaunchedEffect below. @@ -830,7 +835,7 @@ fun main(args: Array) { onContentReady = { contentReady = true }, ) if (customFrame) { - MaterialTheme(colorScheme = getColorScheme(desktopAppDarkTheme(), dynamicColor = false)) { + MaterialTheme(colorScheme = getColorScheme(appInDarkTheme, dynamicColor = false)) { WindowsDesktopTitleBar( title = appName, windowIcon = windowIcon, @@ -973,9 +978,29 @@ private fun configureDesktopAppDataName() { /** * Skia for linux/arm64 is GLES-only, so against Mesa-run GL it must see version 3.0 - * (see the skiko-virgl patch in app/desktop/build.gradle.kts). Applied by generated - * launcher entries via Exec=env MESA_GL_VERSION_OVERRIDE=3.0 . + * (see the skiko-virgl patch in app/desktop/build.gradle.kts). Set before Skiko loads + * (here and in the AppImage AppRun) and in generated desktop entries via + * [mesaGlVersionOverridePrefix]. */ +private object LinuxArm64MesaEnvironment { + private interface LibC : Library { + fun setenv(name: String, value: String, overwrite: Int): Int + } + + private val libc: LibC? = + if (isLinuxOs() && System.getProperty("os.arch") == "aarch64") { + runCatching { Native.load("c", LibC::class.java) }.getOrNull() + } else { + null + } + + fun applyIfNeeded() { + if (!isLinuxOs() || System.getProperty("os.arch") != "aarch64") return + if (!System.getenv("MESA_GL_VERSION_OVERRIDE").isNullOrBlank()) return + libc?.setenv("MESA_GL_VERSION_OVERRIDE", "3.0", 1) + } +} + private fun mesaGlVersionOverridePrefix(): String = if (isLinuxOs() && System.getProperty("os.arch") == "aarch64") { "env MESA_GL_VERSION_OVERRIDE=3.0 " @@ -1094,7 +1119,10 @@ private object LinuxAppIdentity { * Colors match Material3 [darkColorScheme]/[lightColorScheme] defaults used by [ru.fromchat.ui.getColorScheme]. */ private fun applyDesktopWindowChromeBackground() { - UIManager.put("control", ColorUIResource(desktopThemeBackgroundCompose().toAwtColor())) + UIManager.put( + "control", + ColorUIResource(desktopThemeBackgroundCompose(desktopAppDarkTheme()).toAwtColor()), + ) } private fun Color.toAwtColor() = diff --git a/app/desktop/src/main/kotlin/ru/fromchat/desktop/WindowsDesktopTitleBar.kt b/app/desktop/src/main/kotlin/ru/fromchat/desktop/WindowsDesktopTitleBar.kt index 4247adc..bec0183 100644 --- a/app/desktop/src/main/kotlin/ru/fromchat/desktop/WindowsDesktopTitleBar.kt +++ b/app/desktop/src/main/kotlin/ru/fromchat/desktop/WindowsDesktopTitleBar.kt @@ -63,15 +63,12 @@ fun WindowScope.WindowsDesktopTitleBar( val windowActive = rememberWindowsFrameActive(window) val isMaximized = windowState.placement == WindowPlacement.Maximized val scheme = MaterialTheme.colorScheme - val titleColor = Color.White + val titleColor = scheme.onSurface val titleAlpha = if (windowActive) 1f else 0.63f - val barBackground = Color.Transparent - Row( modifier .fillMaxWidth() - .height(WindowsTitleBarHeight) - .background(barBackground), + .height(WindowsTitleBarHeight), verticalAlignment = Alignment.CenterVertically, ) { WindowDraggableArea( @@ -154,8 +151,8 @@ private fun TitleBarWindowButton( ) val iconTint = when { isClose && hoverTarget -> scheme.onError - windowActive -> Color.White - else -> Color.White.copy(alpha = 0.63f) + windowActive -> scheme.onSurface + else -> scheme.onSurface.copy(alpha = 0.63f) } val hoverColor = if (isClose && hoverTarget) { diff --git a/app/shared/src/androidMain/kotlin/ru/fromchat/ui/Theme.android.kt b/app/shared/src/androidMain/kotlin/ru/fromchat/ui/Theme.android.kt index 902c376..5642f69 100644 --- a/app/shared/src/androidMain/kotlin/ru/fromchat/ui/Theme.android.kt +++ b/app/shared/src/androidMain/kotlin/ru/fromchat/ui/Theme.android.kt @@ -7,6 +7,7 @@ import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color @@ -25,6 +26,9 @@ actual fun getColorScheme(darkTheme: Boolean, dynamicColor: Boolean) = else lightColorScheme() } +@Composable +actual fun rememberPlatformSystemDarkTheme(): Boolean = isSystemInDarkTheme() + @Composable actual fun ApplySystemBarTheme(darkTheme: Boolean, surfaceColor: Color) { val view = LocalView.current diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/api/ApiClient.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/api/ApiClient.kt index 9f9c56d..59ac0ce 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/api/ApiClient.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/api/ApiClient.kt @@ -32,6 +32,7 @@ import io.ktor.client.request.post import io.ktor.client.request.put import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse +import io.ktor.client.statement.readRawBytes import io.ktor.http.ContentType import io.ktor.http.Headers import io.ktor.http.HttpHeaders @@ -988,6 +989,24 @@ object ApiClient { /** Plain public-chat attachment URL (same path resolution as [encryptedFileUrl]). */ fun normalFileUrl(path: String): String = encryptedFileUrl(path) + /** JPEG thumbnail URL for a public normal attachment (`THUMBS_DIR/{stem}.jpg`). */ + fun publicThumbnailUrl(normalFilePath: String): String? { + val basename = normalFilePath.substringAfterLast('/').takeIf { it.isNotEmpty() } ?: return null + val stem = basename.substringBeforeLast('.').takeIf { it.isNotEmpty() } ?: return null + return encryptedFileUrl("/uploads/files/thumbs/$stem.jpg") + } + + /** Best-effort fetch when [Message.fileThumbnails] is empty but the thumb exists on the server. */ + suspend fun fetchPublicThumbnailBytes(normalFilePath: String): ByteArray? { + val url = publicThumbnailUrl(normalFilePath) ?: return null + return runCatching { + http.get(url) { + token?.let { bearerAuth(it) } + header(HttpHeaders.UserAgent, currentDownloadUserAgent()) + }.readRawBytes() + }.getOrNull()?.takeIf { it.isNotEmpty() } + } + /** Encrypted ciphertext stored on disk after a resumable download. */ data class EncryptedFileOnDisk( val path: String, diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/api/local/cache/DecryptedImageCache.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/api/local/cache/DecryptedImageCache.kt index 14c8a04..6554930 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/api/local/cache/DecryptedImageCache.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/api/local/cache/DecryptedImageCache.kt @@ -20,6 +20,7 @@ import ru.fromchat.ui.chat.utils.AttachmentDownloadVisibility import ru.fromchat.api.local.cache.DecryptedImageCache.storageKey import ru.fromchat.api.local.download.LocalDecodedImageCache import ru.fromchat.api.local.download.ChatPreviewDecodeSize +import ru.fromchat.api.local.download.decodeImageBytes import ru.fromchat.api.local.download.decodeLocalImageFile /** @@ -142,18 +143,35 @@ object DecryptedImageCache { } } + /** Decode embedded thumbnail bytes synchronously for first frame (no network). */ + fun decodeEmbeddedPlaceholderThumb(memoryKey: String, serverThumbBytes: ByteArray?): androidx.compose.ui.graphics.ImageBitmap? { + LocalDecodedImageCache.peekThumb(memoryKey)?.let { return it } + val thumbBytes = serverThumbBytes?.takeIf { it.isNotEmpty() } ?: return null + val target = ChatPreviewDecodeSize( + ATTACHMENT_DISK_THUMB_MAX_EDGE_PX, + ATTACHMENT_DISK_THUMB_MAX_EDGE_PX, + ) + return decodeImageBytes(thumbBytes, target.widthPx, target.heightPx)?.also { bitmap -> + LocalDecodedImageCache.putThumb(memoryKey, bitmap) + } + } + suspend fun decodePlaceholderThumb( memoryKey: String, messageId: Int, fileIndex: Int, clientMessageId: String?, serverThumbBytes: ByteArray?, + publicNormalFilePath: String? = null, ): androidx.compose.ui.graphics.ImageBitmap? = withContext(Dispatchers.Default) { peekPlaceholderThumb(memoryKey, messageId, fileIndex, clientMessageId)?.let { return@withContext it } // Prefer server base64 before generating a disk thumb from a huge full file. - val thumbBytes = serverThumbBytes?.takeIf { it.isNotEmpty() } + var thumbBytes = serverThumbBytes?.takeIf { it.isNotEmpty() } + if (thumbBytes == null && !publicNormalFilePath.isNullOrBlank()) { + thumbBytes = ApiClient.fetchPublicThumbnailBytes(publicNormalFilePath) + } if (thumbBytes != null) { val target = ChatPreviewDecodeSize( ATTACHMENT_DISK_THUMB_MAX_EDGE_PX, diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/api/schema/messages/MessagesResponse.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/api/schema/messages/MessagesResponse.kt index 5f751da..ae5e17c 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/api/schema/messages/MessagesResponse.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/api/schema/messages/MessagesResponse.kt @@ -1,9 +1,19 @@ package ru.fromchat.api.schema.messages +import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MessagesResponse( val status: String, - val messages: List -) \ No newline at end of file + val messages: List, + @SerialName("has_more") val hasMore: Boolean = false, + @SerialName("has_more_before") val hasMoreBefore: Boolean = false, + @SerialName("has_more_after") val hasMoreAfter: Boolean = false, +) + +/** Whether another `before_id` page likely exists (public chat scroll-up). */ +fun MessagesResponse.hasMoreOlderHistory(pageSize: Int): Boolean { + if (messages.isEmpty()) return false + return hasMoreBefore || hasMore || messages.size >= pageSize +} \ No newline at end of file diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/Theme.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/Theme.kt index d2bc6da..e9660ab 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/Theme.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/Theme.kt @@ -1,7 +1,6 @@ package ru.fromchat.ui import androidx.compose.animation.animateColorAsState -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ColorScheme import androidx.compose.material3.MaterialTheme @@ -56,13 +55,12 @@ expect fun getColorScheme(darkTheme: Boolean, dynamicColor: Boolean): ColorSchem @Composable expect fun ApplySystemBarTheme(darkTheme: Boolean, surfaceColor: Color) +@Composable +expect fun rememberPlatformSystemDarkTheme(): Boolean + @Composable fun FromChatTheme( - darkTheme: Boolean = when (theme) { - Theme.AsSystem -> isSystemInDarkTheme() - Theme.Light -> false - Theme.Dark -> true - }, + darkTheme: Boolean = isAppInDarkTheme(), dynamicColor: Boolean = dynamicThemeEnabled, content: @Composable () -> Unit ) { @@ -154,8 +152,9 @@ fun FromChatTheme( @Composable fun isAppInDarkTheme(): Boolean { + val systemDark = rememberPlatformSystemDarkTheme() return when (theme) { - Theme.AsSystem -> isSystemInDarkTheme() + Theme.AsSystem -> systemDark Theme.Light -> false Theme.Dark -> true } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/AttachmentPreview.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/AttachmentPreview.kt index 8ab46f1..fd544c3 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/AttachmentPreview.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/AttachmentPreview.kt @@ -46,7 +46,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue @@ -96,7 +95,6 @@ import ru.fromchat.attachment_upload_failed_too_large import ru.fromchat.cd_attachment_retry import ru.fromchat.cd_attachment_upload_retry import ru.fromchat.ui.chat.MessageGroupInfo -import ru.fromchat.ui.chat.components.AttachmentLeadingTransitionMs import ru.fromchat.ui.chat.components.CancellableAttachmentProgressIndicator import ru.fromchat.ui.chat.components.ChatFileAttachmentTile import ru.fromchat.ui.chat.components.FileAttachmentLeadingSlot @@ -111,12 +109,7 @@ import ru.fromchat.ui.components.Text import com.pr0gramm3r101.utils.scaleOnPress private const val BLUR_FADE_MS = 450 - -private enum class AttachmentTileVisual { - Empty, - Thumb, - Full, -} +private const val TILE_OVERLAY_FADE_MS = 180 internal fun isImageFilename(name: String): Boolean = name.endsWith(".png", true) || name.endsWith(".jpg", true) || @@ -368,43 +361,65 @@ private fun ChatImageTileContent( val thumbnailBytes = remember(thumbnailBase64) { thumbnailBase64?.let { decodeAttachmentThumbnailBase64(it) } } - val initialPlaceholder = remember(bitmapStateKey) { + val publicThumbFilePath = remember(serverFile, envelope) { + if (envelope != null) null + else serverFile?.path?.takeIf { path -> + path.contains("/normal/") || path.contains("/uploads/") + } + } + val initialPlaceholder = remember( + bitmapStateKey, + placeholderMemoryKey, + thumbnailBytes, + messageId, + fileIndex, + cacheClientId, + ) { DecryptedImageCache.peekPlaceholderThumb( memoryKey = placeholderMemoryKey, messageId = messageId, fileIndex = fileIndex, clientMessageId = cacheClientId, - ) + ) ?: DecryptedImageCache.decodeEmbeddedPlaceholderThumb(placeholderMemoryKey, thumbnailBytes) } - val placeholderBitmap by produceState( - initialValue = initialPlaceholder, + var placeholderBitmap by remember(bitmapStateKey) { + mutableStateOf(initialPlaceholder) + } + var placeholderResolveAttempted by remember(bitmapStateKey) { + mutableStateOf(initialPlaceholder != null) + } + LaunchedEffect( placeholderMemoryKey, - decryptCacheKey, thumbnailBytes, + publicThumbFilePath, messageId, fileIndex, cacheClientId, - diskCacheUri, - displayLocalUri, ) { - value = DecryptedImageCache.decodePlaceholderThumb( - memoryKey = placeholderMemoryKey, - messageId = messageId, - fileIndex = fileIndex, - clientMessageId = cacheClientId, - serverThumbBytes = thumbnailBytes, - ) ?: initialPlaceholder + if (placeholderBitmap != null) { + placeholderResolveAttempted = true + return@LaunchedEffect + } + val decoded = withContext(Dispatchers.Default) { + DecryptedImageCache.decodePlaceholderThumb( + memoryKey = placeholderMemoryKey, + messageId = messageId, + fileIndex = fileIndex, + clientMessageId = cacheClientId, + serverThumbBytes = thumbnailBytes, + publicNormalFilePath = publicThumbFilePath, + ) + } + if (decoded != null) { + placeholderBitmap = decoded + } + placeholderResolveAttempted = true } val hasFullPreview = fullBitmap != null val hasPlaceholder = placeholderBitmap != null var decryptFinished by remember(bitmapStateKey) { mutableStateOf(fullBitmap != null || placeholderBitmap != null) } - val tileVisual = when { - fullBitmap != null -> AttachmentTileVisual.Full - placeholderBitmap != null -> AttachmentTileVisual.Thumb - else -> AttachmentTileVisual.Empty - } val showOutboundBlurOverlay = (isOutboundPending || isUploading || awaitingServerAck) && (hasLocalSource || hasFullPreview || hasPlaceholder) val treatAsOutbound = isOutboundPending || isUploading || awaitingServerAck @@ -479,6 +494,19 @@ private fun ChatImageTileContent( "target" to "${decodeTarget.widthPx}x${decodeTarget.heightPx}", ) + if (placeholderBitmap == null && !isOutboundPending && !isUploading && !awaitingServerAck) { + withContext(Dispatchers.Default) { + DecryptedImageCache.decodePlaceholderThumb( + memoryKey = placeholderMemoryKey, + messageId = messageId, + fileIndex = fileIndex, + clientMessageId = cacheClientId, + serverThumbBytes = thumbnailBytes, + publicNormalFilePath = publicThumbFilePath, + ) + }?.let { placeholderBitmap = it } + } + fun acceptFull(bitmap: ImageBitmap, path: String?) { fullBitmap = bitmap if (path != null) cachedPath = path @@ -726,18 +754,22 @@ private fun ChatImageTileContent( val isDownloadingFullImage = !treatAsOutbound && fullBitmap == null && (downloadProgress != null || isAwaitingNetworkFull) && !suppressNetworkChrome val showDownloadProgressOverlay = isDownloadingFullImage && !showOutboundBlurOverlay && - !downloadCancelled && !hasLocalSource && placeholderBitmap == null + !downloadCancelled && !hasLocalSource && + placeholderResolveAttempted && placeholderBitmap == null val showDownloadCancelledOverlay = downloadCancelled && fullBitmap == null && !treatAsOutbound && !suppressNetworkChrome val showLoadFailedOverlay = decryptFailed && fullBitmap == null && !treatAsOutbound && !downloadCancelled && !suppressNetworkChrome - val showSpinnerOnly = fullBitmap == null && placeholderBitmap == null && !hasLocalSource && + val showSpinnerOnly = treatAsOutbound && + fullBitmap == null && + placeholderBitmap == null && + !hasLocalSource && !suppressNetworkChrome && !showLoadFailedOverlay && !showOutboundBlurOverlay && !showDownloadProgressOverlay && !showDownloadCancelledOverlay && - (!decryptFinished && !treatAsOutbound) + !decryptFinished Box( modifier = Modifier @@ -755,68 +787,57 @@ private fun ChatImageTileContent( ) { when { else -> { - AnimatedContent( - targetState = tileVisual, - modifier = Modifier.fillMaxSize(), - transitionSpec = { - fadeIn(tween(BLUR_FADE_MS, easing = FastOutSlowInEasing)) - .togetherWith(fadeOut(tween(BLUR_FADE_MS, easing = FastOutSlowInEasing))) - }, - label = "attachment_tile_image", - ) { visual -> - when (visual) { - AttachmentTileVisual.Empty -> { - Box( + Box(modifier = Modifier.fillMaxSize()) { + if (fullBitmap == null) { + Box( + modifier = Modifier + .fillMaxSize() + .background(tilePlaceholderColor), + ) + } + if (fullBitmap == null) { + placeholderBitmap?.let { thumb -> + val blurWhileLoadingFull = isDownloadingFullImage || isAwaitingNetworkFull + CachedAttachmentImage( + bitmap = thumb, + contentDescription = serverFile?.name, + contentScale = imageContentScale, modifier = Modifier .fillMaxSize() - .background(tilePlaceholderColor), + .then( + if (blurWhileLoadingFull) { + Modifier.hazeSource(thumbHazeState) + } else { + Modifier + }, + ), ) - } - AttachmentTileVisual.Thumb -> { - placeholderBitmap?.let { thumb -> - Box(modifier = Modifier.fillMaxSize()) { - CachedAttachmentImage( - bitmap = thumb, - contentDescription = serverFile?.name, - contentScale = imageContentScale, - modifier = Modifier - .fillMaxSize() - .hazeSource(thumbHazeState), - ) - Box( - modifier = Modifier - .fillMaxSize() - .hazeBlur( - input = HazeInput.Backdrop(thumbHazeState), - style = thumbOverlayHazeStyle, - ), - ) - } - } - } - AttachmentTileVisual.Full -> { - fullBitmap?.let { full -> - CachedAttachmentImage( - bitmap = full, - contentDescription = serverFile?.name, - contentScale = imageContentScale, - modifier = Modifier.fillMaxSize(), + if (blurWhileLoadingFull) { + Box( + modifier = Modifier + .fillMaxSize() + .hazeBlur( + input = HazeInput.Backdrop(thumbHazeState), + style = thumbOverlayHazeStyle, + ), ) - LaunchedEffect(full) { onFullyLoaded(true) } } } } + fullBitmap?.let { full -> + CachedAttachmentImage( + bitmap = full, + contentDescription = serverFile?.name, + contentScale = imageContentScale, + modifier = Modifier.fillMaxSize(), + ) + LaunchedEffect(full) { onFullyLoaded(true) } + } } AnimatedVisibility( visible = showDownloadProgressOverlay, - enter = scaleIn( - initialScale = 0.82f, - animationSpec = tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing), - ) + fadeIn(tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing)), - exit = scaleOut( - targetScale = 0.82f, - animationSpec = tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing), - ) + fadeOut(tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing)), + enter = fadeIn(tween(TILE_OVERLAY_FADE_MS, easing = FastOutSlowInEasing)), + exit = fadeOut(tween(TILE_OVERLAY_FADE_MS, easing = FastOutSlowInEasing)), ) { Box( modifier = Modifier @@ -843,14 +864,8 @@ private fun ChatImageTileContent( } AnimatedVisibility( visible = showDownloadCancelledOverlay, - enter = scaleIn( - initialScale = 0.82f, - animationSpec = tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing), - ) + fadeIn(tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing)), - exit = scaleOut( - targetScale = 0.82f, - animationSpec = tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing), - ) + fadeOut(tween(AttachmentLeadingTransitionMs, easing = FastOutSlowInEasing)), + enter = fadeIn(tween(TILE_OVERLAY_FADE_MS, easing = FastOutSlowInEasing)), + exit = fadeOut(tween(TILE_OVERLAY_FADE_MS, easing = FastOutSlowInEasing)), ) { DownloadCancelledImageOverlay( isAuthor = isAuthor, @@ -879,6 +894,7 @@ private fun ChatImageTileContent( ApiClient.clearPartialEncryptedDownload(decryptCacheKey) loadAttempt++ }, + obscureContent = placeholderBitmap == null, modifier = Modifier.matchParentSize(), ) } @@ -1214,6 +1230,7 @@ private fun AttachmentUploadFailedOverlay( private fun AttachmentImageLoadFailedOverlay( isAuthor: Boolean, onRetry: () -> Unit, + obscureContent: Boolean = true, modifier: Modifier = Modifier, ) { val retryCd = stringResource(Res.string.cd_attachment_retry) @@ -1225,8 +1242,13 @@ private fun AttachmentImageLoadFailedOverlay( scheme.surfaceVariant } val iconTint = messageBubbleContentColor(isAuthor) + val overlayBackground = if (obscureContent) { + background + } else { + scheme.scrim.copy(alpha = 0.42f) + } Box( - modifier = modifier.background(background), + modifier = modifier.background(overlayBackground), contentAlignment = Alignment.Center, ) { Icon( diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/ChatScreen.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/ChatScreen.kt index 3aa635b..1a1192b 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/ChatScreen.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/ChatScreen.kt @@ -758,6 +758,51 @@ fun ChatScreen( } } + LaunchedEffect(panel, panelId) { + var lastRequestedOldestId = -1 + snapshotFlow { + OlderHistoryPaginationSnapshot( + shouldLoad = listState.shouldLoadOlderChatHistory(), + hasMore = panel.getState().hasMoreMessages, + loading = panel.getState().isLoadingMore, + oldestId = panel.getState().messages.firstOrNull { it.id > 0 }?.id ?: -1, + messageCount = panel.getState().messages.size, + ) + }.collect { snap -> + if (!snap.shouldLoad || !snap.hasMore || snap.loading || snap.messageCount == 0) return@collect + if (snap.oldestId <= 0 || snap.oldestId == lastRequestedOldestId) return@collect + + lastRequestedOldestId = snap.oldestId + val anchorIndex = listState.firstVisibleItemIndex + val anchorOffset = listState.firstVisibleItemScrollOffset + val lazyItemsBefore = listState.layoutInfo.totalItemsCount + val messagesBefore = snap.messageCount + + panel.loadMoreMessages() + while (panel.getState().isLoadingMore) { + withFrameNanos { } + } + + if (panel.getState().messages.size <= messagesBefore) { + lastRequestedOldestId = -1 + return@collect + } + + runCatching { + snapshotFlow { listState.layoutInfo.totalItemsCount } + .first { it > lazyItemsBefore } + }.onSuccess { + val added = it - lazyItemsBefore + if (added > 0) { + listState.scrollToItem( + (anchorIndex + added).coerceAtMost(listState.layoutInfo.totalItemsCount - 1), + anchorOffset, + ) + } + } + } + } + val clipboard = supportClipboardManagerImpl LaunchedEffect(contextMenuState.isOpen, contextMenuState.message, panelState.messages, currentUserId, isReadOnly) { @@ -1410,6 +1455,19 @@ fun ChatScreen( item { Spacer(modifier.height(floatingHeaderClearance)) } } + if (panelState.isLoadingMore) { + Box( + modifier = Modifier + .align(Alignment.TopCenter) + .padding(top = floatingHeaderClearance + 8.dp), + ) { + ExpressiveUploadIndicator( + uploadProgress = null, + modifier = Modifier.size(32.dp), + ) + } + } + val showScrollToBottomFab = !isNearBottom && panelState.messages.isNotEmpty() && !contextMenuState.isOpen @@ -1716,6 +1774,14 @@ private fun ChatDateSeparator( } } +private data class OlderHistoryPaginationSnapshot( + val shouldLoad: Boolean, + val hasMore: Boolean, + val loading: Boolean, + val oldestId: Int, + val messageCount: Int, +) + private val ChatScrollToBottomButtonSize = 44.dp private val ChatScrollToBottomIconSize = 24.dp diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/MessageListUi.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/MessageListUi.kt index 7faeaf8..44f6a3c 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/MessageListUi.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/MessageListUi.kt @@ -256,6 +256,35 @@ fun LazyListState.isChatNearBottom(threshold: Int = 2): Boolean { return firstVisibleItemIndex <= threshold } +/** Lazy indices from the top spacer through the oldest rows (visual top of reversed chat). */ +const val CHAT_OLDER_HISTORY_PREFETCH_THRESHOLD = 14 + +/** Whether the user has scrolled up near the oldest messages (visual top of the chat). */ +fun LazyListState.isChatNearOldest(threshold: Int = CHAT_OLDER_HISTORY_PREFETCH_THRESHOLD): Boolean = + shouldLoadOlderChatHistory(threshold) + +/** + * True when any visible row is within [threshold] of the oldest lazy index. + * More reliable than only checking the last visible index during flings. + */ +fun LazyListState.shouldLoadOlderChatHistory(threshold: Int = CHAT_OLDER_HISTORY_PREFETCH_THRESHOLD): Boolean { + val total = layoutInfo.totalItemsCount + if (total <= 1) return false + val visible = layoutInfo.visibleItemsInfo + if (visible.isEmpty()) return false + val triggerIndex = (total - 1 - threshold).coerceAtLeast(1) + return visible.any { it.index >= triggerIndex } +} + +fun LazyListState.topmostVisibleLazyIndex(): Int? = + layoutInfo.visibleItemsInfo.maxOfOrNull { it.index } + +fun messageIdAtLazyListIndex(listItems: List, lazyIndex: Int): Int? { + if (lazyIndex <= 0) return null + val item = listItems.getOrNull(lazyIndex - 1) ?: return null + return (item as? ChatListItem.MessageRow)?.message?.id +} + /** Scrolls a reversed chat list to the visual bottom (newest messages). */ suspend fun LazyListState.scrollChatToBottom() { if (layoutInfo.totalItemsCount == 0) return diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/panels/publicchat/PublicChatPanel.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/panels/publicchat/PublicChatPanel.kt index 0f29fc8..6a929bd 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/panels/publicchat/PublicChatPanel.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/panels/publicchat/PublicChatPanel.kt @@ -25,6 +25,7 @@ import ru.fromchat.api.local.download.AttachmentDownloadProgress import ru.fromchat.api.local.send.OutgoingMessageCoordinator import ru.fromchat.api.schema.chats.publicchat.PublicChatProfile import ru.fromchat.api.schema.messages.Message +import ru.fromchat.api.schema.messages.hasMoreOlderHistory import ru.fromchat.api.schema.messages.publicchat.SendMessageResponse import ru.fromchat.api.schema.messages.publicchat.resolvePublicAttachmentLayout import ru.fromchat.api.schema.websocket.WebSocketMessage @@ -41,6 +42,8 @@ import ru.fromchat.ui.chat.utils.mergeDatabaseMessagesWithPanelState import ru.fromchat.ui.chat.utils.mergeMessageUiFields import ru.fromchat.ui.chat.utils.preserveReplyToFromExisting +private const val PUBLIC_CHAT_PAGE_SIZE = 50 + class PublicChatPanel( /** Stable cache / panel id (not localized; hardcoded in [ru.fromchat.ui.chat.utils.PublicChatPanelCache]). */ panelKey: String, @@ -409,7 +412,7 @@ class PublicChatPanel( "loadMessages: network refresh cachedCount=${cached.size}", ) val responseResult = withContext(Dispatchers.Default) { - runCatching { ApiClient.getMessages(limit = 50) } + runCatching { ApiClient.getMessages(limit = PUBLIC_CHAT_PAGE_SIZE) } } val response = responseResult.getOrNull() @@ -437,7 +440,7 @@ class PublicChatPanel( if (withSenders != shown) { updateState { it.copy(messages = sortMessagesForChatDisplay(withSenders)) } } - if (_state.hasMoreMessages) setHasMoreMessages(false) + setHasMoreMessages(response.hasMoreOlderHistory(PUBLIC_CHAT_PAGE_SIZE)) if (_state.isLoading) setLoading(false) mergedForCache = mergeNetworkHistoryWithShown(shown, networkMessages) } else { @@ -456,7 +459,7 @@ class PublicChatPanel( "restoring optimistic count=${optimisticSnapshot.size}", ) restorePendingOptimisticMessages(optimisticSnapshot) - setHasMoreMessages(false) // TODO: Implement has_more from API + setHasMoreMessages(response.hasMoreOlderHistory(PUBLIC_CHAT_PAGE_SIZE)) setLoading(false) mergedForCache = mergeNetworkHistoryWithShown( panelMessagesForDbMerge(), @@ -513,26 +516,34 @@ class PublicChatPanel( val messages = _state.messages if (messages.isEmpty()) return - val oldestMessage = messages.first() + val oldestMessage = messages.firstOrNull { it.id > 0 } ?: return setLoadingMore(true) try { val response = withContext(Dispatchers.Default) { - ApiClient.getMessages(limit = 50, beforeId = oldestMessage.id) + ApiClient.getMessages(limit = PUBLIC_CHAT_PAGE_SIZE, beforeId = oldestMessage.id) } if (response.messages.isNotEmpty()) { val olderRaw = response.messages.map { it.resolvePublicAttachmentLayout() } ProfileCache.mergePreviewFromPublicMessages(olderRaw) val older = ProfileCache.enrichPublicMessagesForDisplay(olderRaw.reversed()) - updateState { currentState -> - currentState.copy( - messages = older + currentState.messages - ) - } - withContext(Dispatchers.Default) { - MessageCacheStore.replacePublicMessages(_state.messages, replaceAll = true) + val existingIds = _state.messages.map { it.id }.toSet() + val newOlder = older.filter { it.id > 0 && it.id !in existingIds } + if (newOlder.isNotEmpty()) { + updateState { currentState -> + currentState.copy( + messages = newOlder + currentState.messages, + ) + } + withContext(Dispatchers.Default) { + MessageCacheStore.replacePublicMessages(_state.messages, replaceAll = true) + } + setHasMoreMessages(response.hasMoreOlderHistory(PUBLIC_CHAT_PAGE_SIZE)) + } else { + setHasMoreMessages(false) } + } else { + setHasMoreMessages(false) } - setHasMoreMessages(false) // TODO: Implement has_more from API } catch (_: Exception) { // Handle error } finally { diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/utils/MessageUiMerge.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/utils/MessageUiMerge.kt index 03ac087..26ed0cc 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/utils/MessageUiMerge.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/chat/utils/MessageUiMerge.kt @@ -158,7 +158,7 @@ internal fun mergeMessageUiFields(db: Message, panel: Message?): Message { uploadError = if (confirmed) null else panel.uploadError ?: db.uploadError, files = db.files ?: panel.files, dmEnvelope = db.dmEnvelope ?: panel.dmEnvelope, - fileThumbnails = db.fileThumbnails ?: panel.fileThumbnails, + fileThumbnails = preferNonEmptyThumbnails(db.fileThumbnails, panel.fileThumbnails), fileAspectRatioPairs = db.fileAspectRatioPairs ?: panel.fileAspectRatioPairs, fileAspectRatios = when { confirmed && dbHasRealLayout -> db.fileAspectRatios ?: panel.fileAspectRatios @@ -190,6 +190,19 @@ internal fun mergeMessageUiFields(db: Message, panel: Message?): Message { } } +private fun hasNonBlankThumbnail(list: List?): Boolean = + list?.any { it.isNotBlank() } == true + +/** Prefer API thumbs over cached `[""]` rows from an older persist. */ +internal fun preferNonEmptyThumbnails( + db: List?, + panel: List?, +): List? = when { + hasNonBlankThumbnail(panel) -> panel + hasNonBlankThumbnail(db) -> db + else -> panel ?: db +} + /** Keeps hydrated [Message.reply_to] when a network/DB refresh omits nested reply payloads. */ internal fun preserveReplyToFromExisting( existing: List, diff --git a/app/shared/src/iosMain/kotlin/ru/fromchat/ui/Theme.ios.kt b/app/shared/src/iosMain/kotlin/ru/fromchat/ui/Theme.ios.kt index 9da7155..7a867a9 100644 --- a/app/shared/src/iosMain/kotlin/ru/fromchat/ui/Theme.ios.kt +++ b/app/shared/src/iosMain/kotlin/ru/fromchat/ui/Theme.ios.kt @@ -1,5 +1,6 @@ package ru.fromchat.ui +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable @@ -9,5 +10,8 @@ import androidx.compose.ui.graphics.Color actual fun getColorScheme(darkTheme: Boolean, dynamicColor: Boolean) = if (darkTheme) darkColorScheme() else lightColorScheme() +@Composable +actual fun rememberPlatformSystemDarkTheme(): Boolean = isSystemInDarkTheme() + @Composable actual fun ApplySystemBarTheme(darkTheme: Boolean, surfaceColor: Color) = Unit diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/api/local/download/LocalDecodedImageCache.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/api/local/download/LocalDecodedImageCache.jvm.kt index 3d75963..a4d758a 100644 --- a/app/shared/src/jvmMain/kotlin/ru/fromchat/api/local/download/LocalDecodedImageCache.jvm.kt +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/api/local/download/LocalDecodedImageCache.jvm.kt @@ -2,11 +2,14 @@ package ru.fromchat.api.local.download import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.toComposeImageBitmap +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import javax.imageio.ImageIO import org.jetbrains.skia.Bitmap import org.jetbrains.skia.Image import org.jetbrains.skia.ImageInfo import org.jetbrains.skia.SamplingMode -import java.io.File actual object PlatformDecodedBitmapCache { private val cache = mutableMapOf() @@ -32,11 +35,47 @@ actual fun decodeLocalImageFile(absolutePath: String, reqWidthPx: Int, reqHeight } actual fun decodeImageBytes(bytes: ByteArray, reqWidthPx: Int, reqHeightPx: Int): ImageBitmap? = + decodeWithSkia(bytes, reqWidthPx, reqHeightPx) ?: decodeWithImageIo(bytes, reqWidthPx, reqHeightPx) + +private fun decodeWithSkia(bytes: ByteArray, reqWidthPx: Int, reqHeightPx: Int): ImageBitmap? = runCatching { val image = Image.makeFromEncoded(bytes) scaleSkiaImageToFitWithin(image, reqWidthPx, reqHeightPx) }.getOrNull() +private fun decodeWithImageIo(bytes: ByteArray, reqWidthPx: Int, reqHeightPx: Int): ImageBitmap? = + runCatching { + val source = ImageIO.read(ByteArrayInputStream(bytes)) ?: return@runCatching null + val scaled = scaleBufferedImageToFitWithin(source, reqWidthPx, reqHeightPx) + val out = ByteArrayOutputStream() + ImageIO.write(scaled, "png", out) + val image = Image.makeFromEncoded(out.toByteArray()) + image.toComposeImageBitmap() + }.getOrNull() + +private fun scaleBufferedImageToFitWithin( + source: java.awt.image.BufferedImage, + reqWidthPx: Int, + reqHeightPx: Int, +): java.awt.image.BufferedImage { + if (source.width <= reqWidthPx && source.height <= reqHeightPx) return source + val scale = minOf( + reqWidthPx.toFloat() / source.width.toFloat(), + reqHeightPx.toFloat() / source.height.toFloat(), + ) + if (scale >= 1f) return source + val dstW = (source.width * scale).toInt().coerceAtLeast(1) + val dstH = (source.height * scale).toInt().coerceAtLeast(1) + val scaled = java.awt.Image.SCALE_SMOOTH.let { hint -> + source.getScaledInstance(dstW, dstH, hint) + } + val buffered = java.awt.image.BufferedImage(dstW, dstH, java.awt.image.BufferedImage.TYPE_INT_ARGB) + val graphics = buffered.createGraphics() + graphics.drawImage(scaled, 0, 0, null) + graphics.dispose() + return buffered +} + private fun scaleSkiaImageToFitWithin(image: Image, reqWidthPx: Int, reqHeightPx: Int): ImageBitmap { if (image.width <= reqWidthPx && image.height <= reqHeightPx) return image.toComposeImageBitmap() val scale = minOf( diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/ui/PlatformSystemTheme.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/ui/PlatformSystemTheme.jvm.kt new file mode 100644 index 0000000..15b88a3 --- /dev/null +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/ui/PlatformSystemTheme.jvm.kt @@ -0,0 +1,135 @@ +package ru.fromchat.ui + +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import kotlin.time.Duration.Companion.seconds + +/** Desktop JVM: GNOME/KDE/portal, Windows registry, macOS defaults. */ +fun jvmPlatformSystemDarkTheme(): Boolean = runCatching { + val os = System.getProperty("os.name").orEmpty().lowercase() + when { + os.contains("mac") -> + ProcessBuilder("defaults", "read", "-g", "AppleInterfaceStyle") + .redirectErrorStream(true) + .start() + .inputStream + .bufferedReader() + .readText() + .trim() + .equals("Dark", ignoreCase = true) + os.contains("win") -> readWindowsAppsDarkTheme() + os.contains("linux") -> readLinuxAppsDarkTheme() + else -> false + } +}.getOrDefault(false) + +private fun readLinuxAppsDarkTheme(): Boolean { + readGsettingsValue("org.gnome.desktop.interface", "color-scheme")?.let { scheme -> + when { + scheme.contains("dark", ignoreCase = true) -> return true + scheme.contains("light", ignoreCase = true) -> return false + } + } + readGsettingsValue("org.gnome.desktop.interface", "gtk-theme")?.let { theme -> + if (theme.contains("dark", ignoreCase = true)) return true + if (theme.contains("light", ignoreCase = true)) return false + } + readPortalColorScheme()?.let { value -> + return when (value) { + 1 -> true + 2 -> false + else -> false + } + } + readKdeColorScheme()?.let { scheme -> + if (scheme.contains("dark", ignoreCase = true)) return true + } + return false +} + +private fun readGsettingsValue(schema: String, key: String): String? { + val process = ProcessBuilder("gsettings", "get", schema, key) + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().readText().trim() + process.waitFor() + if (process.exitValue() != 0 || output.isEmpty() || output == "@as []") return null + return output.trim('"') +} + +private fun readPortalColorScheme(): Int? = runCatching { + val process = ProcessBuilder( + "gdbus", + "call", + "--session", + "--dest", + "org.freedesktop.portal.Desktop", + "--object-path", + "/org/freedesktop/portal/desktop", + "--method", + "org.freedesktop.portal.Settings.Read", + "org.freedesktop.appearance", + "color-scheme", + ) + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().readText() + process.waitFor() + if (process.exitValue() != 0) return null + Regex("""\(\s*<(\d+)>\s*,\s*""").find(output)?.groupValues?.getOrNull(1)?.toIntOrNull() +}.getOrNull() + +private fun readKdeColorScheme(): String? = runCatching { + val process = ProcessBuilder( + "kreadconfig6", + "--file", + "kdeglobals", + "--group", + "General", + "--key", + "ColorScheme", + ) + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().readText().trim() + process.waitFor() + if (process.exitValue() != 0 || output.isEmpty()) null else output +}.getOrNull() + +private fun readWindowsAppsDarkTheme(): Boolean { + val process = ProcessBuilder( + "reg", + "query", + "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", + "/v", + "AppsUseLightTheme", + ) + .redirectErrorStream(true) + .start() + val output = process.inputStream.bufferedReader().readText() + process.waitFor() + return when { + "0x0" in output -> true + "0x1" in output -> false + else -> false + } +} + +@Composable +actual fun rememberPlatformSystemDarkTheme(): Boolean { + var dark by remember { mutableStateOf(jvmPlatformSystemDarkTheme()) } + LaunchedEffect(Unit) { + while (isActive) { + val next = jvmPlatformSystemDarkTheme() + if (next != dark) dark = next + delay(2.seconds) + } + } + return dark +} diff --git a/build.gradle.kts b/build.gradle.kts index 8e5f80e..b788143 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -28,4 +28,58 @@ buildscript { dependencies { classpath(libs.google.services) } +} + +/** + * Packaging jobs restore JVM outputs from the Linux Build JAR artifact. Gradle has no local + * execution history for those outputs on macOS/Windows, so it would re-run compileKotlinJvm unless + * we skip it when the restored tree is already present. + */ +fun Project.useCiPrebuiltJvm(): Boolean = + providers.environmentVariable("FROMCHAT_PREBUILT_JVM").orNull == "1" + +fun Project.hasFilesUnder(relativeDir: String, extension: String): Boolean { + val root = layout.buildDirectory.dir(relativeDir).get().asFile + return root.isDirectory && root.walk().any { it.isFile && it.extension == extension } +} + +subprojects { + afterEvaluate { + if (!useCiPrebuiltJvm()) return@afterEvaluate + when (path) { + ":app:shared", ":utils:shared" -> { + tasks.matching { it.name == "compileKotlinJvm" }.configureEach { + onlyIf { + val skip = hasFilesUnder("classes/kotlin/jvm/main", "class") + if (skip) { + logger.lifecycle("$path compileKotlinJvm skipped — CI prebuilt JVM classes") + } + !skip + } + } + } + ":app:desktop" -> { + tasks.matching { it.name == "compileKotlin" }.configureEach { + onlyIf { + val skip = hasFilesUnder("classes/kotlin/main", "class") + if (skip) { + logger.lifecycle("$path compileKotlin skipped — CI prebuilt JVM classes") + } + !skip + } + } + } + } + if (path == ":app:shared") { + tasks.named("generateAppBuildInfo").configure { + onlyIf { + val skip = hasFilesUnder("generated/sources/appBuildInfo/kotlin", "kt") + if (skip) { + logger.lifecycle("generateAppBuildInfo skipped — CI prebuilt output") + } + !skip + } + } + } + } } \ No newline at end of file