202 Commits

807 changed files with 92353 additions and 3509 deletions
+5
View File
@@ -0,0 +1,5 @@
{
"name": "FromChat",
"user": "ubuntu",
"install": "bash .cursor/scripts/cloud-setup.sh"
}
+79
View File
@@ -0,0 +1,79 @@
---
description: Android/KMP workspace rules (single concise source of truth)
alwaysApply: true
---
# Android / KMP rules
## Project context (quick)
- This is a **messaging app**.
- The Kotlin Multiplatform shared code lives under:
- `app/shared/src/commonMain/kotlin/` (cross-platform logic + Compose UI)
- `app/shared/src/androidMain/kotlin/` (Android-specific implementations)
- `app/shared/src/iosMain/kotlin/` (iOS-specific implementations, when present)
- Android app module: `app/android/`
- Shared UI strings (Compose resources):
- `app/shared/src/commonMain/composeResources/values/strings.xml`
- `app/shared/src/commonMain/composeResources/values-ru/strings.xml`
## Build / validation (required before finishing)
- After changes, run this command (and fix all errors):
- `export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" && ./gradlew :app:shared:compileAndroidMain :app:shared:compileKotlinIosArm64`
- If it fails, investigate and try to fix the issue yourself (dont stop at reporting the failure).
## After Android-affecting changes: build + run on device (Mobile MCP)
If you changed anything under `app:android`, `app:shared` (`commonMain` / `androidMain`), or `utils:shared` that affects Android:
- **Build** debug APK: `./gradlew :app:android:assembleDebug` (artifact: `app/android/build/outputs/apk/debug/android-debug.apk`).
- **Install + launch via Cursor Mobile MCP** (configured name **`Mobile MCP`** in `mcp.json`; in Agent MCP tool calls the server id is often **`user-Mobile MCP`**—use whatever id your session lists for `@mobilenext/mobile-mcp`). **Read each tools schema**, then:
1. **`mobile_list_available_devices`** — pick the target **Android** `device` id(s) (prefer a **physical** device when validating UI; use an emulator when the task needs it or no phone is listed).
2. **`mobile_install_app`** — `device`, `path` = **absolute** path to `android-debug.apk` under the repo (e.g. `<workspace>/app/android/build/outputs/apk/debug/android-debug.apk`).
3. **`mobile_launch_app`** — `device`, `packageName` = **`ru.fromchat.beta`** (debug application id; not `ru.fromchat`).
- Smoke-test the affected flows after launch.
- If **`mobile_install_app`** fails on an **emulator** with insufficient storage, use **“Android emulator storage”** (below), then retry.
- Use raw **`adb install` / `am start`** only if Mobile MCP is unavailable after checking MCP status—say so in the reply.
## Calls (LiveKit / `Call*`, call UI, foreground call service, call audio/video)
Whenever the task touches **calls** (e.g. `CallMediaLayer`, `CallForegroundService`, LiveKit wiring, in-call UI, mic/camera/screen-share for calls):
- **Build** debug: `./gradlew :app:android:assembleDebug`
- **Install + launch with Mobile MCP** on **every Android target** you will use for validation (same three tools as above: **`mobile_list_available_devices`** → **`mobile_install_app`** (`device` + absolute `path` to `android-debug.apk`) → **`mobile_launch_app`** (`device`, `packageName` = **`ru.fromchat.beta`**)). Use the MCP **server id** your environment exposes (e.g. **`user-Mobile MCP`**). Repeat for **each** Android `device` id (emulator **and** phone when both appear in `mobile_list_available_devices`).
- Do **not** treat the task as finished until this has been run on **both** an **emulator** and a **physical device** whenever both are available (start/boot the missing one, list devices again, then install + launch on each). If install fails on the emulator, follow **“Android emulator storage”** below, then retry install + launch. If it still fails after a real cleanup attempt, report what you tried.
- If only one class of device is listed, deploy to every listed Android device and state clearly what was missing.
## Android emulator storage (no approval needed)
When an **Android emulator** hits **`INSTALL_FAILED_INSUFFICIENT_STORAGE`** or otherwise has too little free space for a debug install, you may **do whatever is needed to free space on that emulator only** without asking the user first: uninstall third-party apps (`adb -s <emu> uninstall …`), clear caches (`adb shell pm trim-caches` / `rm` under emulator-owned paths the shell can reach), delete arbitrary files **inside that AVD**, or **wipe the AVD / `emulator -wipe-data`** if that is the fastest fix. Treat the emulator as disposable dev state.
- **Never** use this “anything goes” approach on a **physical device** (only uninstall/clear what the user explicitly asked for, or use normal Mobile MCP flows).
## Never touch Gradle caches
- Do not read, list, search, copy, or modify anything under Gradle cache paths (e.g. `~/.gradle/caches`, `**/.gradle/caches`).
## No magic-string “sanitization” of real data
- Never strip/null/rewrite stored or displayed values by comparing to hard-coded UI/placeholder strings.
- Fix at the source (dont persist placeholders) or use explicit migrations/sentinels—never natural-language matching.
## UI strings (shared module)
- No hardcoded user-visible copy in shared UI. Use Compose Multiplatform resources:
- `app/shared/src/commonMain/composeResources/values/strings.xml` (default)
- `app/shared/src/commonMain/composeResources/values-ru/strings.xml` (Russian)
- Keep keys in sync across both files.
- Exception: Debug API screen (`ru.fromchat.ui.debug`) may hardcode strings.
## Prefer utils package APIs
Prefer `com.pr0gramm3r101.utils` when available (before custom solutions), especially:
- Clipboard: `supportClipboardManagerImpl` / `SupportClipboardManager.setText`
- Strings: `String.toAnnotatedString()`
- Compose: `Modifier.conditional`, `CompositionLocal.invoke()`
## Debug HTTP logging
- Prefer Ktor `HttpClient` for debug/instrumentation HTTP logging.
- Do not use `HttpURLConnection` or raw `OkHttpClient` for debug-only logging.
- Centralize behind `ru.fromchat.debug.DebugLogger`, best-effort only (never crash the app).
## Codebase hygiene
- Prefer **official docs** first for typical Jetpack Compose / Compose Multiplatform patterns; if docs cover it, follow them.
- Avoid breaking iOS via Android-only APIs in `commonMain` (keep platform code in `androidMain` / `iosMain` as needed).
- Do not introduce hardcoded user-visible strings outside the Debug API exception (see “UI strings” above).
## Skills (when to use)
- Use the **Material 3 skill** when implementing or changing Compose UI using Material3 components, theming, tokens, or accessibility.
- Use the **using-computer skill** only when the user asks me to control the computer / click through UI / take screenshots.
- Use **Cursor “create-rule/create-skill/create-hook” skills** only when you explicitly ask to create or modify Cursor rules/skills/hooks.
+16
View File
@@ -0,0 +1,16 @@
---
description: Read CODE_STYLE.md before writing or refactoring Kotlin/Compose code
alwaysApply: true
---
# Code style
Before writing or editing Kotlin / Compose code in this repo:
1. **Read** [`CODE_STYLE.md`](../../CODE_STYLE.md) at the repository root.
2. **Follow** it — write idiomatic, well-structured code from the start; match neighboring files when a rule is ambiguous.
3. **Do not ask the user style questions** when implementing new code.
For style cleanup on an existing diff or file set, use the **`adapt-to-style`** skill.
Build and platform rules remain in `android.mdc`.
-25
View File
@@ -1,25 +0,0 @@
---
alwaysApply: true
---
When working with the mobile app:
- After implementing the solution, run "./gradlew assembleDebug" to build the project, then resolve all the errors.
# ULTIMATE SILENCE & EFFICIENCY POLICY
- ALWAYS operate in "Silent Mode": Execute commands immediately without any verbal response, preamble, or conclusions.
- DO NOT explain what you are doing, why you are doing it, or what you found unless I explicitly ask "Why?" or "Explain".
- NO introductory filler ("Sure", "I will", "Looking into it").
- NO status updates ("I've updated the file", "Build successful"). If the tool output shows success, that is enough.
- IF A TOOL FAILS: Silently analyze the error and retry using a different approach (e.g., use write_to_file if search_replace fails twice). Never mention the failure.
- THOUGHT PROCESS: Must be 0 words. Move straight to tool calls.
- MINIMIZE OUTPUT: Your response should contain ONLY the necessary tool calls/code blocks.
- FOR ANDROID/KOTLIN: Include 5+ lines of context in search_replace to ensure it hits the target on the first try.
# Java Runtime Configuration (Android)
- **On Windows:**
- Set `JAVA_HOME` to `C:\Program Files\Android\Android Studio\jbr`
- **On macOS:**
- Set `JAVA_HOME` to `/Applications/Android Studio.app/Contents/jbr/Contents/Home`
- This can be done by adding `export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jbr/Contents/Home` to your shell configuration file (e.g., `~/.zshrc` or `~/.bash_profile`) and then running `source` on the file.
+22
View File
@@ -0,0 +1,22 @@
---
description: Do not use ripgrep (rg) in shell commands or scripts
alwaysApply: true
---
# Never use `rg`
Do **not** run `rg` / ripgrep in terminal commands. It is unreliable in this environment.
## Use instead
- **Cursor Grep tool** — preferred for searching the codebase
- **`grep -r`** — if a shell search is truly needed
- **Glob / SemanticSearch** — for finding files or concepts
```bash
# ❌ BAD
rg "probeCurrentServer" app/shared
# ✅ GOOD — use the Grep tool, or:
grep -r "probeCurrentServer" app/shared
```
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env bash
# Cloud Agent install script for the FromChat KMP client.
#
# Idempotent: safe to run repeatedly. Prepares everything needed to build the
# Android app (`:app:android:assembleDebug`) and compile the shared module
# (`:app:shared:compileAndroidMain`) on a headless Linux Cloud Agent VM:
# 1. A JDK 17+ (uses the system JDK; installs OpenJDK 21 only if none is found).
# 2. The Android SDK (command-line tools + required platforms/build-tools).
# 3. Git-ignored local secrets the Gradle build reads at configuration time:
# debug/release keystores, keys/keystore.properties, and a placeholder
# google-services.json (Firebase config; the checked-in build applies the
# google-services plugin). These are throwaway, non-secret dev values.
# 4. local.properties pointing Gradle at the SDK.
#
# iOS targets (compileKotlinIosArm64 etc.) require macOS + Xcode and cannot be
# built on this Linux VM; only the Android/shared-android surface is prepared.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$REPO_ROOT"
log() { printf '\n\033[1;34m[cloud-setup]\033[0m %s\n' "$*"; }
# --- 0. Base prerequisites ---------------------------------------------------
# On the snapshot these already exist; guard for a bare base image.
missing_pkgs=()
for tool in curl unzip git; do
command -v "$tool" >/dev/null 2>&1 || missing_pkgs+=("$tool")
done
command -v java >/dev/null 2>&1 || missing_pkgs+=("openjdk-21-jdk")
if [ "${#missing_pkgs[@]}" -gt 0 ]; then
log "Installing missing base packages: ${missing_pkgs[*]}"
sudo apt-get update -y
sudo apt-get install -y --no-install-recommends "${missing_pkgs[@]}"
fi
# --- 1. Java -----------------------------------------------------------------
JAVA_BIN="$(command -v java)"
JAVA_MAJOR="$(java -version 2>&1 | sed -n 's/.*version "\([0-9]*\).*/\1/p' | head -1)"
log "Using Java: $JAVA_BIN (major ${JAVA_MAJOR:-unknown})"
# --- 2. Android SDK ----------------------------------------------------------
export ANDROID_HOME="${ANDROID_HOME:-$HOME/android-sdk}"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
CMDLINE_TOOLS_ZIP_URL="https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip"
# Package versions must match the compileSdk/build-tools the Gradle build expects.
SDK_PACKAGES=(
"platform-tools"
"platforms;android-37.0"
"platforms;android-36"
"build-tools;37.0.0"
"build-tools;36.0.0"
)
if [ ! -x "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" ]; then
log "Installing Android command-line tools into $ANDROID_HOME"
mkdir -p "$ANDROID_HOME/cmdline-tools"
tmp_zip="$(mktemp --suffix=.zip)"
curl -fsSL -o "$tmp_zip" "$CMDLINE_TOOLS_ZIP_URL"
rm -rf "$ANDROID_HOME/cmdline-tools/latest" "$ANDROID_HOME/cmdline-tools/.tmp-extract"
mkdir -p "$ANDROID_HOME/cmdline-tools/.tmp-extract"
unzip -q "$tmp_zip" -d "$ANDROID_HOME/cmdline-tools/.tmp-extract"
mv "$ANDROID_HOME/cmdline-tools/.tmp-extract/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
rm -rf "$ANDROID_HOME/cmdline-tools/.tmp-extract" "$tmp_zip"
fi
SDKMANAGER="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager"
log "Accepting SDK licenses"
yes | "$SDKMANAGER" --sdk_root="$ANDROID_HOME" --licenses >/dev/null 2>&1 || true
log "Installing SDK packages: ${SDK_PACKAGES[*]}"
"$SDKMANAGER" --sdk_root="$ANDROID_HOME" "${SDK_PACKAGES[@]}" >/dev/null
# --- 3. Local secrets the build reads (git-ignored, throwaway dev values) -----
KEYS_DIR="$REPO_ROOT/app/android/keys"
mkdir -p "$KEYS_DIR"
DEBUG_STORE_PASS="${DEBUG_STORE_PASS:-android}"
DEBUG_KEY_PASS="${DEBUG_KEY_PASS:-android}"
RELEASE_STORE_PASS="${RELEASE_STORE_PASS:-android}"
RELEASE_KEY_PASS="${RELEASE_KEY_PASS:-android}"
# Debug keystore uses alias "debug"; release uses alias "key0" (see app/android/build.gradle.kts).
if [ ! -f "$KEYS_DIR/debug.jks" ]; then
log "Generating debug keystore"
keytool -genkeypair -v -keystore "$KEYS_DIR/debug.jks" \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias debug -storepass "$DEBUG_STORE_PASS" -keypass "$DEBUG_KEY_PASS" \
-dname "CN=Debug, O=FromChat, C=RU"
fi
if [ ! -f "$KEYS_DIR/release.jks" ]; then
log "Generating release keystore"
keytool -genkeypair -v -keystore "$KEYS_DIR/release.jks" \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias key0 -storepass "$RELEASE_STORE_PASS" -keypass "$RELEASE_KEY_PASS" \
-dname "CN=Release, O=FromChat, C=RU"
fi
log "Writing keys/keystore.properties"
cat > "$KEYS_DIR/keystore.properties" <<EOF
releaseStorePassword=$RELEASE_STORE_PASS
releaseKeyPassword=$RELEASE_KEY_PASS
debugStorePassword=$DEBUG_STORE_PASS
debugKeyPassword=$DEBUG_KEY_PASS
EOF
# Placeholder Firebase config so the google-services plugin resolves. Contains no
# real credentials; replace with a genuine google-services.json for push testing.
GSJSON="$REPO_ROOT/app/android/google-services.json"
if [ ! -f "$GSJSON" ]; then
log "Writing placeholder google-services.json"
cat > "$GSJSON" <<'EOF'
{
"project_info": {
"project_number": "000000000000",
"project_id": "fromchat-cloud-agent",
"storage_bucket": "fromchat-cloud-agent.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:000000000000:android:0000000000000000000000",
"android_client_info": { "package_name": "ru.fromchat" }
},
"oauth_client": [],
"api_key": [ { "current_key": "AIzaSyDUMMYDUMMYDUMMYDUMMYDUMMYDUMMY000" } ],
"services": { "appinvite_service": { "other_platform_oauth_client": [] } }
},
{
"client_info": {
"mobilesdk_app_id": "1:000000000000:android:1111111111111111111111",
"android_client_info": { "package_name": "ru.fromchat.beta" }
},
"oauth_client": [],
"api_key": [ { "current_key": "AIzaSyDUMMYDUMMYDUMMYDUMMYDUMMYDUMMY000" } ],
"services": { "appinvite_service": { "other_platform_oauth_client": [] } }
}
],
"configuration_version": "1"
}
EOF
fi
# --- 4. Point Gradle at the SDK ----------------------------------------------
log "Writing local.properties"
printf 'sdk.dir=%s\n' "$ANDROID_HOME" > "$REPO_ROOT/local.properties"
# --- 5. Warm the Gradle cache and validate the Android build -----------------
export JAVA_HOME="${JAVA_HOME:-$(dirname "$(dirname "$(readlink -f "$JAVA_BIN")")")}"
log "Warming Gradle build (assembleDebug + shared androidMain)"
./gradlew --no-daemon :app:shared:compileAndroidMain :app:android:assembleDebug
log "Setup complete. Debug APK:"
ls -lh "$REPO_ROOT/app/android/build/outputs/apk/debug/" || true
+85
View File
@@ -0,0 +1,85 @@
---
name: adapt-to-style
description: Adapts Kotlin/Compose code (diff, single file, or multiple files) to FromChat CODE_STYLE.md strictly without changing behavior. Use when cleaning up style, refactoring for conventions, adapting a diff to code style, or when the user mentions adapt-to-style, code style cleanup, or style pass.
---
# Adapt to style
Refactor target code to match `[CODE_STYLE.md](../../../CODE_STYLE.md)` at the repository root. **Do not change behavior.**
## Writing new code
When implementing features (not a style-only pass):
1. Read `CODE_STYLE.md` before writing.
2. Follow it from the start — inline single-use bindings, idiomatic Kotlin, match neighboring files.
3. **Do not ask the user style questions** — apply the guide and use your judgment.
If the user used this skill in a prompt asking to implement/fix something, you should just adhere to the coding style.
## Style adaptation pass
When cleaning up an existing diff or file set:
### Before you start
1. Read `CODE_STYLE.md` fully.
2. Identify scope: git diff, named files, or a directory.
3. Read surrounding files in the same package for precedent.
### Refactor checklist
Apply in order:
- [ ] **Inline** `val`/`var`/locals/`@Composable` used exactly once in the file (§1).
- [ ] **Merge** screen-only helper files into their parent screen file (§2).
- [ ] **Replace** non-idiomatic Kotlin with idioms: `runCatching {}`, `buildList {}`, `buildMap {}`, etc. (§3).
- [ ] **Group** related multi-file features into sub-packages where appropriate (§4).
- [ ] **Reuse** existing project components; remove one-off wrappers (§5).
- [ ] **Strings** — no new hardcoded user-visible copy; use compose resources (§6).
- [ ] **Formatting** — one blank line between composables; `private` screen helpers; no `.dp` named constants (§7).
- [ ] **Expression bodies** where §8 applies.
### Uncertainty log
Only during a **style adaptation pass** — not when writing new code.
When unsure how to refactor something:
1. Create or append to `.cursor/code_style_progress_<YYYYMMDD-HHmm>.md` (use current local time).
2. For each item:
```markdown
## relative/path/File.kt
- Unsure: [specific construct and why]
- Chosen approach: [what you did for now]
```
3. Continue refactoring — do not block on open questions.
4. After all files are done, **re-read** the progress file and ask the user the listed questions.
### Constraints
- No behavior, API, or logic changes.
- No magic-string sanitization of real user/message data.
- Minimal diff: only what style requires.
- Do not extract new abstractions that would be used once.
- Do not split files that §2 says should be merged.
- Do not change public API for style-only passes.
### Validation
After Android-affecting changes, run per `android.mdc`:
```bash
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" && ./gradlew :app:shared:compileAndroidMain :app:shared:compileKotlinIosArm64
```
Fix compile errors before finishing.
### Output
Summarize:
- Files touched and main style changes.
- Any entries from the progress file that need user decisions.
- Build result.
+44
View File
@@ -0,0 +1,44 @@
---
name: post-complete
description: Build the Android debug APK, reinstall it on all available connected devices (real first, otherwise emulator), and launch the app. Use after a request is completed or when the user asks to verify changes on devices.
---
# Post-Complete
## When to use
Use this skill after a request was completed and the user wants to verify the result on real devices (if available) and emulators.
## Rules
- Do NOT use subagents in this skill.
- If Mobile MCP install fails because the APK file does not exist, investigate the build outputs directory structure, find the correct APK path, update the skill path, and retry.
- Don't ask questions unless you can't complete the task because my attention is needed. If something fails, try to investigate yourself.
## Instructions
1. In parallel:
- Build a fresh Android debug APK:
- Run: `./gradlew app:android:assembleDebug` from the Android project root.
- Do not try to execute this command multiple times or add additional options like `--no-daemon`.
- List available devices:
- Tool: `mobile_list_available_devices`
- Parameters: `{}` (no params)
2. Select the devices to install the app to:
- If at least one device is a physical Android device, install+launch on those devices.
- Otherwise, install+launch on emulators.
- If working with calls, install+launch on at least 2 devices (pick more devices from the available list).
- Do not ask the user to choose devices unless they explicitly say what device to use.
3. In parallel:
- For each chosen device, run `mobile_install_app` with:
- `device`: string (use `id` from `mobile_list_available_devices`)
- `path`: string (`app/android/build/outputs/apk/debug/android-debug.apk` converted to absolute path)
- `package`: string (`ru.fromchat.beta`)
- For each chosen device, run `mobile_launch_app` with:
- `device`: string (use `id` from `mobile_list_available_devices`)
- `packageName`: string (`ru.fromchat.beta`)
- Use exactly ONE parallel tool execution batch for everything:
- include every `mobile_install_app` call for every chosen device
- include every `mobile_launch_app` call for every chosen device
- Do NOT split into multiple parallel batches and do NOT run installs/launches in separate tool batches.
4. Completion:
- Only after every chosen device has successful results for ALL tool calls the agent should tell the user the task is completed.
- If any device fails any tool call, investigate and try again until they succeed.
+220
View File
@@ -0,0 +1,220 @@
---
name: premortem
description: "Run a premortem on any plan, launch, product, hire, strategy, or decision. Assumes it already failed 6 months from now and works backward to find every reason why. Produces a revised plan with blind spots exposed. MANDATORY TRIGGERS: 'premortem this', 'premortem my', 'run a premortem', 'what could kill this', 'future-proof this', 'stress test this plan', 'what am i missing here', 'find the blind spots'. STRONG TRIGGERS: 'what could go wrong', 'am i missing anything', 'poke holes in this', 'where will this break', 'devil's advocate this'. Do NOT trigger on simple feedback requests, factual questions, or LLM Council requests. DO trigger when someone has a plan or commitment where the cost of being wrong is high."
---
# Premortem
A premortem is the opposite of a postmortem. Instead of figuring out what went wrong after something fails, you imagine it already failed and figure out why before you start.
The method comes from psychologist Gary Klein. He published it in Harvard Business Review. Daniel Kahneman (the Nobel Prize-winning psychologist behind "Thinking, Fast and Slow") called it his single most valuable decision-making technique. Google, Goldman Sachs, and Procter & Gamble all use it before major decisions.
The core insight: when you ask people "what could go wrong?" they give you cautious, hedged answers. When you say "this already failed, tell me why," their brains switch into narrative mode and generate way more specific, creative, honest reasons. Researchers at Wharton and Cornell called this "prospective hindsight" and found it significantly increases the ability to identify causes of future outcomes.
The reason this matters for AI-assisted decisions: Claude defaults to agreeable, optimistic responses. If you ask "is this a good plan?" it will find reasons to say yes. The premortem breaks this pattern by forcing the frame into "this is dead, explain how it died." Claude stops looking for reasons your plan will work and starts explaining how it fell apart.
---
## when to run a premortem
Good premortem targets:
- A product or feature you're about to build
- A launch plan with money or reputation on the line
- A pricing change or business model shift
- A hire you're about to make
- A strategy or positioning pivot
- A partnership or deal you're evaluating
- Any commitment where the cost of being wrong is high
Bad premortem targets:
- Vague ideas with no concrete plan yet (help them plan first, then premortem)
- Questions with one right answer (just answer them)
- Requests for creative feedback on a draft (that's editing, not a premortem)
- Decisions that are already made and irreversible (a premortem is only useful when you can still change course)
---
## context gathering (the minimum bar)
A premortem is only as good as the context it runs on. Vague input produces vague failure scenarios that help nobody. Before running the premortem, you need to hit a minimum context threshold.
### step 1: scan for existing context
Before asking the user anything, look for context that's already available:
**A. The current conversation.** The user may have been discussing a plan, a launch, a product, or a decision earlier in this session. Read back through the conversation and extract whatever's relevant.
**B. The workspace.** Quickly scan for files that might contain relevant context:
- `CLAUDE.md` or `claude.md` (business context, preferences, constraints)
- Any `memory/` folder (audience profiles, business details, past decisions)
- Files the user explicitly referenced or attached
- Any project files, briefs, or plans that relate to the thing being premortemed
Use `Glob` and quick `Read` calls. Don't spend more than 30 seconds on this. You're looking for the key files that would ground the failure scenarios in reality.
### step 2: evaluate context sufficiency
After scanning, check whether you have enough to run a useful premortem. You need three things:
1. **What is it?** — A clear understanding of the thing being premortemed (a product, a launch, a hire, a pricing change, a strategy). You need to be able to describe it back to the user in one sentence.
2. **Who is it for / who does it affect?** — The audience, the customer, the team, the stakeholders. Failure scenarios depend heavily on who's involved.
3. **What does success look like?** — What outcome is the user hoping for? Failure is defined by inverting success. If you don't know what success means, you can't define what failure means.
### step 3: fill gaps conversationally
If you have all three, proceed immediately to the premortem. Don't ask unnecessary questions.
If you're missing one or more, ask for the most important missing piece first. One question at a time. Evaluate after each answer whether you now have enough. Keep asking until the threshold is met, but never ask more than you need.
Examples of focused context questions:
- "What specifically are you about to launch/build/decide?" (if you don't know what it is)
- "Who is this for?" (if you know the plan but not the audience)
- "What does a win look like for this?" (if you know the plan and audience but not the success criteria)
The goal is to reach the minimum bar as fast as possible without making the user feel like they're filling out a form. Conversational, not interrogative. If you can infer an answer from context, do that instead of asking.
---
## how a premortem session works
### step 1: set the frame
After gathering sufficient context, set the premortem frame explicitly. Something like:
"OK, I have enough context. Let's run the premortem. Here's the premise: it's 6 months from now. [The plan/launch/decision] has failed. It's done. We're looking back and trying to understand what went wrong."
This framing matters. It shifts the mode from "evaluate this plan" (which triggers agreeable responses) to "explain why this died" (which triggers honest, specific failure identification).
### step 2: generate failure reasons (raw premortem)
Run the raw premortem as a single comprehensive analysis. No prescribed categories, no lenses, no constraints. Just the core Klein method:
"This plan has failed 6 months from now. Generate every genuine reason it could have died. Be comprehensive. Be specific. Ground every reason in the actual details of the plan. Don't pad with weak reasons and don't stop early if there are more."
The output should be a comprehensive list of failure reasons, each stated in 1-2 sentences. Be honest and thorough. Some plans might have 4 genuine failure modes. Others might have 9. The number should be whatever is real for this specific plan.
Each failure reason should be:
- Specific to this plan (not generic advice that applies to anything)
- Grounded in actual details the user provided
- A genuine threat (not a minor inconvenience or an extremely unlikely edge case)
### step 3: deep-dive agents (one per failure reason, all in parallel)
Take every failure reason from step 2 and spawn one sub-agent per reason, all in parallel. Each agent takes its assigned failure reason and goes deep on it independently.
**Sub-agent prompt template:**
```
You are an investigator in a premortem analysis. You've been assigned one specific failure reason to analyze in depth.
The plan:
---
[full context: what it is, who it's for, what success looks like, plus relevant workspace context]
---
PREMORTEM FRAME: It is 6 months from now. This plan has failed.
YOUR ASSIGNED FAILURE REASON: [the specific failure reason from step 2]
Your job is to go deep on this one failure. Write the story of how it actually played out. Be specific. Use details from the plan. Make it feel real, like a case study of something that actually happened.
Your output should include:
1. THE FAILURE STORY: A 2-3 paragraph narrative of how this specific failure played out. Use details from the plan. Name specific moments where things went wrong and why.
2. THE UNDERLYING ASSUMPTION: The one thing the user was taking for granted that made this failure possible. State it in one sentence.
3. EARLY WARNING SIGNS: 1-2 concrete, observable signals the user could watch for that would indicate this failure mode is starting to play out. These should be things you can actually see or measure, not vague feelings.
Keep the total response under 300 words. Be direct. Don't hedge. Don't sugarcoat.
```
### step 4: synthesis
After all agents complete, read every deep-dive and produce the synthesis:
**PREMORTEM REPORT**
1. **The Most Likely Failure** — Which failure scenario is most probable given what you know about the plan? Why? This is the one the user should focus on first.
2. **The Most Dangerous Failure** — Which failure scenario would cause the most damage if it happened, even if it's less likely? This is the one worth insuring against.
3. **The Hidden Assumption** — Across all the failure analyses, what's the single biggest assumption the user is making that they probably haven't questioned? This is often where the real value of the premortem lives: the thing that's so obvious to the user that they forgot it was an assumption.
4. **The Revised Plan** — Based on the failure scenarios, what specific changes would make the plan more resilient? Be concrete. Don't say "consider your pricing." Say "test pricing at $X with 20 people before committing to it publicly." Each revision should map directly to a specific failure scenario.
5. **The Pre-Launch Checklist** — 3-5 specific things the user should verify, test, or put in place before executing. Each one should prevent or detect one of the failure modes identified.
### step 5: generate the premortem report
Generate a visual HTML report and save it to the user's workspace.
**File:** `premortem-report-[timestamp].html`
The report should be a single self-contained HTML file with inline CSS. Design principles:
- Dark background (#0a0e1a or similar), clean typography, easy to scan
- The synthesis section (most likely failure, most dangerous failure, hidden assumption, revised plan, checklist) should be prominently displayed at the top since that's what most people will read first
- One visual card per failure reason showing the deep-dive analysis. Each card should display the failure reason as a header, the failure story, the underlying assumption, and the early warning signs. Use distinct accent colors for each card so they're visually scannable.
- A clear visual indicator of severity/likelihood for each failure mode
- The round-robin visual: show the number of agents that ran and their findings as a grid or card layout, so the user can see the full scope of the premortem at a glance
- Footer with timestamp and what was premortemed
Open the HTML file after generating it.
### step 6: save the transcript
Save the full premortem transcript as `premortem-transcript-[timestamp].md` in the same location. This includes:
- The context that was gathered (what, who, success criteria)
- The raw premortem failure reasons
- All agent deep-dives
- The full synthesis
---
## output format
Every premortem session produces two files:
```
premortem-report-[timestamp].html # visual report for scanning
premortem-transcript-[timestamp].md # full transcript for reference
```
The user sees the HTML report first. The transcript is there if they want to dig deeper into the reasoning behind each failure scenario.
Also provide a concise summary in the chat: the most likely failure, the hidden assumption, and the single most important revision to the plan. Three sentences max. The report has the full details.
---
## example: premortming a product launch
**User:** "premortem this: I'm about to launch a $297 live workshop on how to use Claude Cowork for marketing teams. 50 seats. Targeting marketing managers at companies with 10-50 employees."
**Raw premortem identifies 6 failure reasons:**
1. Marketing managers at this company size need approval to spend $297 on professional development, adding friction you haven't accounted for
2. "Claude Cowork for marketing" is a tool-specific pitch in a market where most managers are still figuring out whether AI is relevant to them at all
3. The audience that actually buys might be solopreneurs, not team managers, creating a mismatch between content and attendees
4. Building a workshop for marketing teams requires demo environments with realistic marketing data and multi-seat setups, which takes 5 weeks of prep, not the 2 you budgeted
5. If 60% of attendees are solopreneurs, your reviews and case studies won't resonate with the marketing manager audience you need for future cohorts
6. At $297 with 50 seats, the max revenue is $14,850, which may not justify the prep time against other revenue opportunities
**6 agents go deep on each reason independently, producing failure stories, underlying assumptions, and early warning signs.**
**Synthesis:** Most likely failure is the audience mismatch: you're targeting people who need approval to spend $297, which adds friction you haven't accounted for. Most dangerous failure: attracting solopreneurs instead of team managers means your case studies and testimonials won't resonate with the actual target buyer for future cohorts, compounding the problem over time. Hidden assumption: you're assuming "marketing managers at 10-50 person companies" is a reachable audience, but these people don't self-identify that way and don't hang out in the same places. Revised plan: run a $47 pilot session for 20 people first. Use that to identify whether your actual buyers are team managers or solopreneurs, and build the full workshop for whoever actually shows up.
---
## important notes
- **Always spawn all failure agents in parallel.** Sequential spawning wastes time and lets earlier responses influence later ones.
- **Always set the premortem frame explicitly.** "This has already failed" is the psychological mechanism that makes this work. Without it, the analysis defaults to polite risk assessment instead of honest failure identification.
- **Be comprehensive but not padded.** Find every genuine failure reason. Don't stop at 3 if there are 7. But don't force 7 if there are only 3. The number should be whatever is real for this specific plan.
- **The synthesis is the product.** Most users will read the synthesis and skim the individual failure cards. Make the synthesis specific and actionable.
- **Don't sugarcoat.** The whole point of a premortem is to tell the user things they don't want to hear before reality does. If a plan has serious problems, say so directly.
- **The revised plan must be concrete.** Don't say "consider testing your pricing." Say "run a $47 pilot with 20 people before committing to the full $297 workshop." Every revision should be something the user can actually do this week.
- **Respect the minimum context threshold.** Running a premortem on insufficient context produces generic failures that waste the user's time. It's better to ask one more question than to produce a bad premortem.
- **This is not the LLM Council.** The council gives multiple perspectives on a decision right now. The premortem sends Claude into the future where the decision already failed and works backward to explain why. Different psychological mechanism, different output. If the user seems to want multiple perspectives rather than failure analysis, suggest the council instead.
@@ -0,0 +1,52 @@
name: Restore Gradle build directories
description: Restore project .gradle/, build/ trees for faster CI Gradle jobs
inputs:
scope:
description: Unique id for this job (part of the cache key; use restore-keys to reuse other scopes)
required: true
outputs:
cache-hit:
description: Whether an exact cache key match was restored
value: ${{ steps.cache.outputs.cache-hit == 'true' || steps.cache-android.outputs.cache-hit == 'true' }}
cache-save-scope:
description: Scope to pass to the save action (always this job's scope, not a restored fallback key)
value: ${{ inputs.scope }}
runs:
using: composite
steps:
- uses: actions/cache/restore@v5
if: inputs.scope == 'android'
id: cache-android
with:
path: |
.gradle
build
app/shared/build
app/android/build
utils/shared/build
utils/android/build
key: gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-${{ hashFiles('gradle/libs.versions.toml', 'settings.gradle.kts', 'gradle.properties', 'build.gradle.kts', 'app/desktop/build.gradle.kts', 'app/desktop/proguard-rules.pro', 'app/shared/build.gradle.kts', 'app/android/build.gradle.kts', 'utils/shared/build.gradle.kts', 'utils/android/build.gradle.kts') }}
restore-keys: |
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-build-jar-
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-
- uses: actions/cache/restore@v5
if: inputs.scope != 'android'
id: cache
with:
path: |
.gradle
build
app/desktop/build
app/shared/build
app/android/build
utils/shared/build
utils/android/build
key: gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-${{ hashFiles('gradle/libs.versions.toml', 'settings.gradle.kts', 'gradle.properties', 'build.gradle.kts', 'app/desktop/build.gradle.kts', 'app/desktop/proguard-rules.pro', 'app/shared/build.gradle.kts', 'app/android/build.gradle.kts', 'utils/shared/build.gradle.kts', 'utils/android/build.gradle.kts') }}
restore-keys: |
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-build-jar-
gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-
@@ -0,0 +1,24 @@
name: Restore Windows Rust build cache
description: Restore Cargo registry, git checkouts, and the windows-setup target directory
outputs:
cache-hit:
description: Whether an exact cache key match was restored
value: ${{ steps.cache.outputs.cache-hit }}
runs:
using: composite
steps:
- uses: actions/cache/restore@v5
id: cache
with:
path: |
~/.cargo/registry
~/.cargo/git
app/desktop/windows-setup/target
key: windows-rust-${{ runner.os }}-v3-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }}
restore-keys: |
windows-rust-${{ runner.os }}-v3-
windows-rust-${{ runner.os }}-v2-
windows-rust-tools-v1-
cargo-registry-${{ runner.os }}-
@@ -0,0 +1,17 @@
name: Restore git mtimes
description: Reset tracked file timestamps from git so Gradle incremental builds can be UP-TO-DATE after checkout
runs:
using: composite
steps:
- name: Restore mtimes
shell: bash
run: |
set -euo pipefail
if command -v git-restore-mtime >/dev/null 2>&1; then
git-restore-mtime
exit 0
fi
script="${RUNNER_TEMP}/git-restore-mtime"
curl -fsSL https://raw.githubusercontent.com/MestreLion/git-tools/b5822d297b3ca4a3b6574e78327a464790b14937/git-restore-mtime -o "$script"
python3 "$script"
@@ -0,0 +1,38 @@
name: Save Gradle build directories
description: Save project .gradle/, build/ trees after a Gradle build
inputs:
scope:
description: Same scope passed to cache-gradle-build (save always uses this job's key, not a restored fallback key)
required: true
runs:
using: composite
steps:
- name: Save Android Gradle build cache
if: inputs.scope == 'android'
uses: actions/cache/save@v5
continue-on-error: true
with:
key: gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-${{ hashFiles('gradle/libs.versions.toml', 'settings.gradle.kts', 'gradle.properties', 'build.gradle.kts', 'app/desktop/build.gradle.kts', 'app/desktop/proguard-rules.pro', 'app/shared/build.gradle.kts', 'app/android/build.gradle.kts', 'utils/shared/build.gradle.kts', 'utils/android/build.gradle.kts') }}
path: |
.gradle
build
app/shared/build
app/android/build
utils/shared/build
utils/android/build
- name: Save Gradle build cache
if: inputs.scope != 'android'
uses: actions/cache/save@v5
continue-on-error: true
with:
key: gradle-build-${{ runner.os }}-${{ runner.arch }}-v2-${{ inputs.scope }}-${{ hashFiles('gradle/libs.versions.toml', 'settings.gradle.kts', 'gradle.properties', 'build.gradle.kts', 'app/desktop/build.gradle.kts', 'app/desktop/proguard-rules.pro', 'app/shared/build.gradle.kts', 'app/android/build.gradle.kts', 'utils/shared/build.gradle.kts', 'utils/android/build.gradle.kts') }}
path: |
.gradle
build
app/desktop/build
app/shared/build
app/android/build
utils/shared/build
utils/android/build
@@ -0,0 +1,14 @@
name: Save Windows Rust build cache
description: Save Cargo registry, git checkouts, and the windows-setup target directory
runs:
using: composite
steps:
- uses: actions/cache/save@v5
continue-on-error: true
with:
key: windows-rust-${{ runner.os }}-v3-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }}
path: |
~/.cargo/registry
~/.cargo/git
app/desktop/windows-setup/target
+30
View File
@@ -0,0 +1,30 @@
name: Set release version
description: Writes versionName/versionCode into build.gradle.kts for CI
inputs:
version:
description: Semantic version (e.g. 1.2.3)
required: true
runs:
using: composite
steps:
- name: Set version
shell: bash
run: |
VERSION="${{ inputs.version }}"
VERSION_CODE="$(printf '%s' "$VERSION" | sed 's/[^0-9]//g')"
if [[ -z "$VERSION_CODE" ]]; then
VERSION_CODE=1
fi
GRADLE_FILE="build.gradle.kts"
CURRENT_NAME="$(sed -n 's/.*extra\["versionName"\] = "\([^"]*\)".*/\1/p' "$GRADLE_FILE" | head -n 1)"
CURRENT_CODE="$(sed -n 's/.*extra\["versionCode"\] = \([0-9]*\).*/\1/p' "$GRADLE_FILE" | head -n 1)"
if [[ "$CURRENT_NAME" == "$VERSION" && "$CURRENT_CODE" == "$VERSION_CODE" ]]; then
echo "versionName=$VERSION versionCode=$VERSION_CODE (unchanged)"
exit 0
fi
sed -i.bak "s/extra\\[\"versionName\"\\] = \"[^\"]*\"/extra[\"versionName\"] = \"$VERSION\"/" "$GRADLE_FILE"
sed -i.bak "s/extra\\[\"versionCode\"\\] = [0-9]*/extra[\"versionCode\"] = $VERSION_CODE/" "$GRADLE_FILE"
rm -f "$GRADLE_FILE.bak"
echo "versionName=$VERSION versionCode=$VERSION_CODE"
@@ -0,0 +1,28 @@
name: Setup Java and Gradle
description: Temurin JDK 17 + Gradle wrapper with dependency and build cache
inputs:
java-architecture:
description: Optional JDK architecture (x64). Omit for host default.
required: false
default: ""
cache-read-only:
description: Restore Gradle User Home only; do not save (avoids parallel cache write races).
required: false
default: "false"
runs:
using: composite
steps:
- uses: actions/setup-java@v5
with:
distribution: temurin
java-version: "17"
architecture: ${{ inputs.java-architecture }}
- uses: gradle/actions/setup-gradle@v5
with:
gradle-version: wrapper
cache-read-only: ${{ inputs.cache-read-only == 'true' }}
cache-overwrite-existing: true
add-job-summary: on-failure
-11
View File
@@ -1,11 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "gradle" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
+66
View File
@@ -0,0 +1,66 @@
name: Windows x64 installer
on:
workflow_dispatch:
inputs:
version:
description: "App version (e.g. 1.1.4)"
required: false
default: "1.1.4"
push:
tags:
- "win-x64-*"
concurrency:
group: desktop-windows-x64-${{ github.ref }}
cancel-in-progress: true
env:
GRADLE_OPTS: >-
-Dorg.gradle.jvmargs=-Xmx6g
-Dkotlin.daemon.jvm.options=-Xmx6g
-Dorg.gradle.parallel=true
jobs:
windows-x64:
runs-on: windows-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/setup-java-gradle
- uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-pc-windows-msvc
- name: Cache Cargo
uses: actions/cache@v5
with:
path: |
~/.cargo/registry
~/.cargo/git
app/desktop/windows-setup/target
key: cargo-windows-${{ runner.os }}-${{ hashFiles('app/desktop/windows-setup/Cargo.lock') }}
restore-keys: |
cargo-windows-${{ runner.os }}-
- id: ver
name: Resolve version
shell: bash
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
V="${{ inputs.version }}"
else
V="${GITHUB_REF_NAME#win-x64-}"
fi
echo "version=$V" >> "$GITHUB_OUTPUT"
- uses: ./.github/actions/set-version
with:
version: ${{ steps.ver.outputs.version }}
- name: Package Windows x64 installer
shell: bash
run: |
export FROMCHAT_PACKAGING_JDK="$JAVA_HOME"
./gradlew :app:desktop:packageBetaWindows -PbetaDesktop -PdesktopArch=x64 --no-daemon --console=plain
- uses: actions/upload-artifact@v5
with:
name: windows-x64-installer
path: app/desktop/build/distributions/release/FromChat-Setup-*-beta2.exe
if-no-files-found: error
+558
View File
@@ -0,0 +1,558 @@
name: Release
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
version:
description: "Version to build (e.g. 1.1.4). Overrides tag when set."
required: true
type: string
skip_publish:
description: "Skip GitHub Release upload"
required: false
type: choice
options:
- "false"
- "true"
default: "false"
force_update_release:
description: "Overwrite existing GitHub Release for this version instead of failing"
required: false
type: choice
options:
- "false"
- "true"
default: "false"
concurrency:
group: release
cancel-in-progress: true
env:
GRADLE_OPTS: >-
-Dorg.gradle.jvmargs=-Xmx6g
-Dkotlin.daemon.jvm.options=-Xmx6g
-Dorg.gradle.parallel=true
jobs:
resolve-version:
name: Resolve version
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
version: ${{ steps.ver.outputs.version }}
tag: ${{ steps.ver.outputs.tag }}
prerelease: ${{ steps.ver.outputs.prerelease }}
release_label: ${{ steps.ver.outputs.release_label }}
force_update_release: ${{ steps.ver.outputs.force_update_release }}
steps:
- id: ver
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
V="${{ inputs.version }}"
else
V="${GITHUB_REF_NAME#v}"
fi
if [[ ! "$V" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-].*)?$ ]]; then
echo "Invalid version: $V" >&2
exit 1
fi
if [[ ! "$V" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
echo "Cannot derive release label from version: $V" >&2
exit 1
fi
MAJOR="${BASH_REMATCH[1]}"
MINOR="${BASH_REMATCH[2]}"
PATCH="${BASH_REMATCH[3]}"
if [[ "$PATCH" == "0" ]]; then
RELEASE_LABEL="${MAJOR}.${MINOR}"
else
RELEASE_LABEL="${MAJOR}.${MINOR}.${PATCH}"
fi
TAG="v$V"
echo "version=$V" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "release_label=$RELEASE_LABEL" >> "$GITHUB_OUTPUT"
case "$V" in
*-beta*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;;
*) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;;
esac
if gh release view "$TAG" >/dev/null 2>&1; then
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ inputs.force_update_release }}" = "true" ]; then
echo "Release $TAG exists; force_update_release enabled — publish will overwrite it."
echo "force_update_release=true" >> "$GITHUB_OUTPUT"
else
echo "Release $TAG already exists. Delete it first, or run workflow_dispatch with force_update_release=true." >&2
exit 1
fi
else
echo "force_update_release=false" >> "$GITHUB_OUTPUT"
fi
desktop-proguard:
name: Build JAR
needs: resolve-version
runs-on: ubuntu-latest
timeout-minutes: 45
env:
FROMCHAT_PREBUILT_PROGUARD: "0"
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- uses: ./.github/actions/setup-java-gradle
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: build-jar
- name: Compile and ProGuard release desktop jars
run: ./gradlew :app:desktop:exportReleaseProguardForCi --no-daemon --console=plain
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
- uses: actions/upload-artifact@v5
with:
name: desktop-proguard
path: app/desktop/build/ci/proguard/
if-no-files-found: error
retention-days: 3
windows-common:
name: Windows installer
needs: resolve-version
runs-on: windows-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- uses: ./.github/actions/setup-java-gradle
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: windows-installer
- uses: dtolnay/rust-toolchain@stable
with:
targets: x86_64-pc-windows-msvc
- uses: ./.github/actions/cache-windows-rust-tools
id: rust-tools-cache
- name: Verify Windows Rust binaries
id: rust-binaries
shell: bash
run: |
ready=true
for exe in \
FromChat-Installer.exe \
FromChat-Installer-Helper.exe \
fromchat-portable-launcher.exe \
fromchat-pack.exe \
fromchat-icon-patch.exe
do
if [[ ! -f "app/desktop/windows-setup/target/release/$exe" ]]; then
echo "Missing $exe"
ready=false
fi
done
echo "ready=$ready" >> "$GITHUB_OUTPUT"
- name: Build Windows installer Rust tooling
if: steps.rust-binaries.outputs.ready != 'true'
shell: bash
run: ./gradlew :app:desktop:buildWindowsSetupRust --no-daemon --console=plain
- uses: ./.github/actions/save-windows-rust-cache
if: always()
- uses: actions/upload-artifact@v5
with:
name: windows-rust-tools
path: app/desktop/windows-setup/target/release/*.exe
if-no-files-found: error
retention-days: 3
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
windows-package:
name: Windows (${{ matrix.label }})
needs: [resolve-version, desktop-proguard, windows-common]
env:
FROMCHAT_PREBUILT_PROGUARD: "1"
strategy:
fail-fast: false
matrix:
include:
- arch: x64
label: x64
runner: windows-latest
- arch: arm64
label: ARM
runner: windows-11-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 60
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- name: Ensure ARM64 packaging JDK
if: matrix.arch == 'arm64'
shell: cmd
run: call scripts\ensure-windows-arm64-jdk.cmd
- uses: ./.github/actions/setup-java-gradle
if: matrix.arch == 'x64'
with:
cache-read-only: "true"
- uses: gradle/actions/setup-gradle@v5
if: matrix.arch == 'arm64'
with:
gradle-version: wrapper
cache-read-only: true
add-job-summary: on-failure
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: windows-package-${{ matrix.arch }}
- uses: actions/download-artifact@v5
with:
name: desktop-proguard
path: app/desktop/build/prebuilt/main-release/proguard
- name: Restore Windows Rust installer tools
uses: actions/download-artifact@v5
with:
name: windows-rust-tools
path: app/desktop/windows-setup/target/release
- name: Package Windows ${{ matrix.arch }} installer
shell: bash
env:
FROMCHAT_SKIP_RUST_BUILD: "1"
run: |
export FROMCHAT_PACKAGING_JDK="$JAVA_HOME"
args=(
:app:desktop:packSetupOnly
"-PdesktopArch=${{ matrix.arch }}"
--no-daemon
--console=plain
)
if [ "${{ matrix.arch }}" = "arm64" ]; then
args+=("-PwindowsArm64")
fi
./gradlew "${args[@]}"
- uses: actions/upload-artifact@v5
with:
name: windows-${{ matrix.arch }}
path: app/desktop/build/distributions/release/*-windows-${{ matrix.arch }}.exe
if-no-files-found: error
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
macos:
name: macOS (${{ matrix.label }})
needs: [resolve-version, desktop-proguard]
env:
FROMCHAT_PREBUILT_PROGUARD: "1"
strategy:
fail-fast: false
matrix:
include:
- arch: arm64
label: Apple Silicon
- arch: x64
label: Intel
runs-on: macos-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- uses: ./.github/actions/setup-java-gradle
if: matrix.arch == 'x64'
with:
java-architecture: x64
cache-read-only: "true"
- uses: ./.github/actions/setup-java-gradle
if: matrix.arch == 'arm64'
with:
cache-read-only: "true"
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: macos-${{ matrix.arch }}
- uses: actions/download-artifact@v5
with:
name: desktop-proguard
path: app/desktop/build/prebuilt/main-release/proguard
- name: Cache DMG background tooling
uses: actions/cache@v5
with:
path: |
app/desktop/dmg-background/node_modules
~/.cache/ms-playwright
key: dmg-tools-${{ runner.arch }}-${{ hashFiles('app/desktop/dmg-background/package-lock.json') }}
restore-keys: dmg-tools-${{ runner.arch }}-
- name: Install macOS packaging tools
run: |
if ! command -v create-dmg >/dev/null 2>&1; then
brew install create-dmg
fi
DMG_DIR="app/desktop/dmg-background"
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
- name: Package macOS ${{ matrix.arch }}
run: |
export FROMCHAT_PACKAGING_JDK="$JAVA_HOME"
./gradlew :app:desktop:packageReleaseMac -PdesktopArch=${{ matrix.arch }} --no-daemon --console=plain
- uses: actions/upload-artifact@v5
with:
name: macos-${{ matrix.arch }}
path: app/desktop/build/distributions/release/*-macOS-${{ matrix.arch }}.dmg
if-no-files-found: error
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
linux:
name: Linux (${{ matrix.label }})
needs: [resolve-version, desktop-proguard]
env:
FROMCHAT_PREBUILT_PROGUARD: "1"
strategy:
fail-fast: false
matrix:
include:
- arch: x64
label: x64
runner: ubuntu-latest
appimage: appimagetool-x86_64.AppImage
- arch: arm64
label: ARM
runner: ubuntu-24.04-arm
appimage: appimagetool-aarch64.AppImage
runs-on: ${{ matrix.runner }}
timeout-minutes: 45
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- uses: ./.github/actions/setup-java-gradle
with:
cache-read-only: "true"
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: linux-${{ matrix.arch }}
- uses: actions/download-artifact@v5
with:
name: desktop-proguard
path: app/desktop/build/prebuilt/main-release/proguard
- name: Install Linux packaging tools
run: |
sudo apt-get update
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
fakeroot rpm binutils libfuse2 wget
CACHE_DIR="${RUNNER_TOOL_CACHE}/appimagetool"
mkdir -p "$CACHE_DIR"
TOOL="$CACHE_DIR/appimagetool-${{ matrix.arch }}.AppImage"
if [[ ! -f "$TOOL" ]]; then
wget -q "https://github.com/AppImage/appimagetool/releases/download/continuous/${{ matrix.appimage }}" -O "$TOOL"
chmod +x "$TOOL"
fi
echo "APPIMAGETOOL=$TOOL" >> "$GITHUB_ENV"
- name: Package Linux ${{ matrix.arch }}
run: |
export FROMCHAT_PACKAGING_JDK="$JAVA_HOME"
./gradlew :app:desktop:packageReleaseLinux -PdesktopArch=${{ matrix.arch }} --no-daemon --console=plain
- uses: actions/upload-artifact@v5
with:
name: linux-${{ matrix.arch }}
path: |
app/desktop/build/distributions/release/*-linux-${{ matrix.arch }}.deb
app/desktop/build/distributions/release/*-linux-${{ matrix.arch }}.rpm
app/desktop/build/distributions/release/*-linux-${{ matrix.arch }}.AppImage
if-no-files-found: error
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
android:
name: Android
needs: resolve-version
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/restore-git-mtimes
- uses: ./.github/actions/set-version
with:
version: ${{ needs.resolve-version.outputs.version }}
- uses: ./.github/actions/setup-java-gradle
with:
cache-read-only: "true"
- uses: android-actions/setup-android@v4
- uses: ./.github/actions/cache-gradle-build
id: gradle-build-cache
with:
scope: android
- name: Prepare Android SDK cache dirs
run: mkdir -p ~/.android/build-cache ~/.android/cache
- name: Cache Android SDK extras
uses: actions/cache@v5
with:
path: |
~/.android/build-cache
~/.android/cache
key: android-sdk-${{ runner.os }}-${{ hashFiles('gradle/libs.versions.toml', 'app/android/build.gradle.kts') }}
restore-keys: android-sdk-${{ runner.os }}-
- name: Prepare Android signing
env:
KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
GOOGLE_SERVICES_JSON: ${{ secrets.ANDROID_GOOGLE_SERVICES_JSON }}
RELEASE_STORE_PASSWORD: ${{ secrets.ANDROID_RELEASE_STORE_PASSWORD }}
RELEASE_KEY_PASSWORD: ${{ secrets.ANDROID_RELEASE_KEY_PASSWORD }}
run: |
if [[ -z "$KEYSTORE_BASE64" || -z "$GOOGLE_SERVICES_JSON" ]]; then
echo "Missing ANDROID_KEYSTORE_BASE64 or ANDROID_GOOGLE_SERVICES_JSON secrets" >&2
exit 1
fi
mkdir -p app/android/keys
printf '%s' "$KEYSTORE_BASE64" | base64 -d > app/android/keys/release.jks
keytool -genkeypair -noprompt \
-alias key0 -keyalg RSA -keysize 2048 -validity 10000 \
-dname "CN=FromChat Debug" \
-keystore app/android/keys/debug.jks \
-storepass android -keypass android
{
echo "releaseStorePassword=${RELEASE_STORE_PASSWORD}"
echo "releaseKeyPassword=${RELEASE_KEY_PASSWORD}"
echo "debugStorePassword=android"
echo "debugKeyPassword=android"
} > app/android/keys/keystore.properties
printf '%s' "$GOOGLE_SERVICES_JSON" | base64 -d > app/android/google-services.json
- name: Build universal Android APK
run: ./gradlew :app:android:assembleRelease --no-daemon --console=plain
- uses: ./.github/actions/save-gradle-build-cache
if: always()
with:
scope: ${{ steps.gradle-build-cache.outputs.cache-save-scope }}
- name: Stage APK
run: |
mkdir -p release-staging
APK="$(find app/android/build/outputs/apk/release -name '*release*.apk' | head -n 1)"
cp "$APK" "release-staging/FromChat-${{ needs.resolve-version.outputs.release_label }}.apk"
- uses: actions/upload-artifact@v5
with:
name: android
path: release-staging/*.apk
if-no-files-found: error
publish:
if: ${{ github.event_name != 'workflow_dispatch' || inputs.skip_publish != 'true' }}
needs:
- resolve-version
- windows-package
- macos
- linux
- android
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v5
with:
sparse-checkout: |
RELEASE_NOTES.md
sparse-checkout-cone-mode: false
- uses: actions/download-artifact@v5
with:
pattern: "{windows,macos,linux}-*"
merge-multiple: true
path: artifacts
- uses: actions/download-artifact@v5
with:
name: android
path: artifacts
- name: Collect release assets
env:
LABEL: ${{ needs.resolve-version.outputs.release_label }}
run: |
set -euo pipefail
if [[ ! -d artifacts ]]; then
echo "No artifacts were downloaded" >&2
exit 1
fi
mkdir -p release-assets
pick_one() {
local pattern="$1"
local dest="$2"
local match
match=$(find artifacts -type f -name "$pattern" | head -n 1)
if [[ -z "$match" ]]; then
echo "Missing artifact matching $pattern" >&2
exit 1
fi
cp "$match" "release-assets/$dest"
}
pick_one "*-windows-x64.exe" "FromChat-${LABEL}-x64.exe"
pick_one "*-windows-arm64.exe" "FromChat-${LABEL}-arm.exe"
pick_one "*-macOS-arm64.dmg" "FromChat-${LABEL}-apple.dmg"
pick_one "*-macOS-x64.dmg" "FromChat-${LABEL}-intel.dmg"
pick_one "*-linux-x64.deb" "FromChat-${LABEL}-x64.deb"
pick_one "*-linux-arm64.deb" "FromChat-${LABEL}-arm.deb"
pick_one "*-linux-x64.rpm" "FromChat-${LABEL}-x64.rpm"
pick_one "*-linux-arm64.rpm" "FromChat-${LABEL}-arm.rpm"
pick_one "*-linux-x64.AppImage" "FromChat-${LABEL}-x64.AppImage"
pick_one "*-linux-arm64.AppImage" "FromChat-${LABEL}-arm.AppImage"
pick_one "*.apk" "FromChat-${LABEL}.apk"
if find release-assets -type f -name '*.zip' | grep -q .; then
echo "Release assets must not be zip archives" >&2
exit 1
fi
ls -la release-assets
- name: Publish GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ needs.resolve-version.outputs.tag }}
name: ${{ needs.resolve-version.outputs.tag }}
body_path: RELEASE_NOTES.md
draft: false
prerelease: ${{ needs.resolve-version.outputs.prerelease == 'true' }}
generate_release_notes: false
overwrite_existing: ${{ needs.resolve-version.outputs.force_update_release == 'true' }}
files: |
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}.apk
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-x64.exe
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-arm.exe
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-apple.dmg
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-intel.dmg
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-x64.deb
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-arm.deb
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-x64.rpm
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-arm.rpm
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-x64.AppImage
release-assets/FromChat-${{ needs.resolve-version.outputs.release_label }}-arm.AppImage
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+16 -3
View File
@@ -19,8 +19,21 @@ build
local.properties
app/android/keys
releases
release
/releases
app/android/release
app/android/debug
*.xcuserstate
xcuserdata
xcuserdata
google-services.json
.cursor/plans
*.log
premortem-transcript-*.md
premortem-report-*.html
target/
node_modules
preview-dist
+3
View File
@@ -0,0 +1,3 @@
[submodule ".cursor/skills/material-3-skill"]
path = .cursor/skills/material-3-skill
url = https://github.com/hamen/material-3-skill
+8
View File
@@ -0,0 +1,8 @@
<component name="ArtifactManager">
<artifact type="jar" name="shared-jvm">
<output-path>$PROJECT_DIR$/utils/shared/build/libs</output-path>
<root id="archive" name="shared-jvm.jar">
<element id="module-output" name="FromChat.utils.shared.jvmMain" />
</root>
</artifact>
</component>
+34
View File
@@ -1,5 +1,39 @@
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<JavaCodeStyleSettings>
<option name="IMPORT_LAYOUT_TABLE">
<value>
<package name="android" withSubpackages="true" static="true" />
<package name="androidx" withSubpackages="true" static="true" />
<package name="com" withSubpackages="true" static="true" />
<package name="junit" withSubpackages="true" static="true" />
<package name="net" withSubpackages="true" static="true" />
<package name="org" withSubpackages="true" static="true" />
<package name="java" withSubpackages="true" static="true" />
<package name="javax" withSubpackages="true" static="true" />
<package name="" withSubpackages="true" static="true" />
<emptyLine />
<package name="android" withSubpackages="true" static="false" />
<emptyLine />
<package name="androidx" withSubpackages="true" static="false" />
<emptyLine />
<package name="com" withSubpackages="true" static="false" />
<emptyLine />
<package name="junit" withSubpackages="true" static="false" />
<emptyLine />
<package name="net" withSubpackages="true" static="false" />
<emptyLine />
<package name="org" withSubpackages="true" static="false" />
<emptyLine />
<package name="java" withSubpackages="true" static="false" />
<emptyLine />
<package name="javax" withSubpackages="true" static="false" />
<emptyLine />
<package name="" withSubpackages="true" static="false" />
<emptyLine />
</value>
</option>
</JavaCodeStyleSettings>
<JetCodeStyleSettings>
<option name="CODE_STYLE_DEFAULTS" value="KOTLIN_OFFICIAL" />
</JetCodeStyleSettings>
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
<bytecodeTargetLevel target="17" />
</component>
</project>
+1 -1
View File
@@ -6,12 +6,12 @@
<GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
<option value="$PROJECT_DIR$/app/android" />
<option value="$PROJECT_DIR$/app/desktop" />
<option value="$PROJECT_DIR$/app/shared" />
<option value="$PROJECT_DIR$/utils" />
<option value="$PROJECT_DIR$/utils/android" />
+8
View File
@@ -32,6 +32,14 @@
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="LocalVariableName" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="MultiplatformPreviewAnnotationInFunctionWithParameters" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="MultiplatformPreviewMultipleParameterProviders" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
<option name="previewFile" value="true" />
</inspection_tool>
<inspection_tool class="NestedLambdaShadowedImplicitParameter" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="PreviewAnnotationInFunctionWithParameters" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="externalSystemId" value="Gradle" />
<option name="version" value="2.4.20" />
</component>
</project>
+7 -1
View File
@@ -1,6 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CidrRootsConfiguration">
<excludeRoots>
<file path="$PROJECT_DIR$/app/android/keys" />
</excludeRoots>
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
Generated
+1
View File
@@ -8,5 +8,6 @@
</component>
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/.cursor/skills/material-3-skill" vcs="Git" />
</component>
</project>
+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="XcodeMetaData" PROJECT_DIR="$PROJECT_DIR$/iosApp" PROJECT_FILE="$PROJECT_DIR$/app/ios/iosApp.xcodeproj" />
<component name="XcodeMetaData" PROJECT_DIR="$PROJECT_DIR$/app/ios" PROJECT_FILE="$PROJECT_DIR$/app/ios/iosApp.xcodeproj" />
</project>
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
denis0001.dev@ya.ru.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+216
View File
@@ -0,0 +1,216 @@
# FromChat Android — Code Style
Canonical style reference for Kotlin / Compose Multiplatform code in this repository.
Contributors are **not required** to follow this guide — but sticking to it saves me cleanup time, so its appreciated when you do.
This file is created mostly for AI agents to write good and readable code.
---
## 1. Inline single-use bindings
If a `val`, `var`, local function, or `@Composable` is referenced **exactly once** in the file, inline it at the use site.
Do **not** introduce a named binding only used once.
```kotlin
// ❌ BAD — used once
val padding = MaterialTheme.spacing.medium
Box(modifier = Modifier.padding(padding))
// ✅ GOOD
Box(modifier = Modifier.padding(MaterialTheme.spacing.medium))
```
```kotlin
// ❌ BAD — composable used once
@Composable
private fun ProfileHeaderTitle(text: String) {
Text(text = text, style = MaterialTheme.typography.headlineSmall)
}
@Composable
fun ProfileScreen() {
ProfileHeaderTitle(text = title)
}
// ✅ GOOD — inline at the single call site
@Composable
fun ProfileScreen() {
Text(text = title, style = MaterialTheme.typography.headlineSmall)
}
```
**Keep a name when:**
- The expression has side effects and must not run twice.
- Inlining hides a non-obvious boundary (crypto, network, animation controller, pager math).
- Inlining hurts scanability (long chain, non-obvious subexpression).
---
## 2. Merge small screen helpers into the main file
Screen-local helpers that exist only to serve one screen should live in that screen's file, not a separate file.
Merge into the parent screen file when **all** are true:
- Used only by that screen (or its direct private helpers in the same file).
- Not shared across features or modules.
- The combined file stays readable after the merge.
```kotlin
// ❌ BAD — ProfileActionButtonRow.kt used only from ProfileScreen.kt
// ✅ GOOD — private composables at the bottom of ProfileScreen.kt
```
Extract to a separate file only when shared by **two or more** screens/features, or when the screen file would become unwieldy even after inlining.
---
## 3. Kotlin idioms
Prefer standard library helpers over verbose Java-style patterns.
```kotlin
// ❌ BAD
try {
cache.evict(key)
} catch (_: Exception) {
}
// ✅ GOOD
runCatching { cache.evict(key) }
```
```kotlin
// ❌ BAD
val items = mutableListOf<Item>()
items.add(header)
for (row in rows) items.add(row)
items.add(footer)
// ✅ GOOD
val items = buildList {
add(header)
addAll(rows)
add(footer)
}
```
Use `buildList`, `buildMap`, `buildSet`, `apply`, `also`, `takeIf`, `takeUnless`, scoped functions, and expression bodies where they match surrounding code.
---
## 4. Packages for related files
When several files belong to one feature, group them in a **package directory** instead of scattering at the parent level.
```
// ❌ BAD
ui/profile/ProfileScreen.kt
ui/profile/ProfileRoutes.kt
ui/profile/ProfileBioMarkdown.kt
ui/profile/EditProfileScreen.kt // edit is a sub-flow
// ✅ GOOD
ui/profile/ProfileScreen.kt
ui/profile/ProfileRoutes.kt
ui/profile/bio/ProfileBioMarkdown.kt
ui/profile/edit/EditProfileScreen.kt
```
Rules:
- One primary type per file; file name matches the primary type.
- Sub-packages for sub-features (e.g. `edit`, `bio`, `panels/dm`).
- Do not create a package for a single tiny file that only exists to be merged per §2.
---
## 5. Reuse project abstractions
Prefer existing project components and utilities over new wrappers:
- `com.pr0gramm3r101.utils` — clipboard, `Modifier.conditional`, etc.
- `com.pr0gramm3r101.components``Category`, `ListItem`, etc.
- `ru.fromchat.ui.components` — shared UI primitives.
- `apiRequest` / existing API client patterns.
Match naming, imports, and structure of adjacent files in the same package.
---
## 6. User-visible strings
No hardcoded user-visible copy in shared UI. Use Compose Multiplatform resources:
- `app/shared/src/commonMain/composeResources/values/strings.xml`
- `app/shared/src/commonMain/composeResources/values-ru/strings.xml`
Exception: debug API screen (`ru.fromchat.ui.debug`).
---
## 7. Compose layout and formatting
### Blank lines between composables
Separate **every** `@Composable` in a file with **one** blank line — top-level and `private`.
```kotlin
@Composable
fun Header() { ... }
@Composable
fun Body() { ... }
```
### File size
No hard line limit. Merge or split based on readability.
### Visibility
Screen-local composables merged into a screen file are `private`.
### Layout / dimension constants
Do **not** introduce named constants for bare `.dp` values — use literals inline.
```kotlin
// ❌ BAD
private val CardPadding = 16.dp
Box(modifier = Modifier.padding(CardPadding))
// ✅ GOOD
Box(modifier = Modifier.padding(16.dp))
```
For non-trivial layout values (ratios, spring specs, derived calculations), use top-level `private const` or `private val` in the same file.
---
## 8. Function bodies
- If a function contains **only** a `return` statement, always use an expression body (`=`).
- If the logic is a progressive data transform chainable with `let` / `apply` / `also` / `run`, prefer an expression body.
- Otherwise use a block body.
```kotlin
// ✅ GOOD — single return
private fun label(user: User) = user.visibleUsername ?: stringResource(Res.string.user_fallback)
// ✅ GOOD — chain
private fun normalized(input: String) = input.trim().takeIf { it.isNotEmpty() }?.lowercase().orEmpty()
```
---
## 9. General principles
- Do not strip or rewrite data by comparing to hard-coded UI placeholder strings.
- Do not introduce abstractions used only once (same rule as §1).
- When a convention is ambiguous, match neighboring files in the same package.
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+160
View File
@@ -0,0 +1,160 @@
Read in other languages: [Русский](./README.md)
# FromChat
FromChat is a 100% free and open-source messenger. This repository is the cross-platform client (Android, Desktop via Compose Multiplatform, and iOS).
[📥 Download](https://github.com/fromchat-messenger/android/releases/latest) • [💬 Telegram Channel](https://t.me/fromchat_ch) • [🖥️ Server](https://github.com/fromchat-messenger/backend)
## ✨ Features
- **Voice and video calls** — LiveKit
- **Screen sharing** during calls (Android)
- **Public chat** — server-wide community
- **Direct messages** — legal encryption scheme; server-side E2EE planned
- **Device management** — active sessions
- **Dark mode** by default
- **Open source**
## 📊 Client Comparison
| Feature | Android | Desktop | Web | iOS |
|-----------------------------|---------|--------------------------|-----|-------------------|
| **Messaging and profiles** | ✅ | ✅ | ✅ | ✅ |
| **Voice/video calls** | ✅ | ✅ | ✅ | ✅ |
| **Screen sharing** | ✅ | ❌ | ✅ | ❌ |
| **Push when backgrounded** | ✅ (FCM) | ✅ (persistent WS + tray) | ✅ | ❌ (WS while open) |
| **Message reactions** | ❌ | ❌ | ✅ | ❌ |
| **Rich attachment support** | ✅ | ✅ | ❌ | ✅ |
Desktop replaces the former Electron client in the Web repo. Run with `./gradlew :app:desktop:run`.
### Desktop packaging
Build release packages on the matching OS (or via CI):
| Task | Host | Artifacts |
|------------------------------------------------|------------|-------------------------------------------------------------------------------------|
| `./gradlew :app:desktop:packageReleaseMac` | macOS | `FromChat-<ver>-macOS.dmg` |
| `./gradlew :app:desktop:packageReleaseLinux` | Linux | `.deb`, `.rpm`, `.AppImage` (needs `appimagetool`) |
| `./gradlew :app:desktop:packageReleaseWindows` | Windows | `FromChat-Setup-<ver>.exe`, `FromChat-Portable-<ver>.exe` (Rust toolchain required) |
| `./gradlew :app:desktop:packageReleaseDesktop` | current OS | delegates to the task above |
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.
**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`).
**Installed data:** Windows `%LOCALAPPDATA%\FromChat`, macOS `~/Library/Application Support/FromChat`, Linux `~/.local/share/FromChat` (migrates from legacy `~/.fromchat/cache` when present).
---
## 🏗️ Tech Stack
- **Kotlin**
- **Compose Multiplatform**
- **Material Design 3**
- **Ktor Client**
- **LiveKit** — calls
- **SQLDelight** — local storage
- **Firebase Messaging** — push
- **Coil** — images
---
## 📥 Build and Development (Android Studio)
### Requirements
- Latest Android Studio
- JDK from Android Studio (JetBrains Runtime)
### Quick start
1. **Clone the repository:**
```bash
git clone https://github.com/fromchat-messenger/android.git
cd android
```
2. **Generate keys (Debug & Release):**
```bash
DEBUG_STORE_PASS=CHANGEME
DEBUG_KEY_PASS=CHANGEME
RELEASE_STORE_PASS=CHANGEME
RELEASE_KEY_PASS=CHANGEME
mkdir -p app/android/keys
# Quote passwords: characters like & * ? ! break unquoted shell args.
keytool -genkey -v -keystore app/android/keys/debug.jks \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias key0 -storepass "$DEBUG_STORE_PASS" -keypass "$DEBUG_KEY_PASS" \
-dname "CN=Debug, O=FromChat, C=RU"
keytool -genkey -v -keystore app/android/keys/release.jks \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias key0 -storepass "$RELEASE_STORE_PASS" -keypass "$RELEASE_KEY_PASS" \
-dname "CN=Release, O=FromChat, C=RU"
# Path must be app/android/keys/keystore.properties (matches build.gradle.kts).
# Outer "…" / '…' around values are optional; Gradle strips them.
cat > app/android/keys/keystore.properties << EOF
releaseStorePassword=$RELEASE_STORE_PASS
releaseKeyPassword=$RELEASE_KEY_PASS
debugStorePassword=$DEBUG_STORE_PASS
debugKeyPassword=$DEBUG_KEY_PASS
EOF
```
3. **Open in Android Studio:** `File → Open` → repo root. Gradle syncs dependencies automatically.
4. **Run:** `Run → Run 'Android'` (or the app debug configuration).
Debug application id: `ru.fromchat.beta`.
### CLI build
```bash
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
./gradlew :app:shared:compileAndroidMain :app:android:assembleDebug
```
APK: `app/android/build/outputs/apk/debug/android-debug.apk`.
### Project structure
```
android/
├── app/
│ ├── android/ # Android app module
│ └── shared/ # Compose Multiplatform
│ ├── commonMain/
│ ├── androidMain/
│ └── iosMain/ # not ready yet
├── utils/ # reusable utilities
│ ├── android/
│ └── shared/
└── gradle/libs.versions.toml
```
Code style: [CODE_STYLE.md](./CODE_STYLE.md).
---
## 🤝 Contribute
Pull requests are welcome. For large changes, follow `CODE_STYLE.md`.
## 📄 License
GNU Affero General Public License v3.0 — see [LICENSE](./LICENSE).
## 🔗 Related Repositories
- [Backend](https://github.com/fromchat-messenger/backend)
- [Web](https://github.com/fromchat-messenger/web)
- [Website](https://github.com/fromchat-messenger/site)
- [Deployment](https://github.com/fromchat-messenger/deployment)
+157
View File
@@ -0,0 +1,157 @@
Читать на других языках: [English](./README.en.md)
# FromChat
FromChat — 100% бесплатный и открытый мессенджер. В этом репозитории — кроссплатформенный клиент (Android, Desktop на Compose Multiplatform и iOS).
[📥 Скачать](https://github.com/fromchat-messenger/android/releases/latest) • [💬 Telegram-канал](https://t.me/fromchat_ch) • [🖥️ Сервер](https://github.com/fromchat-messenger/backend)
## ✨ Возможности
- **Голосовые и видеозвонки** — LiveKit
- **Демонстрация экрана** во время звонков (Android)
- **Общий чат** — сообщество пользователей сервера
- **Личные сообщения** — легальная схема шифрования; E2EE на сервере планируется
- **Управление устройствами** — активные сеансы
- **Тёмный режим** по умолчанию
- **Открытый исходный код**
## 📊 Сравнение клиентов
| Возможность | Android | Desktop | Web | iOS |
|------------------------------------|---------|--------------------------|-----|---------------------|
| **Обмен сообщениями и профили** | ✅ | ✅ | ✅ | ✅ |
| **Голосовые/видеозвонки** | ✅ | ✅ | ✅ | ✅ |
| **Демонстрация экрана** | ✅ | ❌ | ✅ | ❌ |
| **Push в фоне** | ✅ (FCM) | ✅ (постоянный WS + tray) | ✅ | ❌ (WS пока открыто) |
| **Реакции на сообщения** | ❌ | ❌ | ✅ | ❌ |
| **Расширенная поддержка вложений** | ✅ | ✅ | ❌ | ✅ |
Desktop заменяет бывший Electron-клиент в репозитории Web. Запуск: `./gradlew :app:desktop:run`.
### Сборка Desktop
Релизные пакеты собираются на соответствующей ОС (или в CI):
| Задача | Хост | Артефакты |
|--------|------|-----------|
| `./gradlew :app:desktop:packageReleaseMac` | macOS | `FromChat-<ver>-macOS.dmg` |
| `./gradlew :app:desktop:packageReleaseLinux` | Linux | `.deb`, `.rpm`, `.AppImage` (нужен `appimagetool`) |
| `./gradlew :app:desktop:packageReleaseWindows` | Windows | `FromChat-Setup-<ver>.exe`, `FromChat-Portable-<ver>.exe` (нужен Rust) |
| `./gradlew :app:desktop:packageReleaseDesktop` | текущая ОС | делегирует в задачу выше |
Результаты: `app/desktop/build/distributions/release/`.
**CI:** `.github/workflows/desktop-release.yml` на тегах `v*` и `workflow_dispatch` (обязательный input `version`), затем загрузка в GitHub Release.
**Windows portable:** в папке виден только `FromChat Portable.exe`; остальной runtime — Hidden. Данные в Hidden `fromchat-data/` рядом с EXE.
**Установка:** Windows `%LOCALAPPDATA%\FromChat`, macOS `~/Library/Application Support/FromChat`, Linux `~/.local/share/FromChat` (миграция с `~/.fromchat/cache` при наличии).
---
## 🏗️ Технологический стек
- **Kotlin**
- **Compose Multiplatform**
- **Material Design 3**
- **Ktor Client**
- **LiveKit** — звонки
- **SQLDelight** — локальное хранилище
- **Firebase Messaging** — push
- **Coil** — изображения
---
## 📥 Сборка и разработка (Android Studio)
### Требования
- Актуальная Android Studio
- JDK из Android Studio (JetBrains Runtime)
### Быстрый старт
1. **Клонируйте репозиторий:**
```bash
git clone https://github.com/fromchat-messenger/android.git
cd android
```
2. **Сгенерируйте ключи (Debug & Release):**
```bash
DEBUG_STORE_PASS="CHANGEME"
DEBUG_KEY_PASS="CHANGEME"
RELEASE_STORE_PASS="CHANGEME"
RELEASE_KEY_PASS="CHANGEME"
mkdir -p app/android/keys
keytool -genkey -v -keystore app/android/keys/debug.jks \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias key0 -storepass "$DEBUG_STORE_PASS" -keypass "$DEBUG_KEY_PASS" \
-dname "CN=Debug, O=FromChat, C=RU"
keytool -genkey -v -keystore app/android/keys/release.jks \
-keyalg RSA -keysize 2048 -validity 10000 \
-alias key0 -storepass "$RELEASE_STORE_PASS" -keypass "$RELEASE_KEY_PASS" \
-dname "CN=Release, O=FromChat, C=RU"
cat > app/android/keys/keystore.properties << EOF
releaseStorePassword=$RELEASE_STORE_PASS
releaseKeyPassword=$RELEASE_KEY_PASS
debugStorePassword=$DEBUG_STORE_PASS
debugKeyPassword=$DEBUG_KEY_PASS
EOF
```
3. **Откройте в Android Studio:** `File → Open` → корень репозитория. Gradle подтянет зависимости сам.
4. **Запустите:** `Run → Run 'Android'` (или debug-конфигурацию приложения).
Debug application id: `ru.fromchat.beta`.
### Сборка из CLI
```bash
export JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"
./gradlew :app:shared:compileAndroidMain :app:android:assembleDebug
```
APK: `app/android/build/outputs/apk/debug/android-debug.apk`.
### Структура проекта
```
android/
├── app/
│ ├── android/ # Android app module
│ └── shared/ # Compose Multiplatform
│ ├── commonMain/
│ ├── androidMain/
│ └── iosMain/ # ещё не готово
├── utils/ # переиспользуемые утилиты
│ ├── android/
│ └── shared/
└── gradle/libs.versions.toml
```
Стиль кода: [CODE_STYLE.md](./CODE_STYLE.md).
---
## 🤝 Внести вклад
Pull Request приветствуются. Перед крупными изменениями загляните в `CODE_STYLE.md`.
## 📄 Лицензия
GNU Affero General Public License v3.0 — см. [LICENSE](./LICENSE).
## 🔗 Связанные репозитории
- [Backend](https://github.com/fromchat-messenger/backend)
- [Web](https://github.com/fromchat-messenger/web)
- [Website](https://github.com/fromchat-messenger/site)
- [Deployment](https://github.com/fromchat-messenger/deployment)
+3
View File
@@ -0,0 +1,3 @@
- Наконец-то появилась десктопная версия FromChat! Теперь вы можете общаться прямо с вашего компьютера на Windows, Linux и macOS. Даже старые Mac на Intel поддерживаются.
- На Android и десктопе вы теперь можете напрямую перетаскивать файлы и картинки прямо в чат без необходимости долго их искать.
- Улучшен экран устройств: теперь более наглядно видно, на каких устройствах вы вошли в аккаунт. И иконки теперь везде одинаковые.
+111 -42
View File
@@ -1,73 +1,132 @@
import com.android.build.gradle.tasks.MergeSourceSetFolders
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import java.io.FileInputStream
import com.android.build.api.dsl.ApplicationExtension
import java.util.Properties
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
alias(libs.plugins.compose.compiler)
alias(libs.plugins.compose.multiplatform)
alias(libs.plugins.google.services)
}
kotlin {
compilerOptions {
jvmTarget = JvmTarget.JVM_17
abstract class FixComposeResTask : DefaultTask() {
@get:InputFiles abstract val inputFiles: ConfigurableFileCollection
@get:OutputDirectory abstract val outputDirectory: DirectoryProperty
@TaskAction
fun action() {
val outDir = outputDirectory.get().asFile.apply {
deleteRecursively()
mkdirs()
}
inputFiles.forEach { file ->
if (file.exists()) {
file.copyRecursively(
File(outDir, "composeResources/ru.fromchat"),
overwrite = true
)
}
}
}
}
val fixComposeResourcesStructure = tasks.register<Copy>("fixComposeResourcesStructure") {
val fixComposeResourcesStructure = tasks.register<FixComposeResTask>("fixComposeResourcesStructure") {
val sharedProject = rootProject.project(":app:shared")
from(
inputFiles.from(
sharedProject
.layout
.buildDirectory
.dir("generated/compose/resourceGenerator/preparedResources/commonMain/composeResources")
.dir(
"generated/compose/resourceGenerator/preparedResources/commonMain/composeResources"
)
)
into(
layout
.buildDirectory
.dir("intermediates/fixed_compose_res/composeResources/ru.fromchat")
outputDirectory.set(
layout.buildDirectory.dir("intermediates/fixed_compose_res")
)
dependsOn(sharedProject.tasks.matching { it.name.contains("prepareComposeResources", ignoreCase = true) })
dependsOn(sharedProject.tasks.matching { it.name.contains("copyNonXmlValueResources", ignoreCase = true) })
dependsOn(
sharedProject.tasks.matching {
it.name.contains("prepareComposeResources", ignoreCase = true)
}
)
}
android {
extensions.configure<ApplicationExtension> {
namespace = "ru.fromchat"
compileSdk = 36
compileSdk {
version = release(37) {
minorApiLevel = 2
}
}
defaultConfig {
applicationId = "ru.fromchat"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"
targetSdk = 37
versionCode = rootProject.extra["versionCode"] as Int
versionName = rootProject.extra["versionName"] as String
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}
}
val keystorePropertiesFile = file("keys/keystore.properties")
val hasReleaseKeystore = keystorePropertiesFile.isFile && file("keys/release.jks").isFile
val hasDebugKeystore = keystorePropertiesFile.isFile && file("keys/debug.jks").isFile
signingConfigs {
create("release") {
if (hasReleaseKeystore || hasDebugKeystore) {
val keystoreProperties = Properties().apply {
load(FileInputStream(file("keys/keystore.properties")))
load(keystorePropertiesFile.inputStream())
}
storeFile = file("keys/release.jks")
keyAlias = "key0"
storePassword = keystoreProperties["storePassword"].toString()
keyPassword = keystoreProperties["keyPassword"].toString()
enableV3Signing = true
fun Properties.password(key: String): String {
val raw = getProperty(key)
?: error("Missing $key in keys/keystore.properties")
return raw.trim().removeSurrounding("\"").removeSurrounding("'")
}
if (hasReleaseKeystore) {
create("release") {
storeFile = file("keys/release.jks")
keyAlias = "key0"
storePassword = keystoreProperties.password("releaseStorePassword")
keyPassword = keystoreProperties.password("releaseKeyPassword")
enableV3Signing = true
}
}
if (hasDebugKeystore) {
getByName("debug") {
storeFile = file("keys/debug.jks")
keyAlias = "key0"
storePassword = keystoreProperties.password("debugStorePassword")
keyPassword = keystoreProperties.password("debugKeyPassword")
enableV3Signing = true
}
}
}
}
buildTypes {
debug {
applicationIdSuffix = ".beta"
versionNameSuffix = "-beta"
if (hasDebugKeystore) {
signingConfig = signingConfigs.getByName("debug")
}
}
release {
isMinifyEnabled = true
isShrinkResources = true
signingConfig = signingConfigs.getByName("release")
if (hasReleaseKeystore) {
signingConfig = signingConfigs.getByName("release")
}
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
@@ -78,7 +137,19 @@ android {
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
excludes += setOf(
"/META-INF/{AL2.0,LGPL2.1}",
"/META-INF/DEPENDENCIES",
"/META-INF/LICENSE",
"/META-INF/LICENSE.txt",
"/META-INF/LICENSE.md",
"/META-INF/NOTICE",
"/META-INF/NOTICE.txt",
"/META-INF/NOTICE.md",
"/META-INF/*.kotlin_module",
"/META-INF/versions/**",
"DebugProbesKt.bin",
)
}
}
@@ -86,22 +157,17 @@ android {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
sourceSets["main"].apply {
assets.srcDirs(
layout.buildDirectory.dir("intermediates/fixed_compose_res")
androidComponents {
onVariants { variant ->
variant.sources.assets?.addGeneratedSourceDirectory(
fixComposeResourcesStructure,
FixComposeResTask::outputDirectory
)
}
}
tasks.withType<MergeSourceSetFolders>().configureEach {
dependsOn(fixComposeResourcesStructure)
}
tasks.matching { it.name.contains("lintVital", ignoreCase = true) }.configureEach {
dependsOn(fixComposeResourcesStructure)
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
@@ -109,15 +175,18 @@ dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.graphics)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.compose.material3)
implementation(libs.play.services.base)
debugImplementation(libs.androidx.compose.ui.tooling)
debugImplementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.adaptive.android)
implementation(libs.ktor.client.okhttp)
implementation(libs.ktor.client.core)
implementation(libs.slf4j.android)
implementation(libs.material)
implementation(libs.firebase.messaging)
implementation(libs.kotlinx.serialization.json)
implementation(project(":app:shared"))
implementation(project(":utils:shared"))
+36 -18
View File
@@ -1,21 +1,39 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Release shrinking: obfuscate/rename classes and members as aggressively as R8 allows.
# proguard-android-optimize.txt (from build.gradle) supplies repackageclasses, overloadaggressively, etc.
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
# Crash reports: keep real .kt file names and line numbers; class names stay obfuscated.
-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Kotlin serialization keep structure required at runtime; names may still be shortened.
-keepattributes *Annotation*, InnerClasses, Signature
-dontnote kotlinx.serialization.AnnotationsKt
-if @kotlinx.serialization.Serializable class **
-keepclassmembers class <1> {
static <1>$Companion Companion;
}
-if @kotlinx.serialization.Serializable class ** {
static **$* *;
}
-keepclassmembers,allowobfuscation,allowshrinking class <2>$<3> {
kotlinx.serialization.KSerializer serializer(...);
}
-keep,allowobfuscation,allowshrinking,includedescriptorclasses class **$$serializer {
*;
}
-keepclasseswithmembers,allowobfuscation,allowshrinking class ** {
kotlinx.serialization.KSerializer serializer(...);
}
# SQLDelight generated adapters referenced directly, safe to obfuscate names.
-keep,allowobfuscation,allowshrinking class ru.fromchat.db.** {
*;
}
# Reflection-heavy runtime deps (strip unused code; suppress benign missing-class noise).
-dontwarn org.bouncycastle.**
-dontwarn org.slf4j.**
-dontwarn io.livekit.**
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name" translatable="false">FromChat Beta</string>
</resources>
+56 -1
View File
@@ -2,9 +2,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Required when handing APKs to com.google.android.packageinstaller via ACTION_VIEW. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application
android:enableOnBackInvokedCallback="true"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
@@ -15,15 +19,66 @@
android:usesCleartextTraffic="true"
android:name=".App"
android:networkSecurityConfig="@xml/network_security_config">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_fromchat" />
<meta-data
android:name="firebase_messaging_installation_id_enabled"
android:value="true" />
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:enableOnBackInvokedCallback="true"
android:theme="@style/Theme.FromChat.SplashScreen"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="fromchat"
android:host="u"
android:pathPrefix="/" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="fromchat"
android:host="oauth"
android:pathPrefix="/yandex" />
</intent-filter>
</activity>
<service
android:name=".fcm.FromChatFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<receiver
android:name=".notifications.NotificationReplyReceiver"
android:exported="false">
<intent-filter>
<action android:name="${applicationId}.NOTIFICATION_REPLY" />
</intent-filter>
</receiver>
<provider
android:name="ru.fromchat.api.local.cache.AttachmentFileProvider"
android:authorities="${applicationId}.attachment_files"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/fromchat_attachment_paths" />
</provider>
</application>
</manifest>
+16 -2
View File
@@ -2,10 +2,24 @@ package ru.fromchat
import android.app.Application
import com.pr0gramm3r101.utils.UtilsLibrary
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import ru.fromchat.api.ApiClient
import ru.fromchat.api.local.workers.AttachmentTransferBootstrap
import ru.fromchat.notifications.MessageNotificationCoordinator
class App: Application() {
class App : Application() {
@OptIn(DelicateCoroutinesApi::class)
override fun onCreate() {
super.onCreate()
UtilsLibrary.init(this)
MessageNotificationCoordinator.install()
GlobalScope.launch(Dispatchers.IO) {
runCatching { ApiClient.loadPersistedData() }
AttachmentTransferBootstrap.launchOnApplicationStart()
}
}
}
}
@@ -1,20 +1,249 @@
package ru.fromchat
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import kotlinx.coroutines.launch
import ru.fromchat.notifications.NotificationLaunchCoordinator
import ru.fromchat.notifications.NotificationLaunchTarget
import ru.fromchat.ui.App
import ru.fromchat.ui.chat.panels.publicchat.isPublicChatVisible
private const val EXTRA_NOTIFICATION_CHAT_TYPE = "notification_chat_type"
private const val EXTRA_OPEN_DM_USER_ID = "open_dm_user_id"
private const val EXTRA_MESSAGE_ID = "scroll_to_message_id"
private const val CHAT_TYPE_PUBLIC = "public"
private const val CHAT_TYPE_DM = "dm"
private const val INVALID_PROFILE_DEEP_LINK_MESSAGE = "Could not open this profile link. Use fromchat://u/<idOrUsername>."
private data class ProfileDeepLinkResolution(
val scrollToMessageId: Int? = null,
val startAtPublicChat: Boolean = false,
val startAtDmConversationUserId: Int? = null,
val startAtProfileUserId: Int? = null,
val startAtProfileUsername: String? = null,
val profileLookupErrorMessage: String? = null
)
private data class ProfileDeepLinkTarget(
val userId: Int? = null,
val username: String? = null,
val parseError: String? = null
)
class MainActivity : ComponentActivity() {
private var scrollToMessageId by mutableStateOf<Int?>(null)
private var startAtPublicChat by mutableStateOf(false)
private var startAtDmConversationUserId by mutableStateOf<Int?>(null)
private var startAtProfileUserId by mutableStateOf<Int?>(null)
private var startAtProfileUsername by mutableStateOf<String?>(null)
private var profileLookupErrorMessage by mutableStateOf<String?>(null)
private var prevIsPublicChatVisible: Boolean? = null
private val requestNotificationPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) {}
private fun parseLaunchStateFromIntent(intent: Intent?): ProfileDeepLinkResolution {
Logger.d(
"ProfileDeepLink",
"handleIntent: action=${intent?.action}, data=${intent?.dataString}, messageId=${intent?.getIntExtra(EXTRA_MESSAGE_ID, -1)}, " +
"chatType=${intent?.getStringExtra(EXTRA_NOTIFICATION_CHAT_TYPE)}, openDmUserId=${intent?.getIntExtra(EXTRA_OPEN_DM_USER_ID, -1)}"
)
val messageId = intent?.getIntExtra(EXTRA_MESSAGE_ID, -1) ?: -1
val chatType = intent?.getStringExtra(EXTRA_NOTIFICATION_CHAT_TYPE) ?: CHAT_TYPE_PUBLIC
val dmConversationUserId = intent?.getIntExtra(EXTRA_OPEN_DM_USER_ID, -1) ?: -1
val profileTarget = parseProfileDeepLink(intent)
Logger.d(
"ProfileDeepLink",
"handleIntent parsedProfileTarget: userId=${profileTarget?.userId}, username=${profileTarget?.username}, parseError=${profileTarget?.parseError}"
)
val baseState = ProfileDeepLinkResolution(
scrollToMessageId = if (messageId != -1) messageId else null,
startAtPublicChat = messageId != -1 && chatType != CHAT_TYPE_DM,
startAtDmConversationUserId = if (chatType == CHAT_TYPE_DM && dmConversationUserId > 0) {
dmConversationUserId
} else {
null
}
)
if (profileTarget?.parseError != null) {
return baseState.copy(profileLookupErrorMessage = profileTarget.parseError)
}
if (profileTarget == null) {
return baseState
}
val profileUserId = profileTarget.userId
val profileUsername = profileTarget.username?.trim().orEmpty()
if (profileUserId != null && profileUserId > 0) {
return baseState.copy(
startAtProfileUserId = profileUserId,
startAtProfileUsername = null,
startAtDmConversationUserId = null,
startAtPublicChat = false,
)
}
if (profileUsername.isNotEmpty()) {
return baseState.copy(
startAtProfileUserId = null,
startAtProfileUsername = profileUsername,
startAtDmConversationUserId = null,
startAtPublicChat = false,
)
}
return baseState
}
private fun applyLaunchState(launchState: ProfileDeepLinkResolution) {
scrollToMessageId = launchState.scrollToMessageId
startAtPublicChat = launchState.startAtPublicChat
startAtDmConversationUserId = launchState.startAtDmConversationUserId
startAtProfileUserId = launchState.startAtProfileUserId
startAtProfileUsername = launchState.startAtProfileUsername
profileLookupErrorMessage = launchState.profileLookupErrorMessage
}
private fun deliverLaunchIntent(intent: Intent?) {
val launchState = parseLaunchStateFromIntent(intent)
applyLaunchState(launchState)
val messageId = intent?.getIntExtra(EXTRA_MESSAGE_ID, -1) ?: -1
if (messageId == -1 || intent?.hasExtra(EXTRA_NOTIFICATION_CHAT_TYPE) != true) {
return
}
NotificationLaunchCoordinator.publish(
NotificationLaunchTarget(
dmConversationUserId = launchState.startAtDmConversationUserId,
scrollToMessageId = launchState.scrollToMessageId,
startAtPublicChat = launchState.startAtPublicChat,
)
)
}
private fun parseProfileDeepLink(intent: Intent?): ProfileDeepLinkTarget? {
val data: Uri = intent?.data ?: return null
Logger.d("ProfileDeepLink", "parseProfileDeepLink intentData=${data.toString()}")
if (!data.scheme.equals("fromchat", ignoreCase = true)) return null
if (data.host != "u") return null
val segments = data.pathSegments.filter { it.isNotBlank() }
Logger.d("ProfileDeepLink", "parseProfileDeepLink segments=${segments.joinToString(",")}")
if (segments.size != 1) {
return ProfileDeepLinkTarget(parseError = INVALID_PROFILE_DEEP_LINK_MESSAGE)
}
val segment = segments[0].let { Uri.decode(it) }
val trimmed = segment.trim()
if (trimmed.isBlank()) {
return ProfileDeepLinkTarget(parseError = INVALID_PROFILE_DEEP_LINK_MESSAGE)
}
return trimmed.toLongOrNull()?.let { idLong ->
if (idLong in 1L..Int.MAX_VALUE.toLong()) {
Logger.d("ProfileDeepLink", "parseProfileDeepLink resolved as userId=$idLong")
ProfileDeepLinkTarget(userId = idLong.toInt())
} else {
Logger.d("ProfileDeepLink", "parseProfileDeepLink large numeric treated as username=$trimmed")
ProfileDeepLinkTarget(username = trimmed)
}
} ?: run {
Logger.d("ProfileDeepLink", "parseProfileDeepLink resolved as username=$trimmed")
ProfileDeepLinkTarget(username = trimmed)
}
}
private fun checkGooglePlayServices(): Boolean {
with (GoogleApiAvailability.getInstance()) {
val resultCode = isGooglePlayServicesAvailable(this@MainActivity)
if (resultCode == ConnectionResult.SUCCESS) {
return true
}
if (isUserResolvableError(resultCode)) {
getErrorDialog(
this@MainActivity,
resultCode,
9000
)?.show()
}
return false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
Logger.i("MainActivity", "onCreate savedInstanceStateNull=${savedInstanceState == null}")
super.onCreate(savedInstanceState)
installSplashScreen()
enableEdgeToEdge()
deliverLaunchIntent(intent)
setContent {
App()
App(
scrollToMessageId = scrollToMessageId,
startAtPublicChat = startAtPublicChat,
startAtDmConversationUserId = startAtDmConversationUserId,
startAtProfileUserId = startAtProfileUserId,
startAtProfileUsername = startAtProfileUsername,
profileLookupErrorMessage = profileLookupErrorMessage,
onProfileLookupErrorMessageConsumed = {
profileLookupErrorMessage = null
}
)
}
lifecycleScope.launch {
checkGooglePlayServices()
}
// Request POST_NOTIFICATIONS permission on Android 13+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
deliverLaunchIntent(intent)
}
override fun onPause() {
Logger.i("MainActivity", "onPause")
super.onPause()
prevIsPublicChatVisible = isPublicChatVisible
isPublicChatVisible = false
}
override fun onResume() {
Logger.i("MainActivity", "onResume")
super.onResume()
isPublicChatVisible = prevIsPublicChatVisible ?: false
}
override fun onDestroy() {
Logger.i("MainActivity", "onDestroy isFinishing=$isFinishing")
super.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
Logger.i("MainActivity", "onSaveInstanceState")
super.onSaveInstanceState(outState)
}
}
@@ -0,0 +1,67 @@
package ru.fromchat.fcm
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import com.pr0gramm3r101.utils.settings.settings
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import ru.fromchat.Logger
import ru.fromchat.api.ApiClient
import ru.fromchat.api.uploadPendingFcmTokenIfAvailable
import ru.fromchat.notifications.MessageNotificationCoordinator
@OptIn(DelicateCoroutinesApi::class)
class FromChatFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Logger.i(
"FromChatFCM",
"onMessageReceived: from=${remoteMessage.from} dataSize=${remoteMessage.data.size}",
)
Logger.d("FromChatFCM", "onMessageReceived data=${remoteMessage.data}")
GlobalScope.launch(Dispatchers.IO) {
try {
val pushData = remoteMessage.data
val fallbackMessageId = pushData["message_id"]?.toIntOrNull()
?: pushData["dm_id"]?.toIntOrNull()
val senderId = pushData["sender_id"]?.toIntOrNull()
val messageType = pushData["type"] ?: "public_message"
val isDirectMessage = messageType.equals("dm", ignoreCase = true)
if (ApiClient.token.isNullOrBlank()) {
Logger.w("FromChatFCM", "No auth token in memory; loading persisted data before handling push")
ApiClient.loadPersistedData()
}
val currentUserId = settings.getInt("current_user_id", -1)
if (senderId != null && senderId == currentUserId) {
Logger.d("FromChatFCM", "Skipping push for own message senderId=$senderId")
return@launch
}
if (isDirectMessage) {
MessageNotificationCoordinator.fetchAndNotify(
includeDmMessages = true,
dmMessageId = fallbackMessageId,
)
} else {
MessageNotificationCoordinator.schedulePublicFetchAndNotify()
}
} catch (e: Exception) {
Logger.e("FromChatFCM", "onMessageReceived error: ${e.message}", e)
}
}
}
override fun onRegistered(installationId: String) {
Logger.i("FromChatFCM", "onRegistered received (...${installationId.takeLast(8)})")
GlobalScope.launch(Dispatchers.IO) {
try {
settings.putString("pending_fcm_token", installationId)
uploadPendingFcmTokenIfAvailable()
Logger.i("FromChatFCM", "FCM installation id queued or uploaded for this app instance")
} catch (e: Exception) {
Logger.e("FromChatFCM", "onRegistered upload error: ${e.message}", e)
}
}
}
}
@@ -0,0 +1,86 @@
package ru.fromchat.notifications
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.RemoteInput
import androidx.core.app.NotificationManagerCompat
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import ru.fromchat.Logger
import ru.fromchat.api.ApiClient
private const val EXTRA_REPLY_CHAT_TYPE = "notification_reply_chat_type"
private const val EXTRA_REPLY_DM_USER_ID = "notification_reply_dm_user_id"
private const val EXTRA_REPLY_PARENT_MESSAGE_ID = "notification_reply_parent_message_id"
private const val CHAT_TYPE_PUBLIC = "public"
private const val CHAT_TYPE_DM = "dm"
@OptIn(DelicateCoroutinesApi::class)
class NotificationReplyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Logger.d(
"NotificationReply",
"onReceive action=${intent.action} extras=${intent.extras?.keySet()?.joinToString()}",
)
val replyText = RemoteInput.getResultsFromIntent(intent)?.let { input ->
(input.getCharSequence(KEY_TEXT_REPLY)
?: input.getCharSequence("key_text_reply"))
}
?.toString()
?.trim()
?: run {
Logger.w("NotificationReply", "No inline reply text found")
return
}
if (replyText.isBlank()) {
Logger.w("NotificationReply", "Inline reply text is blank")
return
}
val chatType = intent.getStringExtra(EXTRA_REPLY_CHAT_TYPE) ?: CHAT_TYPE_PUBLIC
val targetDmUserId = intent.getIntExtra(EXTRA_REPLY_DM_USER_ID, -1)
val parentMessageId = intent.getIntExtra(EXTRA_REPLY_PARENT_MESSAGE_ID, -1).takeIf { it > 0 }
Logger.d("NotificationReply", "Received reply for $chatType (length=${replyText.length})")
val notificationId = intent.getIntExtra("notification_id", 0)
if (intent.hasExtra("notification_id")) {
NotificationManagerCompat.from(context).cancel(notificationId)
}
MessageNotificationCoordinator.dismissAll()
GlobalScope.launch(Dispatchers.IO) {
try {
if (ApiClient.token.isNullOrBlank()) {
ApiClient.loadPersistedData()
}
when (chatType) {
CHAT_TYPE_DM -> {
if (targetDmUserId > 0) {
ApiClient.sendDm(
recipientId = targetDmUserId,
plaintext = replyText,
replyToId = parentMessageId
)
} else {
Logger.w("NotificationReply", "Received DM reply without recipient id; skipping send")
}
}
else -> ApiClient.sendMessageViaHttp(
content = replyText,
replyToId = parentMessageId
)
}
Logger.i("NotificationReply", "Reply dispatch attempt completed for $chatType")
} catch (e: Exception) {
Logger.w("NotificationReply", "Failed to send reply", e)
}
}
}
}
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="1000"
android:viewportHeight="1000">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M494,221.5c43.2,0 85.8,0.1 128.4,-0 42.7,-0.1 81.5,12.2 114.8,39.8 30.5,25.2 49.7,58 57,97.6 1.8,9.4 2.6,19.1 2.6,28.7 0.3,47.8 0,95.6 0.1,143.4 0.1,32.6 -9.9,61.9 -28.3,88.2 -21.2,30.3 -48.8,52.2 -83.2,64.2 -12.9,4.5 -26.9,7.5 -40.5,7.6 -95.6,0.6 -191.2,0.2 -286.8,0.6 -5.2,0 -11.3,2.8 -15.6,6.2 -22.2,17.2 -43.8,35.1 -65.8,52.5 -10.9,8.6 -21.9,17.4 -33.8,24.4 -14.4,8.4 -31.4,2.4 -37.5,-12.1 -1.8,-4.1 -2.1,-9.2 -2.1,-13.8 -0.1,-97.8 -0.2,-195.6 -0.2,-293.4 0,-24.8 -0.9,-49.6 0.3,-74.4 1.8,-37.5 14.7,-71 39.1,-99.2 31.7,-36.6 71.7,-57 119.4,-59.2 38.1,-1.7 76.3,-0.9 114.5,-1.1 5.6,-0 11.1,0 17.3,0M330.4,269.1c-16,5.5 -30.2,14.3 -43,25.6 -30.2,26.8 -46.7,60.7 -46.8,101.7 -0.4,108 -0.2,216 -0.2,324 0,2.5 0.2,4.9 0.4,8.1 1.5,-0.8 2.4,-1.1 3.1,-1.6 22.5,-18 45.5,-35.4 67.3,-54.3 15.9,-13.9 33.5,-19.1 54,-19 88.1,0.4 176.1,0.1 264.2,0.2 22.8,0 44,-6.1 63.9,-17 22.3,-12.2 40.4,-29.1 52.5,-52.1 11.1,-21.2 14.6,-44 14.3,-67.8 -0.4,-42.7 0.2,-85.3 -1.3,-128 -1.1,-34.2 -15.6,-63.3 -39.1,-87.4 -24.5,-25.1 -54,-39.6 -88.9,-39.8 -84,-0.4 -168.1,-0.1 -252.1,-0.2 -16.3,0 -32.1,2 -48.4,7.7h0Z" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M401.4,512.8c-30.4,8.6 -59,-5.7 -73.3,-29.9 -13.2,-22.3 -11,-51.9 4.9,-72.2 23.3,-29.7 68.1,-35.5 96.6,-8.4 23.3,22.2 27,58.5 7,85.5 -8.9,12.1 -20.5,20.5 -35.2,25.1h0Z" />
<path
android:fillColor="#FFFFFFFF"
android:pathData="M484.5,471.4c-9.1,-6.2 -12.4,-14.2 -9.9,-22.8 2,-7 10.4,-13.8 20,-13.7 39.3,0.4 78.7,0.2 118,0.2h7.3c0.3,-0.5 0.5,-1 0.8,-1.5 -3.5,-3.7 -6.9,-7.5 -10.4,-11.2 -7.9,-8.4 -8.3,-20 -0.9,-27.5 8.2,-8.2 21.2,-8.7 29.1,-0.7 15.2,15.3 30.3,30.7 45.3,46.1 8.1,8.4 8.4,20.7 0.3,29.1 -16.3,16.7 -32.8,33.1 -49.3,49.5 -6.1,6.1 -18.3,5.5 -24.8,-0.8 -6.9,-6.7 -8,-17.9 -2,-25 4.5,-5.3 9.7,-10.1 14.5,-15.1 1.1,-1.2 2.2,-2.4 4.2,-4.6 -3.3,-0.2 -5.3,-0.4 -7.3,-0.4 -42,0 -84.1,0.1 -126.1,-0 -2.8,0 -5.6,-0.9 -8.8,-1.5h-0Z" />
</vector>
+7 -7
View File
@@ -10,13 +10,13 @@
android:translateX="150"
android:translateY="150">
<path
android:pathData="M494,221.5c43.2,0 85.8,0.1 128.4,-0 42.7,-0.1 81.5,12.2 114.8,39.8 30.5,25.2 49.7,58 57,97.6 1.8,9.4 2.6,19.1 2.6,28.7 0.3,47.8 0,95.6 0.1,143.4 0.1,32.6 -9.9,61.9 -28.3,88.2 -21.2,30.3 -48.8,52.2 -83.2,64.2 -12.9,4.5 -26.9,7.5 -40.5,7.6 -95.6,0.6 -191.2,0.2 -286.8,0.6 -5.2,0 -11.3,2.8 -15.6,6.2 -22.2,17.2 -43.8,35.1 -65.8,52.5 -10.9,8.6 -21.9,17.4 -33.8,24.4 -14.4,8.4 -31.4,2.4 -37.5,-12.1 -1.8,-4.1 -2.1,-9.2 -2.1,-13.8 -0.1,-97.8 -0.2,-195.6 -0.2,-293.4 0,-24.8 -0.9,-49.6 0.3,-74.4 1.8,-37.5 14.7,-71 39.1,-99.2 31.7,-36.6 71.7,-57 119.4,-59.2 38.1,-1.7 76.3,-0.9 114.5,-1.1 5.6,-0 11.1,0 17.3,0M330.4,269.1c-16,5.5 -30.2,14.3 -43,25.6 -30.2,26.8 -46.7,60.7 -46.8,101.7 -0.4,108 -0.2,216 -0.2,324 0,2.5 0.2,4.9 0.4,8.1 1.5,-0.8 2.4,-1.1 3.1,-1.6 22.5,-18 45.5,-35.4 67.3,-54.3 15.9,-13.9 33.5,-19.1 54,-19 88.1,0.4 176.1,0.1 264.2,0.2 22.8,0 44,-6.1 63.9,-17 22.3,-12.2 40.4,-29.1 52.5,-52.1 11.1,-21.2 14.6,-44 14.3,-67.8 -0.4,-42.7 0.2,-85.3 -1.3,-128 -1.1,-34.2 -15.6,-63.3 -39.1,-87.4 -24.5,-25.1 -54,-39.6 -88.9,-39.8 -84,-0.4 -168.1,-0.1 -252.1,-0.2 -16.3,0 -32.1,2 -48.4,7.7h0Z"
android:fillColor="#fff" />
<path
android:pathData="M401.4,512.8c-30.4,8.6 -59,-5.7 -73.3,-29.9 -13.2,-22.3 -11,-51.9 4.9,-72.2 23.3,-29.7 68.1,-35.5 96.6,-8.4 23.3,22.2 27,58.5 7,85.5 -8.9,12.1 -20.5,20.5 -35.2,25.1h0Z"
android:fillColor="#fff" />
<path
android:pathData="M484.5,471.4c-9.1,-6.2 -12.4,-14.2 -9.9,-22.8 2,-7 10.4,-13.8 20,-13.7 39.3,0.4 78.7,0.2 118,0.2h7.3c0.3,-0.5 0.5,-1 0.8,-1.5 -3.5,-3.7 -6.9,-7.5 -10.4,-11.2 -7.9,-8.4 -8.3,-20 -0.9,-27.5 8.2,-8.2 21.2,-8.7 29.1,-0.7 15.2,15.3 30.3,30.7 45.3,46.1 8.1,8.4 8.4,20.7 0.3,29.1 -16.3,16.7 -32.8,33.1 -49.3,49.5 -6.1,6.1 -18.3,5.5 -24.8,-0.8 -6.9,-6.7 -8,-17.9 -2,-25 4.5,-5.3 9.7,-10.1 14.5,-15.1 1.1,-1.2 2.2,-2.4 4.2,-4.6 -3.3,-0.2 -5.3,-0.4 -7.3,-0.4 -42,0 -84.1,0.1 -126.1,-0 -2.8,0 -5.6,-0.9 -8.8,-1.5h-0Z"
android:pathData="M494,221.5c43.2,0 85.8,0.1 128.4,-0 42.7,-0.1 81.5,12.2 114.8,39.8 30.5,25.2 49.7,58 57,97.6 1.8,9.4 2.6,19.1 2.6,28.7 0.3,47.8 0,95.6 0.1,143.4 0.1,32.6 -9.9,61.9 -28.3,88.2 -21.2,30.3 -48.8,52.2 -83.2,64.2 -12.9,4.5 -26.9,7.5 -40.5,7.6 -95.6,0.6 -191.2,0.2 -286.8,0.6 -5.2,0 -11.3,2.8 -15.6,6.2 -22.2,17.2 -43.8,35.1 -65.8,52.5 -10.9,8.6 -21.9,17.4 -33.8,24.4 -14.4,8.4 -31.4,2.4 -37.5,-12.1 -1.8,-4.1 -2.1,-9.2 -2.1,-13.8 -0.1,-97.8 -0.2,-195.6 -0.2,-293.4 0,-24.8 -0.9,-49.6 0.3,-74.4 1.8,-37.5 14.7,-71 39.1,-99.2 31.7,-36.6 71.7,-57 119.4,-59.2 38.1,-1.7 76.3,-0.9 114.5,-1.1 5.6,-0 11.1,0 17.3,0M330.4,269.1c-16,5.5 -30.2,14.3 -43,25.6 -30.2,26.8 -46.7,60.7 -46.8,101.7 -0.4,108 -0.2,216 -0.2,324 0,2.5 0.2,4.9 0.4,8.1 1.5,-0.8 2.4,-1.1 3.1,-1.6 22.5,-18 45.5,-35.4 67.3,-54.3 15.9,-13.9 33.5,-19.1 54,-19 88.1,0.4 176.1,0.1 264.2,0.2 22.8,0 44,-6.1 63.9,-17 22.3,-12.2 40.4,-29.1 52.5,-52.1 11.1,-21.2 14.6,-44 14.3,-67.8 -0.4,-42.7 0.2,-85.3 -1.3,-128 -1.1,-34.2 -15.6,-63.3 -39.1,-87.4 -24.5,-25.1 -54,-39.6 -88.9,-39.8 -84,-0.4 -168.1,-0.1 -252.1,-0.2 -16.3,0 -32.1,2 -48.4,7.7h0Z"
android:fillColor="#fff" />
<path
android:pathData="M401.4,512.8c-30.4,8.6 -59,-5.7 -73.3,-29.9 -13.2,-22.3 -11,-51.9 4.9,-72.2 23.3,-29.7 68.1,-35.5 96.6,-8.4 23.3,22.2 27,58.5 7,85.5 -8.9,12.1 -20.5,20.5 -35.2,25.1h0Z"
android:fillColor="#fff" />
<path
android:pathData="M484.5,471.4c-9.1,-6.2 -12.4,-14.2 -9.9,-22.8 2,-7 10.4,-13.8 20,-13.7 39.3,0.4 78.7,0.2 118,0.2h7.3c0.3,-0.5 0.5,-1 0.8,-1.5 -3.5,-3.7 -6.9,-7.5 -10.4,-11.2 -7.9,-8.4 -8.3,-20 -0.9,-27.5 8.2,-8.2 21.2,-8.7 29.1,-0.7 15.2,15.3 30.3,30.7 45.3,46.1 8.1,8.4 8.4,20.7 0.3,29.1 -16.3,16.7 -32.8,33.1 -49.3,49.5 -6.1,6.1 -18.3,5.5 -24.8,-0.8 -6.9,-6.7 -8,-17.9 -2,-25 4.5,-5.3 9.7,-10.1 14.5,-15.1 1.1,-1.2 2.2,-2.4 4.2,-4.6 -3.3,-0.2 -5.3,-0.4 -7.3,-0.4 -42,0 -84.1,0.1 -126.1,-0 -2.8,0 -5.6,-0.9 -8.8,-1.5h-0Z"
android:fillColor="#fff" />
</group>
</vector>
@@ -0,0 +1,16 @@
<vector
xmlns:android="http://schemas.android.com/apk/res/android"
android:width="200dp"
android:height="200dp"
android:viewportWidth="1000"
android:viewportHeight="1000">
<path
android:pathData="M494,221.5c43.2,0 85.8,0.1 128.4,-0 42.7,-0.1 81.5,12.2 114.8,39.8 30.5,25.2 49.7,58 57,97.6 1.8,9.4 2.6,19.1 2.6,28.7 0.3,47.8 0,95.6 0.1,143.4 0.1,32.6 -9.9,61.9 -28.3,88.2 -21.2,30.3 -48.8,52.2 -83.2,64.2 -12.9,4.5 -26.9,7.5 -40.5,7.6 -95.6,0.6 -191.2,0.2 -286.8,0.6 -5.2,0 -11.3,2.8 -15.6,6.2 -22.2,17.2 -43.8,35.1 -65.8,52.5 -10.9,8.6 -21.9,17.4 -33.8,24.4 -14.4,8.4 -31.4,2.4 -37.5,-12.1 -1.8,-4.1 -2.1,-9.2 -2.1,-13.8 -0.1,-97.8 -0.2,-195.6 -0.2,-293.4 0,-24.8 -0.9,-49.6 0.3,-74.4 1.8,-37.5 14.7,-71 39.1,-99.2 31.7,-36.6 71.7,-57 119.4,-59.2 38.1,-1.7 76.3,-0.9 114.5,-1.1 5.6,-0 11.1,0 17.3,0M330.4,269.1c-16,5.5 -30.2,14.3 -43,25.6 -30.2,26.8 -46.7,60.7 -46.8,101.7 -0.4,108 -0.2,216 -0.2,324 0,2.5 0.2,4.9 0.4,8.1 1.5,-0.8 2.4,-1.1 3.1,-1.6 22.5,-18 45.5,-35.4 67.3,-54.3 15.9,-13.9 33.5,-19.1 54,-19 88.1,0.4 176.1,0.1 264.2,0.2 22.8,0 44,-6.1 63.9,-17 22.3,-12.2 40.4,-29.1 52.5,-52.1 11.1,-21.2 14.6,-44 14.3,-67.8 -0.4,-42.7 0.2,-85.3 -1.3,-128 -1.1,-34.2 -15.6,-63.3 -39.1,-87.4 -24.5,-25.1 -54,-39.6 -88.9,-39.8 -84,-0.4 -168.1,-0.1 -252.1,-0.2 -16.3,0 -32.1,2 -48.4,7.7h0Z"
android:fillColor="#fff" />
<path
android:pathData="M401.4,512.8c-30.4,8.6 -59,-5.7 -73.3,-29.9 -13.2,-22.3 -11,-51.9 4.9,-72.2 23.3,-29.7 68.1,-35.5 96.6,-8.4 23.3,22.2 27,58.5 7,85.5 -8.9,12.1 -20.5,20.5 -35.2,25.1h0Z"
android:fillColor="#fff" />
<path
android:pathData="M484.5,471.4c-9.1,-6.2 -12.4,-14.2 -9.9,-22.8 2,-7 10.4,-13.8 20,-13.7 39.3,0.4 78.7,0.2 118,0.2h7.3c0.3,-0.5 0.5,-1 0.8,-1.5 -3.5,-3.7 -6.9,-7.5 -10.4,-11.2 -7.9,-8.4 -8.3,-20 -0.9,-27.5 8.2,-8.2 21.2,-8.7 29.1,-0.7 15.2,15.3 30.3,30.7 45.3,46.1 8.1,8.4 8.4,20.7 0.3,29.1 -16.3,16.7 -32.8,33.1 -49.3,49.5 -6.1,6.1 -18.3,5.5 -24.8,-0.8 -6.9,-6.7 -8,-17.9 -2,-25 4.5,-5.3 9.7,-10.1 14.5,-15.1 1.1,-1.2 2.2,-2.4 4.2,-4.6 -3.3,-0.2 -5.3,-0.4 -7.3,-0.4 -42,0 -84.1,0.1 -126.1,-0 -2.8,0 -5.6,-0.9 -8.8,-1.5h-0Z"
android:fillColor="#fff" />
</vector>
@@ -0,0 +1,11 @@
<resources>
<string name="public_chat">Общий чат</string>
<string name="chat_preview_attachment">Вложение</string>
<string name="chat_preview_image_emoji">📷</string>
<string name="chat_preview_image">%1$s 1 фото</string>
<string name="notification_reply">Ответить</string>
<string name="notification_reply_hint">Ответ в чат…</string>
<string name="notification_direct_message">Личное сообщение</string>
<string name="notification_direct_message_from">Личное сообщение от %1$s</string>
<string name="notification_direct_messages_title">Личные сообщения</string>
</resources>
@@ -1,3 +1,12 @@
<resources>
<string name="app_name" translatable="false">FromChat</string>
<string name="public_chat">Main chat</string>
<string name="chat_preview_attachment">Attachment</string>
<string name="chat_preview_image_emoji">📷</string>
<string name="chat_preview_image">%1$s 1 photo</string>
<string name="notification_reply">Reply</string>
<string name="notification_reply_hint">Reply to chat…</string>
<string name="notification_direct_message">Direct message</string>
<string name="notification_direct_message_from">Direct message from %1$s</string>
<string name="notification_direct_messages_title">Direct Messages</string>
</resources>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="decrypted_files" path="decrypted_files/" />
<cache-path name="decrypted_images" path="decrypted_images/" />
<!-- Outbound upload staging (instance uploads/) -->
<cache-path name="fromchat" path="fromchat/" />
</paths>
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

@@ -0,0 +1,8 @@
{
"appLabel": "FromChat",
"applicationsLabel": "Программы",
"primaryColor": "#dabaf9",
"titleBarInset": 22,
"windowChromeBottom": 22
}
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env node
/**
* Export the DMG artboard to PNG + icon slot positions for create-dmg.
*
* Args: <stageDir> <distDir>
*
* Outputs under distDir:
* dmg-background.png
* dmg-background@2x.png
* icon-positions.json
*/
import { chromium } from "playwright";
import { createServer } from "node:http";
import { readFile, mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { readFile as readFileSync } from "node:fs/promises";
const [stageArg, distArg] = process.argv.slice(2);
if (!stageArg || !distArg) {
console.error("Usage: node export.mjs <stageDir> <distDir>");
process.exit(1);
}
const ROOT = path.resolve(stageArg);
const DIST = path.resolve(distArg);
const CONFIG_PATH = path.join(ROOT, "dmg-config.json");
const MIME = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".png": "image/png",
".ttf": "font/ttf",
};
function startStaticServer() {
return new Promise((resolve, reject) => {
const server = createServer(async (req, res) => {
try {
const urlPath = decodeURIComponent((req.url ?? "/").split("?")[0]);
const rel = urlPath === "/" ? "/index.html" : urlPath;
const filePath = path.normalize(path.join(ROOT, rel));
if (!filePath.startsWith(ROOT)) {
res.writeHead(403).end("Forbidden");
return;
}
const data = await readFile(filePath);
const ext = path.extname(filePath).toLowerCase();
res.writeHead(200, {
"Content-Type": MIME[ext] ?? "application/octet-stream",
"Cache-Control": "no-store",
});
res.end(data);
} catch {
res.writeHead(404).end("Not found");
}
});
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
if (!addr || typeof addr === "string") {
reject(new Error("Failed to bind static server"));
return;
}
resolve({ server, port: addr.port });
});
server.on("error", reject);
});
}
function round(n) {
return Math.round(n * 100) / 100;
}
async function measureSlots(page) {
return page.evaluate(() => {
const artboard = document.querySelector("#dmg");
if (!artboard) throw new Error("#dmg not found");
const artRect = artboard.getBoundingClientRect();
const measureSlot = (id) => {
const el = document.querySelector("#" + id);
if (!el) throw new Error("#" + id + " not found");
const r = el.getBoundingClientRect();
const width = r.width;
const height = r.height;
const x = r.left - artRect.left;
const y = r.top - artRect.top;
return {
id,
x,
y,
width,
height,
centerX: x + width / 2,
centerY: y + height / 2,
};
};
return {
artboard: {
width: artboard.clientWidth,
height: artboard.clientHeight,
},
slots: {
app: measureSlot("slot-app"),
applications: measureSlot("slot-applications"),
},
};
});
}
function buildPositionsJson(measured) {
const { artboard, slots } = measured;
const app = slots.app;
const applications = slots.applications;
return {
canvas: {
width: round(artboard.width),
height: round(artboard.height),
background: "dist/dmg-background.png",
background2x: "dist/dmg-background@2x.png",
},
// Include both the standard "Applications" name and the localized "Программы"
// so create-dmg (Finder) receives the expected English link while we also
// keep the localized name for our records and packaging logic.
icons: {
"FromChat.app": {
x: round(app.centerX),
y: round(app.centerY),
width: round(app.width),
height: round(app.height),
slotId: "slot-app",
},
"Applications": {
x: round(applications.centerX),
y: round(applications.centerY),
width: round(applications.width),
height: round(applications.height),
slotId: "slot-applications",
},
"Программы": {
x: round(applications.centerX),
y: round(applications.centerY),
width: round(applications.width),
height: round(applications.height),
slotId: "slot-applications",
},
},
createDmg: {
windowSize: [round(artboard.width), round(artboard.height)],
iconSize: Math.round(Math.min(app.width, app.height) * 0.88),
icons: [
["FromChat.app", round(app.centerX), round(app.centerY)],
["Applications", round(applications.centerX), round(applications.centerY)],
["Программы", round(applications.centerX), round(applications.centerY)],
],
},
};
}
async function applyConfig(page, config) {
const windowChromeBottom = config.windowChromeBottom ?? config.titleBarInset ?? 22;
await page.evaluate(
({ bottom, primaryColor }) => {
document.documentElement.style.setProperty("--window-chrome-bottom", `${bottom}px`);
if (primaryColor) {
document.documentElement.style.setProperty("--primary-pill", primaryColor);
}
},
{ bottom: windowChromeBottom, primaryColor: config.primaryColor },
);
return windowChromeBottom;
}
async function applyLabelsAndMeasure(page, config, measured) {
// Set labels from config into DOM, measure their rendered widths and apply inline styles,
// then position the label pills centered under measured slot centers.
return page.evaluate(
({ cfg, measured }) => {
document.documentElement.style.setProperty("--primary-pill", cfg.primaryColor || "#7e22ce");
const setLabel = (selector, text) => {
const el = document.querySelector(selector);
if (!el) return null;
el.textContent = text;
return el;
};
const appLabel = setLabel('.slot__label[data-for="slot-app"]', cfg.appLabel || "FromChat");
const appsLabel = setLabel('.slot__label[data-for="slot-applications"]', cfg.applicationsLabel || "Программы");
const measureTextWidth = (el) => {
if (!el) return 0;
const span = document.createElement("span");
span.style.visibility = "hidden";
span.style.position = "absolute";
span.style.whiteSpace = "nowrap";
span.style.font = window.getComputedStyle(el).font;
span.textContent = el.textContent;
document.body.appendChild(span);
const w = Math.ceil(span.getBoundingClientRect().width);
document.body.removeChild(span);
return w;
};
const horizPad = 24;
const appW = measureTextWidth(appLabel);
const appsW = measureTextWidth(appsLabel);
// Finder draws labels below icons; placeholders stay invisible in the PNG.
const labelGapBelowSlot = -1;
const placeLabel = (el, slot, textWidth) => {
if (!el || !slot) return;
const width = textWidth + horizPad;
el.style.width = `${width}px`;
el.style.left = `${Math.round(slot.centerX)}px`;
el.style.top = `${Math.round(slot.centerY + slot.height / 2 + labelGapBelowSlot)}px`;
el.style.transform = "translateX(-50%)";
};
placeLabel(appLabel, measured?.slots?.app, appW);
placeLabel(appsLabel, measured?.slots?.applications, appsW);
const rectFor = (el) => {
if (!el) return null;
const r = el.getBoundingClientRect();
const bg = getComputedStyle(el, "::before").backgroundColor;
return { left: Math.round(r.left), top: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height), bg };
};
return {
labels: {
app: { text: appLabel?.textContent || "", width: appW + horizPad, rect: rectFor(appLabel) },
applications: { text: appsLabel?.textContent || "", width: appsW + horizPad, rect: rectFor(appsLabel) },
},
};
},
{ cfg: config, measured },
);
}
async function screenshotArtboard(page, outPath, deviceScaleFactor) {
const dmg = page.locator("#dmg");
await dmg.waitFor({ state: "visible" });
await page.evaluate(async () => {
if (document.fonts?.ready) await document.fonts.ready;
});
await page.waitForTimeout(150);
await dmg.screenshot({
path: outPath,
type: "png",
omitBackground: false,
scale: deviceScaleFactor === 2 ? "device" : "css",
});
}
async function loadConfig() {
try {
const cfgText = await readFileSync(CONFIG_PATH, "utf8");
return JSON.parse(cfgText);
} catch {
return {};
}
}
async function exportAtScale(browser, baseUrl, cfg, scale) {
const context = await browser.newContext({
viewport: { width: 1280, height: 900 },
deviceScaleFactor: scale,
});
const page = await context.newPage();
await page.goto(baseUrl, { waitUntil: "networkidle" });
await page.evaluate(async () => {
if (document.fonts?.ready) await document.fonts.ready;
});
await applyConfig(page, cfg);
const measured = await measureSlots(page);
const labelMetrics = await applyLabelsAndMeasure(page, cfg, measured);
const suffix = scale === 2 ? "@2x" : "";
await screenshotArtboard(page, path.join(DIST, `dmg-background${suffix}.png`), scale);
await context.close();
return { measured, labelMetrics };
}
async function main() {
await mkdir(DIST, { recursive: true });
const { server, port } = await startStaticServer();
const baseUrl = `http://127.0.0.1:${port}/`;
let browser;
try {
browser = await chromium.launch({ headless: true });
const cfg = await loadConfig();
const { measured, labelMetrics } = await exportAtScale(browser, baseUrl, cfg, 1);
console.log("label metrics:", JSON.stringify(labelMetrics));
const positions = buildPositionsJson(measured);
positions.labels = labelMetrics.labels;
await writeFile(
path.join(DIST, "icon-positions.json"),
`${JSON.stringify(positions, null, 2)}\n`,
"utf8",
);
console.log(`canvas ${positions.canvas.width}×${positions.canvas.height}`);
await exportAtScale(browser, baseUrl, cfg, 2);
console.log(`wrote ${path.join(DIST, "dmg-background.png")}`);
console.log(`wrote ${path.join(DIST, "dmg-background@2x.png")}`);
console.log(`wrote ${path.join(DIST, "icon-positions.json")}`);
} finally {
if (browser) await browser.close();
server.close();
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
+48
View File
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>FromChat — фон DMG</title>
<!-- Montserrat for brand wordmark; Google Sans kept for the rest (local fonts) -->
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<!--
Icon slots (#slot-app, #slot-applications) mark create-dmg / appdmg drop targets.
Empty outlines only — Finder draws the real icons and labels.
-->
<div id="dmg" role="img" aria-label="Фон установки FromChat (DMG)">
<div class="window-chrome-bleed" aria-hidden="true"></div>
<header class="brand">
<div class="brand__logo-wrap">
<div class="brand__logo" aria-hidden="true"></div>
</div>
<div class="brand__wordmark">FromChat</div>
<div class="brand__tagline">Перетащите в «Программы», чтобы установить</div>
</header>
<div class="install">
<div id="slot-app" class="slot" aria-hidden="true"></div>
<div class="arrow" aria-hidden="true">
<!-- Material Symbols Rounded arrow_forward (Google Fonts / fonts.gstatic) -->
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" width="44" height="44" fill="currentColor">
<path d="M686-450H190q-13 0-21.5-8.5T160-480q0-13 8.5-21.5T190-510h496L459-737q-9-9-9-21t9-21q9-9 21-9t21 9l278 278q5 5 7 10t2 11q0 6-2 11t-7 10L501-181q-9 9-21 9t-21-9q-9-9-9-21t9-21l227-227Z"/>
</svg>
</div>
<div id="slot-applications" class="slot" aria-hidden="true"></div>
</div>
<div class="slot__label" data-for="slot-app" aria-hidden="true">FromChat</div>
<div class="slot__label" data-for="slot-applications" aria-hidden="true">Программы</div>
<p class="notice">
Если macOS блокирует приложение, откройте
<strong>Системные настройки → Конфиденциальность и безопасность</strong>
и разрешите его.
</p>
</div>
</body>
</html>
+57
View File
@@ -0,0 +1,57 @@
{
"name": "fromchat-dmg-background-tools",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "fromchat-dmg-background-tools",
"dependencies": {
"playwright": "1.52.0"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.52.0.tgz",
"integrity": "sha512-JAwMNMBlxJ2oD1kce4KPtMkDeKGHQstdpFPcPH3maElAXon/QZeTvtsfXmTMRyO9TslfoYOXkSsvao2nE1ilTw==",
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.52.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.52.0.tgz",
"integrity": "sha512-l2osTgLXSMeuLZOML9qYODUQoPPnUsKsb5/P6LJ2e6uPKXUdPK5WYhN4z03G+YNbWmGDY4YENauNu4ZKczreHg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "fromchat-dmg-background-tools",
"private": true,
"type": "module",
"dependencies": {
"playwright": "1.52.0"
}
}
+261
View File
@@ -0,0 +1,261 @@
/* Fonts and logo are staged by :app:desktop:stageDmgBackground from composeResources. */
@font-face {
font-family: "Google Sans";
font-style: normal;
font-weight: 400;
font-display: block;
src: url("assets/fonts/google_sans_regular.ttf") format("truetype");
}
@font-face {
font-family: "Google Sans";
font-style: normal;
font-weight: 500;
font-display: block;
src: url("assets/fonts/google_sans_medium.ttf") format("truetype");
}
@font-face {
font-family: "Google Sans";
font-style: normal;
font-weight: 600;
font-display: block;
src: url("assets/fonts/google_sans_semibold.ttf") format("truetype");
}
@font-face {
font-family: "Google Sans";
font-style: normal;
font-weight: 700;
font-display: block;
src: url("assets/fonts/google_sans_bold.ttf") format("truetype");
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
background: rgb(21, 18, 24);
overflow: hidden;
}
:root {
--brand-gradient: linear-gradient(
45deg,
#9333ea,
#6366f1,
#3b82f6,
#a855f7,
#d946ef,
#ec4899,
#7e22ce
);
--brand-conic: conic-gradient(
from 0deg,
rgba(147, 51, 234, 0.5) 0%,
rgba(99, 102, 241, 0.6) 12.5%,
rgba(59, 130, 246, 0.55) 25%,
rgba(168, 85, 247, 0.5) 37.5%,
rgba(217, 70, 239, 0.6) 50%,
rgba(236, 72, 153, 0.55) 62.5%,
rgba(192, 132, 252, 0.5) 75%,
rgba(126, 34, 206, 0.6) 87.5%,
rgba(147, 51, 234, 0.5) 100%
);
--surface: rgb(21, 18, 24);
--on-surface: rgba(230, 224, 233, 0.92);
--on-surface-muted: rgba(230, 224, 233, 0.72);
/* Extra strip at the bottom; Finder clips it so the visible area lines up with the title bar. */
--window-chrome-bottom: 22px;
--content-height: 380px;
--slot-size: 96px;
}
#dmg {
position: relative;
width: 540px;
height: calc(var(--content-height) + var(--window-chrome-bottom));
overflow: hidden;
color: var(--on-surface);
font-family: "Google Sans", system-ui, sans-serif;
background-color: var(--surface);
isolation: isolate;
}
/* Clipped by Finder at the bottom — keeps the designed content aligned under the title bar. */
.window-chrome-bleed {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: var(--window-chrome-bottom);
background-color: var(--surface);
z-index: 0;
}
.brand {
position: absolute;
top: 28px;
left: 0;
right: 0;
z-index: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
}
.brand__logo-wrap {
position: relative;
width: 100%;
overflow-x: clip;
display: flex;
justify-content: center;
}
.brand__logo-wrap::before {
content: "";
background: var(--brand-conic);
position: absolute;
width: 1200px;
height: 1200px;
bottom: -180px;
opacity: 0.48;
left: calc(50% - 600px);
border-radius: 50%;
filter: blur(80px);
pointer-events: none;
z-index: 0;
}
.brand__logo {
width: 68px;
height: 68px;
background-image: url("assets/logo_square.png");
background-size: cover;
background-position: center;
background-repeat: no-repeat;
border-radius: 17px;
position: relative;
z-index: 1;
}
.brand__wordmark {
font-family: "Montserrat", "Google Sans", sans-serif;
font-weight: 700;
font-size: 30px;
letter-spacing: -0.03em;
line-height: 1;
background: var(--brand-gradient);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
-webkit-text-fill-color: transparent;
position: relative;
z-index: 1;
}
.brand__tagline {
font-family: "Google Sans", sans-serif;
font-weight: 500;
font-size: 13px;
letter-spacing: 0.01em;
color: rgba(230, 224, 233, 0.9);
position: relative;
z-index: 1;
}
.install {
position: absolute;
/* Vertically centered in the gap between brand block (~151px) and notice (~292px). */
top: 174px;
left: 0;
right: 0;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
gap: 20px;
}
.slot {
width: var(--slot-size);
height: var(--slot-size);
border: none;
background: transparent;
flex-shrink: 0;
}
.arrow {
width: 44px;
height: 44px;
flex-shrink: 0;
color: rgba(230, 224, 233, 0.88);
display: flex;
align-items: center;
justify-content: center;
}
.arrow svg {
display: block;
width: 44px;
height: 44px;
}
.notice {
position: absolute;
left: 20px;
right: 20px;
bottom: calc(var(--window-chrome-bottom) + 16px);
z-index: 1;
text-align: center;
font-family: "Google Sans", sans-serif;
font-weight: 400;
font-size: 12px;
line-height: 1.4;
color: var(--on-surface-muted);
text-wrap: balance;
}
.notice strong {
font-weight: 600;
color: var(--on-surface);
}
.slot__label {
position: absolute;
display: inline-flex;
align-items: center;
justify-content: center;
font-family: "Google Sans", system-ui, sans-serif;
font-size: 13px;
font-weight: 500;
line-height: 1.2;
letter-spacing: 0.01em;
color: var(--primary-pill, #7e22ce);
text-align: center;
white-space: nowrap;
z-index: 3;
pointer-events: none;
box-sizing: border-box;
min-height: 26px;
padding: 5px 12px;
}
.slot__label::before {
content: "";
position: absolute;
inset: 0;
border-radius: 9999px;
background: var(--primary-pill, #7e22ce);
z-index: -1;
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+41
View File
@@ -0,0 +1,41 @@
# ProGuard specializes return types of @JvmMultifileClass actuals (VerifyError: Paragraph vs SkiaParagraph).
# Upstream: https://github.com/JetBrains/compose-multiplatform/pull/5652 (CMP-10488)
-keep,allowshrinking,allowobfuscation class **Kt__* { *; }
# Ktor ContentNegotiation JSON extension (ServiceLoader).
-keep class io.ktor.serialization.kotlinx.json.KotlinxSerializationJsonExtensionProvider { *; }
# Ktor CIO client engine (ServiceLoader).
-keep class io.ktor.client.engine.cio.CIOEngineContainer { *; }
# SQLite JDBC driver + JNI natives (ProGuard drops native methods otherwise).
-keepclasseswithmembernames class * {
native <methods>;
}
-keep class org.sqlite.** { *; }
# BouncyCastle security providers (ServiceLoader java.security.Provider).
-keep class org.bouncycastle.jce.provider.BouncyCastleProvider { *; }
-keep class org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider { *; }
# Cryptography provider (ServiceLoader).
-keep class dev.whyoleg.cryptography.providers.jdk.JdkCryptographyProviderContainer { *; }
# Coil fetchers/decoders registered via ServiceLoader (network + SVG).
-keep class coil3.network.ktor3.internal.KtorNetworkFetcherServiceLoaderTarget { *; }
-keep class coil3.svg.internal.SvgDecoderServiceLoaderTarget { *; }
# Compose Multiplatform generated resource accessors (logo, strings, fonts).
-keep class ru.fromchat.Drawable*_commonMainKt { *; }
-keep class ru.fromchat.String*_commonMainKt { *; }
-keep class ru.fromchat.Font*_commonMainKt { *; }
-keep class ru.fromchat.ActualResourceCollectorsKt { *; }
-keep class ru.fromchat.Res { *; }
-keep class ru.fromchat.Res$* { *; }
# App JSON models.
-keep @kotlinx.serialization.Serializable class ru.fromchat.** { *; }
-keepclassmembers @kotlinx.serialization.Serializable class ru.fromchat.** {
<fields>;
<init>(...);
}
@@ -0,0 +1,63 @@
@echo off
setlocal EnableExtensions
set "OUT_DIR=%~1"
set "SRC=%~2"
set "JAVA_HOME=%~3"
set "ARCH=%~4"
if /I "%ARCH%"=="arm64" (
set "VCVARS_NAME=vcvarsarm64.bat"
) else (
set "VCVARS_NAME=vcvars64.bat"
)
set "VCVARS="
if exist "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\%VCVARS_NAME%" (
set "VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\%VCVARS_NAME%"
)
if not defined VCVARS if exist "C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\%VCVARS_NAME%" (
set "VCVARS=C:\Program Files\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\%VCVARS_NAME%"
)
if not defined VCVARS if exist "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\%VCVARS_NAME%" (
set "VCVARS=C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\%VCVARS_NAME%"
)
if not defined VCVARS if exist "C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\%VCVARS_NAME%" (
set "VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\%VCVARS_NAME%"
)
if not defined VCVARS if exist "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\%VCVARS_NAME%" (
set "VCVARS=C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\%VCVARS_NAME%"
)
if not defined VCVARS (
for /f "delims=" %%i in ('where /r "C:\Program Files\Microsoft Visual Studio" %VCVARS_NAME% 2^>nul') do set "VCVARS=%%i"
)
if not defined VCVARS (
echo compile-windows-native: %VCVARS_NAME% not found >&2
exit /b 1
)
call "%VCVARS%"
if errorlevel 1 exit /b 1
if not exist "%OUT_DIR%" mkdir "%OUT_DIR%"
cd /d "%OUT_DIR%"
set "JNI_INCLUDE=%JAVA_HOME%\include"
set "JNI_WIN32=%JNI_INCLUDE%\win32"
cl /nologo /LD /EHsc /std:c++17 /utf-8 ^
/I"%JNI_INCLUDE%" /I"%JNI_WIN32%" ^
"%SRC%" /Fe:fromchat_windows.dll ^
/link windowsapp.lib user32.lib shell32.lib ole32.lib oleaut32.lib uxtheme.lib
if errorlevel 1 (
echo compile-windows-native: cl failed >&2
exit /b 1
)
if not exist "fromchat_windows.dll" (
echo compile-windows-native: missing fromchat_windows.dll in %OUT_DIR% >&2
exit /b 1
)
if exist "fromchat_windows.lib" del "fromchat_windows.lib"
if exist "fromchat_windows.exp" del "fromchat_windows.exp"
if exist "WindowsNativeBridge.obj" del "WindowsNativeBridge.obj"
exit /b 0
@@ -0,0 +1,91 @@
package ru.fromchat.desktop
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import ru.fromchat.Logger
import ru.fromchat.api.local.db.store.MessageDatabasePaths
import kotlin.time.Duration.Companion.milliseconds
object DatabaseLockGate {
private val _blocked = MutableStateFlow(false)
val blocked: StateFlow<Boolean> = _blocked.asStateFlow()
private val _processes = MutableStateFlow<List<LockingProcessInfo>>(emptyList())
val processes: StateFlow<List<LockingProcessInfo>> = _processes.asStateFlow()
private val _runtimeSqliteBusy = MutableStateFlow(false)
private var monitorJob: Job? = null
fun onSqliteBusy(throwable: Throwable?): Boolean {
Logger.w("DatabaseLockGate", "SQLite busy", throwable)
_runtimeSqliteBusy.value = true
return refreshBlockedState()
}
fun startMonitoring(scope: CoroutineScope, onUnlocked: () -> Unit) {
monitorJob?.cancel()
monitorJob = scope.launch {
var bootstrapDelivered = false
while (isActive) {
val blocked = refreshBlockedState()
if (!blocked && !bootstrapDelivered) {
bootstrapDelivered = true
onUnlocked()
}
if (!blocked && bootstrapDelivered) return@launch
delay(750.milliseconds)
}
}
}
fun killProcess(pid: Long): Boolean = DatabaseLockingProcessResolver.killProcess(pid)
fun releaseRuntimeLock() {
MessageDatabaseRuntimeLock.release()
}
private fun refreshBlockedState(): Boolean {
val externalProcesses = DatabaseLockingProcessResolver.findLockingProcesses(
MessageDatabasePaths.lockProbeFiles(),
)
if (!MessageDatabaseRuntimeLock.isHeld() && !MessageDatabaseRuntimeLock.tryAcquire()) {
Logger.w(
"DatabaseLockGate",
"Instance lock held by another process; blockers=$externalProcesses",
)
_blocked.value = true
_processes.value = externalProcesses
return true
}
if (externalProcesses.isNotEmpty()) {
Logger.w(
"DatabaseLockGate",
"Database files in use by other process(es): $externalProcesses",
)
_blocked.value = true
_processes.value = externalProcesses
return true
}
if (_runtimeSqliteBusy.value) {
Logger.i(
"DatabaseLockGate",
"SQLite busy with no external locker — treating as in-process contention, not blocking",
)
_runtimeSqliteBusy.value = false
}
_blocked.value = false
_processes.value = emptyList()
return false
}
}
@@ -0,0 +1,11 @@
package ru.fromchat.desktop
import androidx.compose.ui.graphics.ImageBitmap
data class LockingProcessInfo(
val pid: Long,
val name: String,
val description: String?,
val executablePath: String?,
val icon: ImageBitmap?,
)
@@ -0,0 +1,234 @@
package ru.fromchat.desktop
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialShapes
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.rememberWindowState
import org.jetbrains.compose.resources.stringResource
import ru.fromchat.Res
import ru.fromchat.desktop_database_locked_kill
import ru.fromchat.desktop_database_locked_message
import ru.fromchat.desktop_database_locked_pid
import ru.fromchat.desktop_database_locked_title
import ru.fromchat.desktop_database_locked_unknown_hint
import ru.fromchat.desktop_database_locked_waiting
import ru.fromchat.desktop_quit
import ru.fromchat.ui.components.ActionButton
import ru.fromchat.ui.components.ExpressiveIconFrame
import ru.fromchat.ui.components.Text
import ru.fromchat.ui.components.TextCta
import java.awt.image.BufferedImage
@Composable
fun DatabaseLockWindow(
appName: String,
windowIcon: Painter,
dockIconImage: BufferedImage?,
processes: List<LockingProcessInfo>,
onKillProcess: (Long) -> Unit,
onQuit: () -> Unit,
) {
val windows = remember { isWindowsOs() }
val windowState = rememberWindowState(width = 420.dp, height = 480.dp)
Window(
onCloseRequest = onQuit,
title = appName,
state = windowState,
icon = windowIcon,
undecorated = windows,
resizable = false,
) {
DesktopRootSurface(
appName = appName,
windowIcon = windowIcon,
dockIconImage = dockIconImage,
windows = windows,
windowState = windowState,
onCloseRequest = onQuit,
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(
top = if (windows) WindowsTitleBarHeight + 24.dp else 24.dp,
start = 32.dp,
end = 32.dp,
bottom = 24.dp,
),
contentAlignment = Alignment.Center,
) {
DatabaseLockContent(
processes = processes,
onKillProcess = onKillProcess,
onQuit = onQuit,
)
}
}
}
}
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
private fun DatabaseLockContent(
processes: List<LockingProcessInfo>,
onKillProcess: (Long) -> Unit,
onQuit: () -> Unit,
) {
Column(
modifier = Modifier
.widthIn(max = 360.dp)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp),
) {
ExpressiveIconFrame(
icon = Icons.Default.Warning,
containerSize = 56.dp,
iconSize = 28.dp,
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
materialPolygon = MaterialShapes.SoftBurst,
)
Text(
text = stringResource(Res.string.desktop_database_locked_title),
style = MaterialTheme.typography.headlineSmall,
textAlign = TextAlign.Center,
)
Text(
text = stringResource(Res.string.desktop_database_locked_message),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
if (processes.isNotEmpty()) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
processes.forEach { process ->
LockingProcessRow(
process = process,
onKill = { onKillProcess(process.pid) },
)
}
}
} else {
Text(
text = stringResource(Res.string.desktop_database_locked_unknown_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth(),
)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(modifier = Modifier.width(10.dp))
Text(
text = stringResource(Res.string.desktop_database_locked_waiting),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
TextCta(
onClick = onQuit,
modifier = Modifier.fillMaxWidth(),
) {
Text(
text = stringResource(Res.string.desktop_quit),
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
)
}
}
}
@Composable
private fun LockingProcessRow(
process: LockingProcessInfo,
onKill: () -> Unit,
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
if (process.icon != null) {
Image(
bitmap = process.icon,
contentDescription = null,
modifier = Modifier.size(36.dp),
)
} else {
Icon(
imageVector = Icons.Default.Warning,
contentDescription = null,
modifier = Modifier.size(36.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Spacer(modifier = Modifier.width(12.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = process.name,
style = MaterialTheme.typography.titleSmall,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
process.description?.let { description ->
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
}
if (process.pid > 0L) {
Text(
text = stringResource(Res.string.desktop_database_locked_pid, process.pid.toInt()),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (process.pid > 0L) {
Spacer(modifier = Modifier.width(8.dp))
ActionButton(onClick = onKill) {
Text(stringResource(Res.string.desktop_database_locked_kill))
}
}
}
}
@@ -0,0 +1,76 @@
package ru.fromchat.desktop
import java.io.File
import java.lang.ProcessHandle
import java.util.concurrent.TimeUnit
object DatabaseLockingProcessResolver {
fun findLockingProcesses(files: List<File>): List<LockingProcessInfo> {
val probeFiles = files
.map { file -> runCatching { file.canonicalFile }.getOrDefault(file) }
.distinctBy { it.absolutePath }
val discovered = when {
isWindowsOs() -> WindowsRestartManager.findLockingProcesses(probeFiles)
isMacOs() -> findWithLsof(probeFiles.filter { it.exists() })
isLinuxOs() -> findWithFuser(probeFiles.filter { it.exists() })
else -> emptyList()
}
return discovered
.distinctBy { it.pid }
.sortedBy { it.name.lowercase() }
}
fun killProcess(pid: Long): Boolean = ProcessExecutableResolver.killProcess(pid)
private fun findWithLsof(files: List<File>): List<LockingProcessInfo> {
val pids = linkedSetOf<Long>()
files.forEach { file ->
val process = runCatching {
ProcessBuilder("lsof", "-t", file.absolutePath)
.redirectErrorStream(true)
.start()
}.getOrNull() ?: return@forEach
process.waitFor(3, TimeUnit.SECONDS)
process.inputStream.bufferedReader().readLines()
.mapNotNull { it.trim().toLongOrNull() }
.forEach { pids += it }
}
return pids.mapNotNull { pidToLockingProcess(it) }
}
private fun findWithFuser(files: List<File>): List<LockingProcessInfo> {
val pids = linkedSetOf<Long>()
files.forEach { file ->
val process = runCatching {
ProcessBuilder("fuser", file.absolutePath)
.redirectErrorStream(true)
.start()
}.getOrNull() ?: return@forEach
process.waitFor(3, TimeUnit.SECONDS)
val output = process.inputStream.bufferedReader().readText()
output.split(Regex("\\s+"))
.mapNotNull { token -> token.trim().toLongOrNull() }
.forEach { pids += it }
}
return pids.mapNotNull { pidToLockingProcess(it) }
}
private fun pidToLockingProcess(pid: Long): LockingProcessInfo? {
if (pid == ProcessHandle.current().pid()) return null
val handle = ProcessHandle.of(pid)
if (handle.isEmpty) return null
val info = handle.get().info()
val command = info.command().orElse("")
val executable = ProcessExecutableResolver.executablePathForPid(pid)
val name = executable?.let { File(it).name }
?: command.substringBefore(' ').takeIf { it.isNotBlank() }
?: "PID $pid"
return LockingProcessInfo(
pid = pid,
name = name,
description = command.ifBlank { null },
executablePath = executable,
icon = ProcessExecutableResolver.iconForExecutable(executable),
)
}
}
@@ -0,0 +1,415 @@
package ru.fromchat.desktop
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.CloudSync
import androidx.compose.material.icons.filled.DesktopWindows
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import java.awt.AWTEvent
import java.awt.Point
import java.awt.SystemTray
import java.awt.Toolkit
import java.awt.TrayIcon
import java.awt.event.AWTEventListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowEvent
import java.awt.image.BufferedImage
import javax.swing.JFrame
import javax.swing.SwingUtilities
import kotlin.math.roundToInt
import ru.fromchat.ui.FromChatTheme
import ru.fromchat.ui.components.Text
import ru.fromchat.ui.isInsideWindow
internal enum class TrayConnectionStatus {
Connected,
Connecting,
Disconnected,
}
@Composable
internal fun DesktopTrayHost(
trayImage: BufferedImage,
tooltip: String,
statusLabel: String,
connectionStatus: TrayConnectionStatus,
showLabel: String,
aboutLabel: String,
quitLabel: String,
onShow: () -> Unit,
onAbout: () -> Unit,
onQuit: () -> Unit,
) {
var menuOpen by remember { mutableStateOf(false) }
var menuAnchor by remember { mutableStateOf<Point?>(null) }
val closeMenu = rememberUpdatedState { menuOpen = false }
val onShowState = rememberUpdatedState(onShow)
DisposableEffect(trayImage, tooltip) {
if (!SystemTray.isSupported()) {
onDispose {}
} else {
val trayIcon = TrayIcon(trayImage, tooltip)
trayIcon.isImageAutoSize = true
fun openMenu(event: MouseEvent) {
val screen = event.locationOnScreen
SwingUtilities.invokeLater {
menuAnchor = screen
menuOpen = true
}
}
val listener = object : MouseAdapter() {
override fun mouseClicked(event: MouseEvent) {
if (MouseEvent.BUTTON1 == event.button && event.clickCount == 1) {
SwingUtilities.invokeLater { onShowState.value() }
}
}
override fun mousePressed(event: MouseEvent) {
if (event.isPopupTrigger) {
event.consume()
}
}
override fun mouseReleased(event: MouseEvent) {
if (event.isPopupTrigger) {
openMenu(event)
}
}
}
trayIcon.addMouseListener(listener)
val tray = SystemTray.getSystemTray()
runCatching { tray.add(trayIcon) }
onDispose {
trayIcon.removeMouseListener(listener)
runCatching { tray.remove(trayIcon) }
}
}
}
if (menuOpen) {
val density = LocalDensity.current
var contentSizePx by remember { mutableStateOf(IntSize.Zero) }
var showWindow by remember { mutableStateOf(false) }
val windowState = rememberWindowState(
width = 220.dp,
height = 260.dp,
position = WindowPosition((-20_000).dp, (-20_000).dp),
)
Window(
onCloseRequest = { menuOpen = false },
state = windowState,
title = "",
undecorated = true,
transparent = false,
resizable = false,
alwaysOnTop = true,
focusable = true,
onPreviewKeyEvent = { event ->
if (event.type == KeyEventType.KeyDown && event.key == Key.Escape) {
menuOpen = false
true
} else {
false
}
},
) {
val awtWindow = window
SideEffect {
if (!showWindow) {
awtWindow.isVisible = false
}
}
DisposableEffect(awtWindow) {
showWindow = false
awtWindow.isVisible = false
awtWindow.setLocation(-20_000, -20_000)
val dismiss = { SwingUtilities.invokeLater { closeMenu.value() } }
val toolkit = Toolkit.getDefaultToolkit()
var armed = false
val armTimer = javax.swing.Timer(200) { armed = true }.apply {
isRepeats = false
start()
}
val dismissListener = AWTEventListener { event ->
when (event.id) {
MouseEvent.MOUSE_RELEASED -> armed = true
MouseEvent.MOUSE_PRESSED -> {
if (!armed) return@AWTEventListener
val mouse = event as MouseEvent
if (mouse.button != MouseEvent.BUTTON1) return@AWTEventListener
if (mouse.isInsideWindow(awtWindow)) return@AWTEventListener
dismiss()
}
}
}
var focusDismissArmed = false
val focusArmTimer = javax.swing.Timer(250) { focusDismissArmed = true }.apply {
isRepeats = false
start()
}
val focusListener = object : java.awt.event.WindowFocusListener {
override fun windowGainedFocus(event: WindowEvent) = Unit
override fun windowLostFocus(event: WindowEvent) {
if (focusDismissArmed) {
dismiss()
}
}
}
toolkit.addAWTEventListener(dismissListener, AWTEvent.MOUSE_EVENT_MASK)
awtWindow.addWindowFocusListener(focusListener)
onDispose {
armTimer.stop()
focusArmTimer.stop()
toolkit.removeAWTEventListener(dismissListener)
awtWindow.removeWindowFocusListener(focusListener)
}
}
LaunchedEffect(contentSizePx, menuAnchor) {
val anchor = menuAnchor
if (anchor == null || contentSizePx.width < 80 || contentSizePx.height < 40) {
showWindow = false
awtWindow.isVisible = false
return@LaunchedEffect
}
val scale = density.density
val awtWidth = (contentSizePx.width / scale).roundToInt().coerceAtLeast(1)
val awtHeight = (contentSizePx.height / scale).roundToInt().coerceAtLeast(1)
val screen = awtWindow.graphicsConfiguration.bounds
val x = (anchor.x - awtWidth).coerceIn(
screen.x,
(screen.x + screen.width - awtWidth).coerceAtLeast(screen.x),
)
val y = (anchor.y - awtHeight).coerceIn(
screen.y,
(screen.y + screen.height - awtHeight).coerceAtLeast(screen.y),
)
awtWindow.setSize(awtWidth, awtHeight)
awtWindow.setLocation(x, y)
with(density) {
windowState.position = WindowPosition(
x = (x / density.density).dp,
y = (y / density.density).dp,
)
windowState.size = DpSize(
width = contentSizePx.width.toDp(),
height = contentSizePx.height.toDp(),
)
}
excludeFromWindowsTaskbar(awtWindow)
showWindow = true
awtWindow.isVisible = true
awtWindow.toFront()
awtWindow.requestFocus()
}
Box(
modifier = Modifier
.wrapContentSize(unbounded = true)
.onSizeChanged { size ->
if (size.width > 0 && size.height > 0) {
contentSizePx = size
}
},
) {
FromChatTheme(darkTheme = desktopAppDarkTheme(), dynamicColor = false) {
val surfaceColor = MaterialTheme.colorScheme.surfaceContainerHigh
SideEffect {
val awtColor = java.awt.Color(
surfaceColor.red,
surfaceColor.green,
surfaceColor.blue,
surfaceColor.alpha,
)
awtWindow.background = awtColor
(awtWindow as? JFrame)?.contentPane?.background = awtColor
}
DesktopTrayMenuContent(
statusLabel = statusLabel,
connectionStatus = connectionStatus,
showLabel = showLabel,
aboutLabel = aboutLabel,
quitLabel = quitLabel,
onShow = {
menuOpen = false
onShow()
},
onAbout = {
menuOpen = false
onAbout()
},
onQuit = {
menuOpen = false
onQuit()
},
)
}
}
}
}
}
@Composable
private fun DesktopTrayMenuContent(
statusLabel: String,
connectionStatus: TrayConnectionStatus,
showLabel: String,
aboutLabel: String,
quitLabel: String,
onShow: () -> Unit,
onAbout: () -> Unit,
onQuit: () -> Unit,
) {
val statusIcon = when (connectionStatus) {
TrayConnectionStatus.Connected -> Icons.Filled.CloudDone
TrayConnectionStatus.Connecting -> Icons.Filled.CloudSync
TrayConnectionStatus.Disconnected -> Icons.Filled.CloudOff
}
val statusTint = when (connectionStatus) {
TrayConnectionStatus.Connected -> MaterialTheme.colorScheme.primary
TrayConnectionStatus.Connecting -> MaterialTheme.colorScheme.onSurfaceVariant
TrayConnectionStatus.Disconnected -> MaterialTheme.colorScheme.error
}
Column(
modifier = Modifier
.width(IntrinsicSize.Max)
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
.border(1.dp, MaterialTheme.colorScheme.outlineVariant)
.padding(vertical = 2.dp),
) {
DesktopTrayMenuRow(
text = statusLabel,
icon = statusIcon,
iconTint = statusTint,
enabled = false,
onClick = {},
)
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
DesktopTrayMenuRow(
text = showLabel,
icon = Icons.Filled.DesktopWindows,
onClick = onShow,
)
DesktopTrayMenuRow(
text = aboutLabel,
icon = Icons.Filled.Info,
onClick = onAbout,
)
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
DesktopTrayMenuRow(
text = quitLabel,
icon = Icons.AutoMirrored.Filled.Logout,
textColor = MaterialTheme.colorScheme.error,
iconTint = MaterialTheme.colorScheme.error,
onClick = onQuit,
)
}
}
@Composable
private fun DesktopTrayMenuRow(
text: String,
icon: ImageVector,
enabled: Boolean = true,
textColor: Color = MaterialTheme.colorScheme.onSurface,
iconTint: Color = textColor,
onClick: () -> Unit,
) {
val interactionSource = remember { MutableInteractionSource() }
val hovered by interactionSource.collectIsHoveredAsState()
val resolvedTextColor = when {
!enabled -> MaterialTheme.colorScheme.onSurfaceVariant
else -> textColor
}
val resolvedIconTint = when {
!enabled -> iconTint.copy(alpha = 0.7f)
else -> iconTint
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(
if (enabled && hovered) {
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f)
} else {
Color.Transparent
},
)
.hoverable(interactionSource, enabled = enabled)
.clickable(
interactionSource = interactionSource,
indication = null,
enabled = enabled,
onClick = onClick,
)
.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(18.dp),
tint = resolvedIconTint,
)
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
color = resolvedTextColor,
)
}
}
@@ -0,0 +1,70 @@
package ru.fromchat.desktop
import ru.fromchat.config.Settings
import ru.fromchat.ui.Theme
import javax.swing.JRootPane
internal fun isMacOs(): Boolean =
System.getProperty("os.name").orEmpty().lowercase().contains("mac")
internal fun isWindowsOs(): Boolean =
System.getProperty("os.name").orEmpty().lowercase().contains("win")
internal fun isLinuxOs(): Boolean =
System.getProperty("os.name").orEmpty().lowercase().contains("linux")
internal fun isWindowsArm64(): Boolean {
if (!isWindowsOs()) return false
val arch = System.getProperty("os.arch").orEmpty().lowercase()
return arch.contains("aarch64") || arch.contains("arm64")
}
internal fun desktopAppDarkTheme(): Boolean =
when (runCatching { Settings.theme }.getOrDefault(Theme.AsSystem)) {
Theme.Dark -> true
Theme.Light -> false
Theme.AsSystem -> desktopSystemDarkTheme()
}
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()
else -> false
}
}.getOrDefault(false)
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
}
}
/** Enables drawing under the system title bar on macOS. */
internal fun applyDesktopEdgeToEdgeChrome(rootPane: JRootPane) {
if (!isMacOs()) return
rootPane.putClientProperty("apple.awt.fullWindowContent", true)
rootPane.putClientProperty("apple.awt.transparentTitleBar", true)
rootPane.putClientProperty("apple.awt.windowTitleVisible", false)
}
@@ -0,0 +1,118 @@
package ru.fromchat.desktop
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.FrameWindowScope
import androidx.compose.ui.window.WindowExceptionHandler
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.zIndex
import androidx.compose.ui.awt.ComposeWindow
import ru.fromchat.Logger
import ru.fromchat.api.local.db.isSqliteBusy
import ru.fromchat.ui.FromChatTheme
import ru.fromchat.ui.LocalExtraStatusBarTop
import ru.fromchat.ui.getColorScheme
import java.awt.image.BufferedImage
internal fun desktopThemeBackgroundCompose(): Color =
if (desktopAppDarkTheme()) Color(0xFF1C1B1F) else Color(0xFFFFFBFE)
@OptIn(ExperimentalComposeUiApi::class)
internal fun installDesktopWindowExceptionHandler(window: ComposeWindow) {
window.exceptionHandler = WindowExceptionHandler { throwable ->
if (isSqliteBusy(throwable)) {
if (!DatabaseLockGate.onSqliteBusy(throwable)) {
Logger.w("DesktopWindow", "Suppressed SQLITE_BUSY in composition", throwable)
}
} else {
Logger.e("DesktopWindow", "uncaught in composition", throwable)
}
}
}
@Composable
internal fun FrameWindowScope.DesktopRootSurface(
appName: String,
windowIcon: Painter,
dockIconImage: BufferedImage?,
windows: Boolean,
windowState: WindowState,
onCloseRequest: () -> Unit,
content: @Composable () -> Unit,
) {
val windowChrome = desktopThemeBackgroundCompose()
LaunchedEffect(window, appName, windowChrome) {
window.title = appName
windowChrome.toAwtColor().also {
window.background = it
window.contentPane.background = it
if (windows) {
updateWindowsNativeCaptionBackground(window, it)
}
}
if (windows) {
installWindowsNativeCaptionChrome(window)
applyWindowsRoundedCorners(window)
}
applyDesktopEdgeToEdgeChrome(window.rootPane)
dockIconImage?.let { image ->
window.iconImages = listOf(image)
applyDockIcon(image)
}
}
DisposableEffect(window) {
installDesktopWindowExceptionHandler(window)
onDispose {}
}
FromChatTheme(darkTheme = desktopAppDarkTheme()) {
CompositionLocalProvider(
LocalExtraStatusBarTop provides when {
windows -> WindowsTitleBarHeight
else -> 0.dp
},
) {
Box(
Modifier
.fillMaxSize()
.background(windowChrome),
) {
content()
if (windows) {
MaterialTheme(colorScheme = getColorScheme(desktopAppDarkTheme(), dynamicColor = false)) {
WindowsDesktopTitleBar(
title = appName,
windowIcon = windowIcon,
window = window,
windowState = windowState,
onCloseRequest = onCloseRequest,
modifier = Modifier
.align(Alignment.TopStart)
.fillMaxWidth()
.zIndex(10_000f),
)
}
}
}
}
}
}
private fun Color.toAwtColor() =
java.awt.Color(red, green, blue, alpha)
@@ -0,0 +1,53 @@
package ru.fromchat.desktop
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.WindowPosition
import java.util.prefs.Preferences
/**
* Desktop main-window size and position prefs.
*
* Stored in the same JVM prefs node as PlatformSettings (`ru.fromchat.settings`):
* - `desktop_window_width` / `desktop_window_height` (float dp)
* - `desktop_window_x` / `desktop_window_y` (float dp, absolute; absent platform default)
*
* Listdetail left pane width uses the sibling key `desktop_list_pane_width`
* (see [ru.fromchat.ui.main.ConversationListDetailShell]).
*/
internal object DesktopWindowPrefs {
private const val WIDTH_KEY = "desktop_window_width"
private const val HEIGHT_KEY = "desktop_window_height"
private const val X_KEY = "desktop_window_x"
private const val Y_KEY = "desktop_window_y"
private val prefs: Preferences =
Preferences.userRoot().node("ru.fromchat.settings")
fun loadSize(): DpSize {
val width = prefs.getFloat(WIDTH_KEY, 0f)
val height = prefs.getFloat(HEIGHT_KEY, 0f)
return if (width <= 0f || height <= 0f) {
DpSize(800.dp, 600.dp)
} else {
DpSize(width.dp, height.dp)
}
}
fun loadPosition(): WindowPosition {
if (prefs.get(X_KEY, null) == null || prefs.get(Y_KEY, null) == null) {
return WindowPosition.PlatformDefault
}
return WindowPosition(prefs.getFloat(X_KEY, 0f).dp, prefs.getFloat(Y_KEY, 0f).dp)
}
fun save(size: DpSize, position: WindowPosition) {
prefs.putFloat(WIDTH_KEY, size.width.value)
prefs.putFloat(HEIGHT_KEY, size.height.value)
if (position is WindowPosition.Absolute) {
prefs.putFloat(X_KEY, position.x.value)
prefs.putFloat(Y_KEY, position.y.value)
}
runCatching { prefs.flush() }
}
}
@@ -0,0 +1,19 @@
package ru.fromchat.desktop
/**
* macOS close-to-background policy notes (implemented in [MainKt] / tray close handler).
*
* ## Window close background (not quit)
* The red traffic-light / window close hides the main window and keeps the JVM process
* plus menu-bar tray alive (close-to-tray). Quit is only via tray Quit, File Quit, or Q.
* Dock icon stays (NSApplicationActivationPolicyRegular) so macOS can show the Dock
* "Running in Background" indicator when no windows are visible.
*
* ## No Login Item / SMAppService
* We intentionally do **not** register `SMAppService.mainAppService` (Open at Login /
* Login Items & Extensions). Close-to-tray does not require that registration; the process
* simply stays alive with a menu-bar tray while the window is hidden.
*/
internal object MacBackgroundLifecycle {
const val LOG_TAG = "MacBackground"
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
package ru.fromchat.desktop
import ru.fromchat.api.local.db.store.MessageDatabasePaths
import java.io.File
import java.io.RandomAccessFile
import java.nio.channels.FileLock
/**
* Holds an exclusive lock on a sidecar file for the lifetime of this process so only one
* desktop instance can use the message database at a time.
*/
internal object MessageDatabaseRuntimeLock {
private var lockHolder: RandomAccessFile? = null
private var fileLock: FileLock? = null
fun isHeld(): Boolean = fileLock?.isValid == true
fun tryAcquire(): Boolean {
if (isHeld()) return true
val lockFile = instanceLockFile()
lockFile.parentFile?.mkdirs()
return runCatching {
val raf = RandomAccessFile(lockFile, "rw")
val lock = raf.channel.tryLock()
if (lock == null) {
raf.close()
false
} else {
lockHolder = raf
fileLock = lock
true
}
}.getOrDefault(false)
}
fun release() {
runCatching { fileLock?.release() }
runCatching { lockHolder?.close() }
fileLock = null
lockHolder = null
}
private fun instanceLockFile(): File {
val dbDir = MessageDatabasePaths.databaseFile().parentFile
return File(dbDir, "message_database.instance.lock")
}
}
@@ -0,0 +1,74 @@
package ru.fromchat.desktop
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.toComposeImageBitmap
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.File
import java.lang.ProcessHandle
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.filechooser.FileSystemView
import org.jetbrains.skia.Image as SkiaImage
internal object ProcessExecutableResolver {
fun executablePathForPid(pid: Long): String? {
if (pid <= 0L) return null
return runCatching {
ProcessHandle.of(pid).flatMap { handle ->
handle.info().command().map { command ->
extractExecutablePath(command)
}
}.orElse(null)
}.getOrNull()
}
fun commandLineForPid(pid: Long): String? {
if (pid <= 0L) return null
return runCatching {
ProcessHandle.of(pid).flatMap { it.info().command() }.orElse(null)
}.getOrNull()
}
fun iconForExecutable(path: String?): ImageBitmap? {
if (path.isNullOrBlank()) return null
val file = File(path)
if (!file.exists()) return null
val awtIcon = runCatching {
val icon = FileSystemView.getFileSystemView().getSystemIcon(file)
when (icon) {
is ImageIcon -> icon.image as? BufferedImage
else -> null
}
}.getOrNull() ?: return null
return bufferedImageToImageBitmap(awtIcon)
}
private fun bufferedImageToImageBitmap(image: BufferedImage): ImageBitmap {
val bytes = ByteArrayOutputStream().use { out ->
ImageIO.write(image, "png", out)
out.toByteArray()
}
return SkiaImage.makeFromEncoded(bytes).toComposeImageBitmap()
}
private fun extractExecutablePath(command: String): String? {
val trimmed = command.trim()
if (trimmed.isEmpty()) return null
if (trimmed.first() == '"') {
val end = trimmed.indexOf('"', startIndex = 1)
if (end > 1) return trimmed.substring(1, end)
}
return trimmed.substringBefore(' ').takeIf { it.isNotBlank() }
}
fun killProcess(pid: Long): Boolean {
if (pid <= 0L) return false
val handle = ProcessHandle.of(pid)
if (handle.isEmpty) return false
return runCatching {
handle.get().destroyForcibly()
true
}.getOrDefault(false)
}
}
@@ -0,0 +1,14 @@
package ru.fromchat.desktop
import com.sun.jna.WString
import com.sun.jna.platform.win32.Shell32
/** Taskbar / jump-list identity for the desktop app (must run before first window). */
internal fun setWindowsDesktopAppUserModelId(registrationId: String) {
if (!isWindowsOs()) return
val id = when (registrationId) {
"FromChat Beta" -> "denis0001-dev.FromChat.Beta"
else -> "denis0001-dev.FromChat"
}
Shell32.INSTANCE.SetCurrentProcessExplicitAppUserModelID(WString(id))
}
@@ -0,0 +1,238 @@
package ru.fromchat.desktop
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowScope
import androidx.compose.ui.window.WindowState
import java.awt.Window
import ru.fromchat.ui.components.Text
/** Height of the custom Windows title bar; keep in sync with [ru.fromchat.ui.LocalExtraStatusBarTop]. */
val WindowsTitleBarHeight = 32.dp
private val TitleBarHoverAlpha = 0.28f
private val TitleBarPressAlpha = 0.36f
private val TitleBarCloseHoverAlpha = 1f
@Composable
fun WindowScope.WindowsDesktopTitleBar(
title: String,
windowIcon: Painter,
window: Window,
windowState: WindowState,
onCloseRequest: () -> Unit,
modifier: Modifier = Modifier,
) {
window.syncWindowsPlacementFromNative(windowState)
val windowActive = rememberWindowsFrameActive(window)
val isMaximized = windowState.placement == WindowPlacement.Maximized
val scheme = MaterialTheme.colorScheme
val titleColor =
if (windowActive) {
Color.White
} else {
Color.White.copy(alpha = 0.63f)
}
Row(
modifier
.fillMaxWidth()
.height(WindowsTitleBarHeight),
verticalAlignment = Alignment.CenterVertically,
) {
WindowDraggableArea(
modifier = Modifier
.weight(1f)
.fillMaxHeight(),
) {
Row(
Modifier
.fillMaxHeight()
.padding(start = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Image(
painter = windowIcon,
contentDescription = null,
modifier = Modifier.size(16.dp),
alpha = if (windowActive) 1f else 0.63f,
)
Text(
text = title,
style = MaterialTheme.typography.titleSmall,
color = titleColor,
modifier = Modifier.padding(start = 8.dp),
)
}
}
TitleBarWindowButton(
onClick = { window.windowsMinimize() },
windowActive = windowActive,
isClose = false,
) {
TitleBarRemoveIcon(tint = it)
}
TitleBarWindowButton(
onClick = { window.windowsToggleMaximize(windowState) },
windowActive = windowActive,
isClose = false,
) {
if (isMaximized) {
TitleBarRestoreIcon(tint = it)
} else {
TitleBarMaximizeIcon(tint = it)
}
}
TitleBarWindowButton(
onClick = onCloseRequest,
windowActive = windowActive,
isClose = true,
) {
TitleBarCloseIcon(tint = it)
}
}
}
@Composable
private fun TitleBarWindowButton(
onClick: () -> Unit,
windowActive: Boolean,
isClose: Boolean,
icon: @Composable (Color) -> Unit,
) {
val interactionSource = remember { MutableInteractionSource() }
val hovered by interactionSource.collectIsHoveredAsState()
val pressed by interactionSource.collectIsPressedAsState()
val scheme = MaterialTheme.colorScheme
val iconTint = when {
isClose && (hovered || pressed) -> scheme.onError
windowActive -> Color.White
else -> Color.White.copy(alpha = 0.63f)
}
val hoverAlpha = when {
isClose && (hovered || pressed) -> TitleBarCloseHoverAlpha
pressed -> TitleBarPressAlpha
hovered -> TitleBarHoverAlpha
else -> 0f
}
val hoverColor =
if (isClose && (hovered || pressed)) {
scheme.error
} else {
scheme.onSurface
}
Box(
modifier = Modifier
.width(46.dp)
.fillMaxHeight()
.clip(RoundedCornerShape(0.dp))
.hoverable(interactionSource)
.background(hoverColor.copy(alpha = hoverAlpha))
.clickable(
interactionSource = interactionSource,
indication = null,
onClick = onClick,
),
contentAlignment = Alignment.Center,
) {
icon(iconTint)
}
}
@Composable
private fun TitleBarRemoveIcon(tint: Color) {
Canvas(Modifier.size(16.dp)) {
val y = size.height / 2f
val pad = size.width * 0.22f
drawLine(
color = tint,
start = Offset(pad, y),
end = Offset(size.width - pad, y),
strokeWidth = size.height * 0.06f,
)
}
}
@Composable
private fun TitleBarCloseIcon(tint: Color) {
Canvas(Modifier.size(16.dp)) {
val pad = size.width * 0.28f
val stroke = size.height * 0.06f
drawLine(color = tint, start = Offset(pad, pad), end = Offset(size.width - pad, size.height - pad), strokeWidth = stroke)
drawLine(color = tint, start = Offset(size.width - pad, pad), end = Offset(pad, size.height - pad), strokeWidth = stroke)
}
}
/** Material `select_window_2` — rounded maximize tile. */
@Composable
private fun TitleBarMaximizeIcon(tint: Color) {
Canvas(Modifier.size(16.dp)) {
val inset = size.width * 0.24f
val stroke = size.height * 0.06f
val corner = size.width * 0.12f
drawRoundRect(
color = tint,
topLeft = Offset(inset, inset),
size = Size(size.width - inset * 2f, size.height - inset * 2f),
cornerRadius = CornerRadius(corner, corner),
style = Stroke(width = stroke),
)
}
}
/** Restored-from-maximize: overlapping rounded tiles. */
@Composable
private fun TitleBarRestoreIcon(tint: Color) {
Canvas(Modifier.size(16.dp)) {
val stroke = size.height * 0.06f
val corner = size.width * 0.1f
val backSize = size.width * 0.46f
val frontSize = size.width * 0.52f
drawRoundRect(
color = tint,
topLeft = Offset(size.width * 0.28f, size.height * 0.16f),
size = Size(backSize, backSize),
cornerRadius = CornerRadius(corner, corner),
style = Stroke(width = stroke),
)
drawRoundRect(
color = tint,
topLeft = Offset(size.width * 0.2f, size.height * 0.28f),
size = Size(frontSize, frontSize),
cornerRadius = CornerRadius(corner, corner),
style = Stroke(width = stroke),
)
}
}
@@ -0,0 +1,47 @@
package ru.fromchat.desktop
import com.sun.jna.Library
import com.sun.jna.Memory
import com.sun.jna.Native
import com.sun.jna.platform.win32.WinDef.HWND
import java.awt.Window
private const val DWMWA_TRANSITIONS_FORCEDISABLED = 3
private const val DWMWA_WINDOW_CORNER_PREFERENCE = 33
private const val DWMWCP_ROUND = 2
private interface DwmapiLib : Library {
fun DwmSetWindowAttribute(
hwnd: HWND,
dwAttribute: Int,
pvAttribute: Memory,
cbAttribute: Int,
): Int
companion object {
val INSTANCE: DwmapiLib = Native.load("dwmapi", DwmapiLib::class.java)
}
}
/** Opt in to Windows 11 rounded window corners for undecorated custom chrome. */
internal fun applyWindowsRoundedCorners(window: Window) {
if (!isWindowsOs()) return
val hwnd = window.windowsHwnd()
if (hwnd.pointer == null) return
setDwmInt(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND)
setDwmInt(hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, 0)
}
internal fun setDwmTransitionsForcedDisabled(hwnd: HWND, disabled: Boolean) {
setDwmInt(hwnd, DWMWA_TRANSITIONS_FORCEDISABLED, if (disabled) 1 else 0)
}
private fun setDwmInt(hwnd: HWND, attribute: Int, value: Int) {
val memory = Memory(4)
memory.setInt(0, value)
DwmapiLib.INSTANCE.DwmSetWindowAttribute(hwnd, attribute, memory, 4)
}
internal fun applyWindowsRoundedCorners(composeWindow: androidx.compose.ui.awt.ComposeWindow) {
applyWindowsRoundedCorners(composeWindow as Window)
}
@@ -0,0 +1,87 @@
package ru.fromchat.desktop
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowState
import com.sun.jna.platform.win32.User32
import com.sun.jna.platform.win32.WinDef.LPARAM
import com.sun.jna.platform.win32.WinDef.WPARAM
import com.sun.jna.platform.win32.WinUser
import java.awt.Frame
import java.awt.Window
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.awt.event.WindowStateListener
/** Tracks whether the AWT frame is the active (foreground) window. */
@Composable
internal fun rememberWindowsFrameActive(window: Window): Boolean {
var active by remember(window) {
mutableStateOf(window.isActive)
}
DisposableEffect(window) {
val listener = object : WindowAdapter() {
override fun windowActivated(event: WindowEvent?) {
active = true
}
override fun windowDeactivated(event: WindowEvent?) {
active = false
}
}
window.addWindowListener(listener)
active = window.isActive
onDispose { window.removeWindowListener(listener) }
}
return active
}
internal fun Window.windowsMinimize() {
User32.INSTANCE.SendMessage(
windowsHwnd(),
WinUser.WM_SYSCOMMAND,
WPARAM(SC_MINIMIZE),
LPARAM(0),
)
}
internal fun Window.windowsToggleMaximize(windowState: WindowState) {
val hwnd = windowsHwnd()
if (hwnd.isNativeZoomed() || windowState.placement == WindowPlacement.Maximized) {
User32.INSTANCE.SendMessage(hwnd, WinUser.WM_SYSCOMMAND, WPARAM(SC_RESTORE), LPARAM(0))
windowState.placement = WindowPlacement.Floating
} else {
User32.INSTANCE.SendMessage(hwnd, WinUser.WM_SYSCOMMAND, WPARAM(SC_MAXIMIZE), LPARAM(0))
windowState.placement = WindowPlacement.Maximized
}
}
@Composable
internal fun Window.syncWindowsPlacementFromNative(windowState: WindowState) {
DisposableEffect(this, windowState) {
val frame = this@syncWindowsPlacementFromNative as? Frame
if (frame == null) {
onDispose {}
} else {
val listener = WindowStateListener { event ->
windowState.placement =
if (event.newState and Frame.MAXIMIZED_BOTH != 0) {
WindowPlacement.Maximized
} else {
WindowPlacement.Floating
}
}
frame.addWindowStateListener(listener)
onDispose { frame.removeWindowStateListener(listener) }
}
}
}
private const val SC_MINIMIZE = 0xF020L
private const val SC_MAXIMIZE = 0xF030L
private const val SC_RESTORE = 0xF120L
@@ -0,0 +1,251 @@
package ru.fromchat.desktop
import androidx.compose.ui.awt.ComposeWindow
import com.sun.jna.Native
import com.sun.jna.NativeLibrary
import com.sun.jna.Pointer
import com.sun.jna.platform.win32.BaseTSD.LONG_PTR
import com.sun.jna.platform.win32.User32
import com.sun.jna.platform.win32.WinDef.HWND
import com.sun.jna.platform.win32.WinDef.LPARAM
import com.sun.jna.platform.win32.WinDef.LRESULT
import com.sun.jna.platform.win32.WinDef.RECT
import com.sun.jna.platform.win32.WinDef.WPARAM
import com.sun.jna.platform.win32.WinUser
import com.sun.jna.platform.win32.WinUser.WindowProc
import com.sun.jna.win32.W32APIOptions
import java.awt.Color
import java.awt.Window
import javax.swing.JFrame
private const val ChromeKey = "fromchat.windowsNativeChrome"
private const val ChromeBackgroundKey = "fromchat.windowsNativeChromeBackground"
private const val WM_NCCALCSIZE = 0x0083
private const val WM_ERASEBKGND = 0x0014
private const val GWLP_WNDPROC = -4
/**
* Makes the undecorated Compose window look borderless while remaining an overlapped
* Win32 window, so maximize/minimize use DWM animations and maximize to the work area.
*
* [undecorated][androidx.compose.ui.window.Window] creates a `WS_POPUP` window. Popup
* maximize is fullscreen (no animation). Restoring `WS_CAPTION` and handling
* `WM_NCCALCSIZE` is the same approach as FlatLaf native decorations and
* rossy/borderless-window.
*/
internal fun installWindowsNativeCaptionChrome(window: Window) {
if (!isWindowsOs()) return
val frame = window as? JFrame ?: return
if (frame.rootPane.getClientProperty(ChromeKey) != null) return
val hwnd = window.windowsHwnd()
if (hwnd.pointer == null) return
val background = frame.background ?: Color(0x1C, 0x1B, 0x1F)
frame.rootPane.putClientProperty(ChromeBackgroundKey, background)
frame.rootPane.putClientProperty(ChromeKey, WindowsCaptionWndProc(hwnd, background))
}
internal fun updateWindowsNativeCaptionBackground(window: Window, background: Color) {
if (!isWindowsOs()) return
val frame = window as? JFrame ?: return
frame.rootPane.putClientProperty(ChromeBackgroundKey, background)
(frame.rootPane.getClientProperty(ChromeKey) as? WindowsCaptionWndProc)?.background = background
}
private const val GwlExStyle = -20
private const val WsExToolWindow = 0x00000080
private const val WsExAppWindow = 0x00040000
/** Keeps transient popups (tray menu, etc.) out of the Windows taskbar and Alt+Tab. */
internal fun excludeFromWindowsTaskbar(window: Window) {
if (!isWindowsOs()) return
val hwnd = window.windowsHwnd()
if (hwnd.pointer == null) return
val exStyle = User32.INSTANCE.GetWindowLong(hwnd, GwlExStyle)
User32.INSTANCE.SetWindowLong(
hwnd,
GwlExStyle,
(exStyle or WsExToolWindow) and WsExAppWindow.inv(),
)
User32.INSTANCE.SetWindowPos(
hwnd,
null,
0,
0,
0,
0,
WinUser.SWP_NOMOVE or
WinUser.SWP_NOSIZE or
WinUser.SWP_NOZORDER or
WinUser.SWP_NOACTIVATE or
WinUser.SWP_FRAMECHANGED,
)
}
internal fun Window.windowsHwnd(): HWND {
val handle = (this as? ComposeWindow)?.windowHandle ?: 0L
return if (handle != 0L) {
HWND(Pointer(handle))
} else {
HWND(Native.getComponentPointer(this))
}
}
internal fun HWND.isNativeZoomed(): Boolean =
User32.INSTANCE.GetWindowLong(this, WinUser.GWL_STYLE) and WS_MAXIMIZE != 0
internal fun Window.isNativeZoomed(): Boolean = windowsHwnd().isNativeZoomed()
private const val WS_MAXIMIZE = 0x01000000
@Suppress("FunctionName")
private interface User32Ex : User32 {
fun SetWindowLong(hWnd: HWND, nIndex: Int, wndProc: WindowProc): LONG_PTR
fun SetWindowLongPtr(hWnd: HWND, nIndex: Int, wndProc: WindowProc): LONG_PTR
fun CallWindowProc(proc: LONG_PTR, hWnd: HWND, uMsg: Int, wParam: WPARAM, lParam: LPARAM): LRESULT
}
private class WindowsCaptionWndProc(
private val hwnd: HWND,
@Volatile var background: Color,
) : WindowProc {
private val user32 = runCatching {
Native.load("user32", User32Ex::class.java, W32APIOptions.DEFAULT_OPTIONS)
}.getOrNull()
private val defaultWndProc = when {
user32 == null -> LONG_PTR(-1)
is64Bit() -> user32.SetWindowLongPtr(hwnd, GWLP_WNDPROC, this)
else -> user32.SetWindowLong(hwnd, GWLP_WNDPROC, this)
}
init {
val style = User32.INSTANCE.GetWindowLong(hwnd, WinUser.GWL_STYLE)
User32.INSTANCE.SetWindowLong(
hwnd,
WinUser.GWL_STYLE,
style and WinUser.WS_POPUP.inv() or
WinUser.WS_CAPTION or
WinUser.WS_THICKFRAME or
WinUser.WS_SYSMENU or
WinUser.WS_MINIMIZEBOX or
WinUser.WS_MAXIMIZEBOX,
)
extendFrameIntoClientArea(hwnd)
setDwmTransitionsForcedDisabled(hwnd, disabled = false)
User32.INSTANCE.SetWindowPos(
hwnd,
null,
0,
0,
0,
0,
WinUser.SWP_NOMOVE or
WinUser.SWP_NOSIZE or
WinUser.SWP_NOZORDER or
WinUser.SWP_NOACTIVATE or
WinUser.SWP_FRAMECHANGED,
)
}
override fun callback(hWnd: HWND, uMsg: Int, wParam: WPARAM, lParam: LPARAM): LRESULT =
when (uMsg) {
WM_ERASEBKGND -> {
eraseClientBackground(wParam)
LRESULT(1)
}
WM_NCCALCSIZE -> handleNcCalcSize(hWnd, wParam, lParam)
else -> callDefault(hWnd, uMsg, wParam, lParam)
}
private fun eraseClientBackground(wParam: WPARAM) {
runCatching {
val gdi = NativeLibrary.getInstance("gdi32")
val hdc = Pointer(wParam.toLong())
val rect = RECT()
if (!User32.INSTANCE.GetClientRect(hwnd, rect)) return
val brush = gdi.getFunction("CreateSolidBrush")
.invoke(arrayOf(background.toColorRef())) as? Pointer ?: return
gdi.getFunction("FillRect").invoke(arrayOf(hdc, rect, brush))
gdi.getFunction("DeleteObject").invoke(arrayOf(brush))
}
}
private fun handleNcCalcSize(hWnd: HWND, wParam: WPARAM, lParam: LPARAM): LRESULT {
if (wParam.toLong() == 0L) {
return callDefault(hWnd, WM_NCCALCSIZE, wParam, lParam)
}
val pointer = Pointer(lParam.toLong())
val before = RECT().apply {
left = pointer.getInt(0)
top = pointer.getInt(4)
right = pointer.getInt(8)
bottom = pointer.getInt(12)
}
callDefault(hWnd, WM_NCCALCSIZE, wParam, lParam)
if (hWnd.isNativeZoomed()) {
applyMaximizedWorkArea(lParam)
} else {
pointer.setInt(0, before.left)
pointer.setInt(4, before.top)
pointer.setInt(8, before.right)
pointer.setInt(12, before.bottom)
}
return LRESULT(0)
}
private fun callDefault(hWnd: HWND, uMsg: Int, wParam: WPARAM, lParam: LPARAM): LRESULT {
val lib = user32 ?: return LRESULT(0)
return if (defaultWndProc.toLong() == -1L) {
User32.INSTANCE.DefWindowProc(hWnd, uMsg, wParam, lParam)
} else {
lib.CallWindowProc(defaultWndProc, hWnd, uMsg, wParam, lParam)
}
}
}
private fun applyMaximizedWorkArea(lParam: LPARAM) {
val pointer = Pointer(lParam.toLong())
val proposed = RECT().apply {
left = pointer.getInt(0)
top = pointer.getInt(4)
right = pointer.getInt(8)
bottom = pointer.getInt(12)
}
val monitor = User32.INSTANCE.MonitorFromRect(proposed, WinUser.MONITOR_DEFAULTTONEAREST)
?: return
val info = WinUser.MONITORINFO()
User32.INSTANCE.GetMonitorInfo(monitor, info)
val work = info.rcWork
if (work.right <= work.left || work.bottom <= work.top) return
pointer.setInt(0, work.left)
pointer.setInt(4, work.top)
pointer.setInt(8, work.right)
pointer.setInt(12, work.bottom)
}
private fun extendFrameIntoClientArea(hwnd: HWND) {
runCatching { NativeLibrary.getInstance("dwmapi") }
.getOrNull()
?.runCatching { getFunction("DwmExtendFrameIntoClientArea") }
?.getOrNull()
?.invoke(arrayOf(hwnd, DwmMargins()))
}
private fun is64Bit(): Boolean =
System.getProperty("sun.arch.data.model") == "64"
@com.sun.jna.Structure.FieldOrder(
"cxLeftWidth",
"cxRightWidth",
"cyTopHeight",
"cyBottomHeight",
)
internal class DwmMargins(
@JvmField var cxLeftWidth: Int = 0,
@JvmField var cxRightWidth: Int = 0,
@JvmField var cyTopHeight: Int = 0,
@JvmField var cyBottomHeight: Int = 0,
) : com.sun.jna.Structure(), com.sun.jna.Structure.ByReference
private fun Color.toColorRef(): Int =
(blue and 0xFF shl 16) or (green and 0xFF shl 8) or (red and 0xFF)
@@ -0,0 +1,155 @@
package ru.fromchat.desktop
import com.sun.jna.Native
import com.sun.jna.Structure
import com.sun.jna.platform.win32.WinBase
import ru.fromchat.Logger
import com.sun.jna.platform.win32.WinDef.DWORD
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.ptr.IntByReference
import com.sun.jna.win32.StdCallLibrary
import com.sun.jna.win32.W32APIOptions
import java.io.File
import java.lang.ProcessHandle
internal object WindowsRestartManager {
private const val ERROR_MORE_DATA = 234
private const val CCH_RM_MAX_APP_NAME = 255
private const val CCH_RM_MAX_SVC_NAME = 63
fun findLockingProcesses(files: List<File>): List<LockingProcessInfo> {
if (!isWindowsOs()) return emptyList()
val paths = files
.map { file -> runCatching { file.canonicalPath }.getOrElse { file.absolutePath } }
.filter { it.isNotBlank() }
.distinct()
if (paths.isEmpty()) return emptyList()
val session = IntByReference()
val sessionKey = CharArray(33)
val start = RestartManager.INSTANCE.RmStartSession(session, 0, sessionKey)
if (start != WinNT.ERROR_SUCCESS) {
Logger.w("WindowsRestartManager", "RmStartSession failed: $start")
return emptyList()
}
val sessionHandle = session.value
try {
val pathArray = paths.toTypedArray()
val register = RestartManager.INSTANCE.RmRegisterResources(
sessionHandle,
pathArray.size,
pathArray,
0,
null,
0,
null,
)
if (register != WinNT.ERROR_SUCCESS) {
Logger.w("WindowsRestartManager", "RmRegisterResources failed: $register paths=$paths")
return emptyList()
}
val needed = IntByReference()
val count = IntByReference()
var result = RestartManager.INSTANCE.RmGetList(
sessionHandle,
needed,
count,
null,
null,
)
if (result != ERROR_MORE_DATA && result != WinNT.ERROR_SUCCESS) {
Logger.w("WindowsRestartManager", "RmGetList probe failed: $result")
return emptyList()
}
val processCount = needed.value.coerceAtLeast(count.value)
if (processCount <= 0) return emptyList()
@Suppress("UNCHECKED_CAST")
val processes = RmProcessInfo().toArray(processCount) as Array<RmProcessInfo>
count.value = processCount
result = RestartManager.INSTANCE.RmGetList(
sessionHandle,
needed,
count,
processes,
null,
)
if (result != WinNT.ERROR_SUCCESS) {
Logger.w("WindowsRestartManager", "RmGetList failed: $result")
return emptyList()
}
val currentPid = ProcessHandle.current().pid()
return processes
.take(count.value.coerceAtMost(processes.size))
.onEach { it.read() }
.mapNotNull { info ->
val pid = info.dwProcessId.toLong()
if (pid <= 0L || pid == currentPid) return@mapNotNull null
val appName = info.appName().trim()
val executable = ProcessExecutableResolver.executablePathForPid(pid)
LockingProcessInfo(
pid = pid,
name = appName.ifBlank { executable?.let { File(it).name } ?: "PID $pid" },
description = executable ?: ProcessExecutableResolver.commandLineForPid(pid),
executablePath = executable,
icon = ProcessExecutableResolver.iconForExecutable(executable),
)
}
.distinctBy { it.pid }
} finally {
RestartManager.INSTANCE.RmEndSession(sessionHandle)
}
}
@Structure.FieldOrder(
"dwProcessId",
"processStartTime",
"strAppName",
"strServiceShortName",
"applicationType",
"appStatus",
"tsSessionId",
"restartable",
)
private class RmProcessInfo : Structure() {
@JvmField var dwProcessId = 0
@JvmField var processStartTime = WinBase.FILETIME()
@JvmField var strAppName = CharArray(CCH_RM_MAX_APP_NAME + 1)
@JvmField var strServiceShortName = CharArray(CCH_RM_MAX_SVC_NAME + 1)
@JvmField var applicationType = DWORD(0)
@JvmField var appStatus = DWORD(0)
@JvmField var tsSessionId = DWORD(0)
@JvmField var restartable = 0
fun appName(): String = Native.toString(strAppName)
}
private interface RestartManager : StdCallLibrary {
fun RmStartSession(sessionHandle: IntByReference, sessionFlags: Int, sessionKey: CharArray): Int
fun RmEndSession(sessionHandle: Int): Int
fun RmRegisterResources(
sessionHandle: Int,
fileCount: Int,
fileNames: Array<String>?,
serviceCount: Int,
serviceNames: Array<String>?,
processCount: Int,
processIds: IntArray?,
): Int
fun RmGetList(
sessionHandle: Int,
procInfoNeeded: IntByReference,
procInfoCount: IntByReference,
affectedApps: Array<RmProcessInfo>?,
rebootReasons: IntByReference?,
): Int
companion object {
val INSTANCE: RestartManager = Native.load("Rstrtmgr", RestartManager::class.java, W32APIOptions.DEFAULT_OPTIONS)
}
}
}
@@ -0,0 +1,131 @@
package ru.fromchat.desktop
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.WindowPlacement
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.WindowState
import com.sun.jna.platform.win32.User32
import com.sun.jna.platform.win32.WinUser
import java.awt.Rectangle
import java.awt.Window
import kotlin.math.abs
internal fun windowsWorkAreaBounds(window: Window): Rectangle? {
if (!isWindowsOs()) return null
val hwnd = window.windowsHwnd()
if (hwnd.pointer == null) return null
val monitor = User32.INSTANCE.MonitorFromWindow(hwnd, WinUser.MONITOR_DEFAULTTONEAREST)
?: return null
val info = WinUser.MONITORINFO()
if (!User32.INSTANCE.GetMonitorInfo(monitor, info).booleanValue()) return null
val work = info.rcWork
if (work.right <= work.left || work.bottom <= work.top) return null
return Rectangle(
work.left,
work.top,
work.right - work.left,
work.bottom - work.top,
)
}
/** Keeps a floating window inside the monitor work area (excludes taskbar). */
internal fun clampFloatingAwtWindowToWorkArea(window: Window): Boolean {
if (!isWindowsOs()) return false
if (window.isNativeZoomed()) return false
val work = windowsWorkAreaBounds(window) ?: return false
val current = window.bounds
val clamped = clampRectangleToWorkArea(current, work)
if (clamped == current) return false
window.setBounds(clamped)
return true
}
internal fun applyFloatingGeometry(
window: Window,
windowState: WindowState,
size: DpSize,
position: WindowPosition,
density: Density,
) {
with(density) {
val widthPx = size.width.roundToPx().coerceAtLeast(1)
val heightPx = size.height.roundToPx().coerceAtLeast(1)
val (x, y) = when (position) {
is WindowPosition.Absolute -> {
position.x.roundToPx() to position.y.roundToPx()
}
else -> window.location.x to window.location.y
}
window.setBounds(x, y, widthPx, heightPx)
windowState.size = size
if (position is WindowPosition.Absolute) {
windowState.position = position
}
}
}
internal fun applySavedFloatingGeometry(
window: Window,
windowState: WindowState,
density: Density,
) {
applyFloatingGeometry(
window,
windowState,
DesktopWindowPrefs.loadSize(),
DesktopWindowPrefs.loadPosition(),
density,
)
}
internal fun captureFloatingGeometryToPrefs(
window: Window,
windowState: WindowState,
density: Density,
) {
if (windowState.placement != WindowPlacement.Floating || window.isNativeZoomed()) return
val bounds = window.bounds
with(density) {
DesktopWindowPrefs.save(
size = DpSize(bounds.width.toDp(), bounds.height.toDp()),
position = WindowPosition(bounds.x.toDp(), bounds.y.toDp()),
)
}
}
internal fun syncComposeWindowStateFromAwt(
window: Window,
windowState: WindowState,
density: Density,
) {
if (windowState.placement != WindowPlacement.Floating) return
val bounds = window.bounds
with(density) {
windowState.size = DpSize(bounds.width.toDp(), bounds.height.toDp())
windowState.position = WindowPosition(bounds.x.toDp(), bounds.y.toDp())
}
}
internal fun floatingWindowCoversWorkArea(window: Window, tolerancePx: Int = 8): Boolean {
val work = windowsWorkAreaBounds(window) ?: return false
val bounds = window.bounds
return abs(bounds.x - work.x) <= tolerancePx &&
abs(bounds.y - work.y) <= tolerancePx &&
abs(bounds.width - work.width) <= tolerancePx &&
abs(bounds.height - work.height) <= tolerancePx
}
private fun clampRectangleToWorkArea(bounds: Rectangle, work: Rectangle): Rectangle {
val width = bounds.width.coerceAtMost(work.width).coerceAtLeast(320)
val height = bounds.height.coerceAtMost(work.height).coerceAtLeast(240)
val maxX = (work.x + work.width - width).coerceAtLeast(work.x)
val maxY = (work.y + work.height - height).coerceAtLeast(work.y)
return Rectangle(
bounds.x.coerceIn(work.x, maxX),
bounds.y.coerceIn(work.y, maxY),
width,
height,
)
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

@@ -0,0 +1,468 @@
#import <AppKit/AppKit.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreServices/CoreServices.h>
#import <Foundation/Foundation.h>
#import <UserNotifications/UserNotifications.h>
#import <jni.h>
@class FromChatNotificationDelegate;
static JavaVM *fromchatJvm = NULL;
static FromChatNotificationDelegate *fromchatDelegate = nil;
static jclass fromchatMacNotificationCenterClass = NULL;
@interface FromChatNotificationDelegate : NSObject <UNUserNotificationCenterDelegate>
@end
static void fromchatCallJavaStaticVoid(const char *methodName, const char *utfArg);
@implementation FromChatNotificationDelegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
UNNotificationPresentationOptions options =
UNNotificationPresentationOptionBanner |
UNNotificationPresentationOptionList |
UNNotificationPresentationOptionSound |
UNNotificationPresentationOptionBadge;
NSLog(
@"FromChat UN willPresent id=%@ nsAppActive=%d options=%lu",
notification.request.identifier,
[NSApp isActive],
(unsigned long)options
);
completionHandler(options);
fromchatCallJavaStaticVoid("onNativeWillPresent", notification.request.identifier.UTF8String);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler {
NSString *action = response.actionIdentifier;
NSString *identifier = response.notification.request.identifier;
NSLog(@"FromChat UN response action=%@ id=%@", action, identifier);
if ([action isEqualToString:UNNotificationDismissActionIdentifier]) {
completionHandler();
return;
}
fromchatCallJavaStaticVoid("onNativeActivated", identifier.UTF8String);
completionHandler();
}
@end
static void fromchatCallJavaStaticVoid(const char *methodName, const char *utfArg) {
if (fromchatJvm == NULL || fromchatMacNotificationCenterClass == NULL || methodName == NULL) {
return;
}
JNIEnv *env = NULL;
jint getEnv = (*fromchatJvm)->GetEnv(fromchatJvm, (void **)&env, JNI_VERSION_1_8);
jboolean attachedHere = JNI_FALSE;
if (getEnv == JNI_EDETACHED) {
if ((*fromchatJvm)->AttachCurrentThread(fromchatJvm, (void **)&env, NULL) != JNI_OK) {
return;
}
attachedHere = JNI_TRUE;
}
if (env == NULL) return;
jmethodID mid = (*env)->GetStaticMethodID(
env,
fromchatMacNotificationCenterClass,
methodName,
"(Ljava/lang/String;)V"
);
if (mid != NULL) {
jstring jid = utfArg != NULL ? (*env)->NewStringUTF(env, utfArg) : NULL;
(*env)->CallStaticVoidMethod(env, fromchatMacNotificationCenterClass, mid, jid);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
}
if (jid != NULL) (*env)->DeleteLocalRef(env, jid);
}
if (attachedHere) {
(*fromchatJvm)->DetachCurrentThread(fromchatJvm);
}
}
static BOOL fromchatIsBundledApp(void) {
NSString *path = [NSBundle mainBundle].bundlePath;
return [path.pathExtension isEqualToString:@"app"];
}
static UNUserNotificationCenter *fromchatNotificationCenter(void) {
NSBundle *bundle = [NSBundle mainBundle];
if (!fromchatIsBundledApp()) {
NSLog(@"FromChat UN skip: not an .app (path=%@ id=%@)", bundle.bundlePath, bundle.bundleIdentifier);
return nil;
}
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
NSLog(@"FromChat UN center=%p path=%@ id=%@", center, bundle.bundlePath, bundle.bundleIdentifier);
return center;
}
static void fromchatRunOnMain(void (^block)(void)) {
if ([NSThread isMainThread]) {
block();
} else {
dispatch_sync(dispatch_get_main_queue(), block);
}
}
static void fromchatEnsureDelegate(UNUserNotificationCenter *center) {
if (center == nil) return;
fromchatRunOnMain(^{
if (fromchatDelegate == nil) {
fromchatDelegate = [FromChatNotificationDelegate new];
}
center.delegate = fromchatDelegate;
NSLog(@"FromChat UN delegate set on %@", center);
});
}
static NSRunningApplication *fromchatOtherFrontApp(void) {
NSString *ours = [NSBundle mainBundle].bundleIdentifier;
pid_t ourPid = [NSRunningApplication currentApplication].processIdentifier;
NSRunningApplication *wsFront = [[NSWorkspace sharedWorkspace] frontmostApplication];
if (wsFront != nil && wsFront.processIdentifier != ourPid &&
(ours == nil || ![wsFront.bundleIdentifier isEqualToString:ours])) {
return wsFront;
}
CFArrayRef info = CGWindowListCopyWindowInfo(
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
kCGNullWindowID
);
if (info == NULL) return nil;
NSArray *windows = CFBridgingRelease(info);
for (NSDictionary *win in windows) {
NSNumber *layer = win[(id)kCGWindowLayer];
if (layer == nil || layer.intValue != 0) continue;
NSNumber *pidNum = win[(id)kCGWindowOwnerPID];
if (pidNum == nil) continue;
pid_t pid = pidNum.intValue;
if (pid == ourPid) continue;
NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
if (app == nil) continue;
if (app.activationPolicy != NSApplicationActivationPolicyRegular) continue;
return app;
}
return nil;
}
static BOOL fromchatIsAppFrontmost(void) {
__block BOOL frontmost = NO;
fromchatRunOnMain(^{
NSString *frontId = [[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier;
NSString *ours = [NSBundle mainBundle].bundleIdentifier;
frontmost = frontId != nil && ours != nil && [frontId isEqualToString:ours];
NSLog(
@"FromChat frontmost=%d front=%@ ours=%@ nsAppActive=%d",
frontmost,
frontId,
ours,
[NSApp isActive]
);
});
return frontmost;
}
static void fromchatResignActive(void) {
fromchatRunOnMain(^{
[NSApp deactivate];
NSRunningApplication *other = fromchatOtherFrontApp();
if (other != nil) {
if (@available(macOS 14.0, *)) {
[NSApp yieldActivationToApplication:other];
} else {
[other activateWithOptions:NSApplicationActivateIgnoringOtherApps];
}
}
NSLog(
@"FromChat resignActive nsAppActive=%d front=%@",
[NSApp isActive],
[[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier
);
});
}
static void fromchatYieldIfNotFrontmost(void) {
fromchatResignActive();
}
static BOOL fromchatDeliverNotification(
UNUserNotificationCenter *center,
NSString *title,
NSString *body,
NSString *subtitle,
NSString *identifier,
BOOL playSound,
BOOL windowFocused
) {
if (center == nil) return NO;
fromchatEnsureDelegate(center);
if (windowFocused != YES) {
fromchatResignActive();
}
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = title;
if (subtitle.length > 0) {
content.subtitle = subtitle;
}
content.body = body;
content.sound = playSound ? [UNNotificationSound defaultSound] : nil;
if (@available(macOS 12.0, *)) {
content.interruptionLevel = UNNotificationInterruptionLevelActive;
}
UNNotificationRequest *request =
[UNNotificationRequest requestWithIdentifier:identifier content:content trigger:nil];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block BOOL ok = NO;
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
ok = error == nil;
NSLog(
@"FromChat UN add id=%@ ok=%d focused=%d nsAppActive=%d error=%@",
identifier,
ok,
windowFocused == YES,
[NSApp isActive],
error
);
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC));
return ok;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
fromchatJvm = vm;
JNIEnv *env = NULL;
if ((*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_8) == JNI_OK && env != NULL) {
jclass local = (*env)->FindClass(env, "ru/fromchat/desktop/MacNotificationCenter");
if (local != NULL) {
fromchatMacNotificationCenterClass = (*env)->NewGlobalRef(env, local);
(*env)->DeleteLocalRef(env, local);
}
}
return JNI_VERSION_1_8;
}
JNIEXPORT jboolean JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRequestAuthorization(
JNIEnv *env,
jclass cls
) {
UNUserNotificationCenter *center = fromchatNotificationCenter();
if (center == nil) return JNI_FALSE;
fromchatEnsureDelegate(center);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block BOOL grantedResult = NO;
void (^request)(void) = ^{
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert |
UNAuthorizationOptionSound |
UNAuthorizationOptionBadge)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
grantedResult = granted;
NSLog(@"FromChat UN auth granted=%d error=%@", granted, error);
dispatch_semaphore_signal(semaphore);
}];
};
if ([NSThread isMainThread]) {
request();
} else {
dispatch_async(dispatch_get_main_queue(), request);
}
dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC));
return grantedResult ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jint JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeAuthorizationStatus(
JNIEnv *env,
jclass cls
) {
UNUserNotificationCenter *center = fromchatNotificationCenter();
if (center == nil) return 0;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSInteger status = 0;
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
status = settings.authorizationStatus;
if (@available(macOS 12.0, *)) {
NSLog(
@"FromChat UN status=%ld alert=%ld sound=%ld badge=%ld preview=%ld",
(long)settings.authorizationStatus,
(long)settings.alertSetting,
(long)settings.soundSetting,
(long)settings.badgeSetting,
(long)settings.showPreviewsSetting
);
} else {
NSLog(@"FromChat UN status=%ld alert=%ld sound=%ld badge=%ld",
(long)settings.authorizationStatus,
(long)settings.alertSetting,
(long)settings.soundSetting,
(long)settings.badgeSetting);
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC));
return (jint)status;
}
JNIEXPORT jboolean JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeDeliver(
JNIEnv *env,
jclass cls,
jstring jTitle,
jstring jBody,
jstring jSubtitle,
jstring jIdentifier,
jboolean playSound,
jboolean windowFocused
) {
UNUserNotificationCenter *center = fromchatNotificationCenter();
if (center == nil) return JNI_FALSE;
const char *titleChars = (*env)->GetStringUTFChars(env, jTitle, NULL);
const char *bodyChars = (*env)->GetStringUTFChars(env, jBody, NULL);
const char *subtitleChars = jSubtitle ? (*env)->GetStringUTFChars(env, jSubtitle, NULL) : NULL;
const char *idChars = (*env)->GetStringUTFChars(env, jIdentifier, NULL);
NSString *title = titleChars ? [NSString stringWithUTF8String:titleChars] : @"";
NSString *body = bodyChars ? [NSString stringWithUTF8String:bodyChars] : @"";
NSString *subtitle = subtitleChars ? [NSString stringWithUTF8String:subtitleChars] : @"";
NSString *identifier = idChars ? [NSString stringWithUTF8String:idChars] : [[NSUUID UUID] UUIDString];
__block BOOL ok = NO;
void (^deliver)(void) = ^{
ok = fromchatDeliverNotification(
center,
title,
body,
subtitle,
identifier,
playSound == JNI_TRUE,
windowFocused
);
};
if ([NSThread isMainThread]) {
deliver();
} else {
dispatch_sync(dispatch_get_main_queue(), deliver);
}
if (titleChars) (*env)->ReleaseStringUTFChars(env, jTitle, titleChars);
if (bodyChars) (*env)->ReleaseStringUTFChars(env, jBody, bodyChars);
if (subtitleChars) (*env)->ReleaseStringUTFChars(env, jSubtitle, subtitleChars);
if (idChars) (*env)->ReleaseStringUTFChars(env, jIdentifier, idChars);
return ok ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRemove(
JNIEnv *env,
jclass cls,
jobjectArray jIdentifiers
) {
UNUserNotificationCenter *center = fromchatNotificationCenter();
if (center == nil || jIdentifiers == NULL) return;
jsize count = (*env)->GetArrayLength(env, jIdentifiers);
NSMutableArray<NSString *> *ids = [NSMutableArray arrayWithCapacity:(NSUInteger)count];
for (jsize i = 0; i < count; i++) {
jstring jId = (*env)->GetObjectArrayElement(env, jIdentifiers, i);
if (jId == NULL) continue;
const char *chars = (*env)->GetStringUTFChars(env, jId, NULL);
if (chars) {
[ids addObject:[NSString stringWithUTF8String:chars]];
(*env)->ReleaseStringUTFChars(env, jId, chars);
}
(*env)->DeleteLocalRef(env, jId);
}
NSLog(@"FromChat UN remove count=%lu", (unsigned long)ids.count);
[center removeDeliveredNotificationsWithIdentifiers:ids];
[center removePendingNotificationRequestsWithIdentifiers:ids];
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRemoveAll(
JNIEnv *env,
jclass cls
) {
UNUserNotificationCenter *center = fromchatNotificationCenter();
if (center == nil) return;
NSLog(@"FromChat UN removeAll");
[center removeAllDeliveredNotifications];
[center removeAllPendingNotificationRequests];
}
JNIEXPORT jboolean JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeOpenSettings(
JNIEnv *env,
jclass cls
) {
NSURL *url = [NSURL URLWithString:
@"x-apple.systempreferences:com.apple.Notifications-Settings.extension?id=ru.fromchat.desktop"];
if (url == nil) return JNI_FALSE;
BOOL opened = [[NSWorkspace sharedWorkspace] openURL:url];
if (!opened) {
url = [NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.notifications"];
opened = url != nil && [[NSWorkspace sharedWorkspace] openURL:url];
}
return opened ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT jstring JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeDebugInfo(
JNIEnv *env,
jclass cls
) {
__block NSString *info = @"";
fromchatRunOnMain(^{
NSBundle *bundle = [NSBundle mainBundle];
NSString *frontId = [[NSWorkspace sharedWorkspace] frontmostApplication].bundleIdentifier;
NSString *ours = bundle.bundleIdentifier;
BOOL frontmost = frontId != nil && ours != nil && [frontId isEqualToString:ours];
info = [NSString stringWithFormat:
@"bundlePath=%@ bundleId=%@ bundled=%d frontmost=%d front=%@ nsAppActive=%d",
bundle.bundlePath,
ours ?: @"(null)",
fromchatIsBundledApp() ? 1 : 0,
frontmost ? 1 : 0,
frontId ?: @"(null)",
[NSApp isActive] ? 1 : 0];
});
return (*env)->NewStringUTF(env, info.UTF8String);
}
JNIEXPORT jboolean JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeIsAppFrontmost(
JNIEnv *env,
jclass cls
) {
return fromchatIsAppFrontmost() ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeResignActive(
JNIEnv *env,
jclass cls
) {
fromchatResignActive();
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeYieldActivation(
JNIEnv *env,
jclass cls
) {
fromchatYieldIfNotFrontmost();
}
JNIEXPORT jboolean JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeIsBundled(
JNIEnv *env,
jclass cls
) {
return fromchatIsBundledApp() ? JNI_TRUE : JNI_FALSE;
}
JNIEXPORT void JNICALL Java_ru_fromchat_desktop_MacNotificationCenter_nativeRegisterBundle(
JNIEnv *env,
jclass cls
) {
if (!fromchatIsBundledApp()) return;
NSURL *url = [NSBundle mainBundle].bundleURL;
if (url == nil) return;
LSRegisterURL((__bridge CFURLRef)url, true);
}
+1
View File
@@ -0,0 +1 @@
target/
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More