diff --git a/.github/workflows/build-android-fcm.yml b/.github/workflows/build-android-fcm.yml index 331f2ad3..d58392a1 100644 --- a/.github/workflows/build-android-fcm.yml +++ b/.github/workflows/build-android-fcm.yml @@ -18,11 +18,6 @@ on: - 'pubspec.yaml' - '.github/workflows/build-android-fcm.yml' -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: build-android-fcm: runs-on: ubuntu-latest diff --git a/.github/workflows/build-android-play.yml b/.github/workflows/build-android-play.yml index 72a4f515..894167b4 100644 --- a/.github/workflows/build-android-play.yml +++ b/.github/workflows/build-android-play.yml @@ -3,11 +3,6 @@ name: Build Android (Google Play) on: workflow_dispatch: -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: build-play: runs-on: ubuntu-latest diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 8a07970c..a3693977 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -18,11 +18,6 @@ on: - 'pubspec.yaml' - '.github/workflows/build-android.yml' -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: build-android: runs-on: ubuntu-latest diff --git a/.github/workflows/build-ios-appstore.yml b/.github/workflows/build-ios-appstore.yml index 6ca89371..f82162f7 100644 --- a/.github/workflows/build-ios-appstore.yml +++ b/.github/workflows/build-ios-appstore.yml @@ -10,6 +10,7 @@ on: - 'lib/**' - 'scripts/build_ios_share.sh' - 'scripts/sign_ios_appstore.py' + - 'scripts/validate_ios_appstore_metadata.py' - 'native/komet_share/**' - 'native/komet_tlottie/**' - 'native/crypto-core' @@ -26,6 +27,7 @@ on: - 'lib/**' - 'scripts/build_ios_share.sh' - 'scripts/sign_ios_appstore.py' + - 'scripts/validate_ios_appstore_metadata.py' - 'native/komet_share/**' - 'native/komet_tlottie/**' - 'native/crypto-core' @@ -39,9 +41,6 @@ on: - '.github/actions/pin-kolibri-crates/**' env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: @@ -84,6 +83,9 @@ jobs: - name: Pin kolibri crates uses: ./.github/actions/pin-kolibri-crates + - name: Validate App Store metadata + run: python3 scripts/validate_ios_appstore_metadata.py + # Схема max:// принадлежит официальному приложению MAX, App Store-сборка её не заявляет - name: Drop the max URL scheme run: | @@ -101,8 +103,8 @@ jobs: - name: Build App Store variant (no codesign) env: KOMET_APPSTORE_BUILD: 'true' - KOMET_REVIEW_PHONE: ${{ secrets.KOMET_REVIEW_PHONE }} - KOMET_REVIEW_PAYLOAD: ${{ secrets.KOMET_REVIEW_PAYLOAD }} + KOMET_REVIEW_PHONE: ${{ secrets.KOMET_REVIEW_PHONE_IOS }} + KOMET_REVIEW_PAYLOAD: ${{ secrets.KOMET_REVIEW_PAYLOAD_IOS }} run: | flutter config --no-enable-swift-package-manager flutter build ios --release --no-codesign -v \ @@ -195,11 +197,15 @@ jobs: args=( build/ios/iphoneos/Runner.app --app-profile "$RUNNER_TEMP/appstore.mobileprovision" + --app-entitlements ios/Runner/Runner.entitlements --identity "$IDENTITY" --keychain "$KEYCHAIN_PATH" ) if [ -f "$RUNNER_TEMP/appstore-share.mobileprovision" ]; then - args+=(--share-profile "$RUNNER_TEMP/appstore-share.mobileprovision") + args+=( + --share-profile "$RUNNER_TEMP/appstore-share.mobileprovision" + --share-entitlements ios/ShareExtension/ShareExtension.entitlements + ) fi python3 scripts/sign_ios_appstore.py "${args[@]}" diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index f44a9dcc..e26ee6c7 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -43,9 +43,6 @@ on: - '.github/actions/pin-kolibri-crates/**' env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 04c13912..4aed53dd 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -19,9 +19,6 @@ on: - '.github/workflows/build-linux.yml' env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index ec05e50c..65f835bc 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -19,9 +19,6 @@ on: - '.github/workflows/build-macos.yml' env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 4a737961..baaa16b1 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -19,9 +19,6 @@ on: - '.github/workflows/build-windows.yml' env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/flutter-dev.yml b/.github/workflows/flutter-dev.yml index 44ed5300..85f845b8 100644 --- a/.github/workflows/flutter-dev.yml +++ b/.github/workflows/flutter-dev.yml @@ -5,11 +5,6 @@ on: branches: - 'dev/**' -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: analyze-and-build-android: runs-on: ubuntu-latest diff --git a/.github/workflows/flutter-main.yml b/.github/workflows/flutter-main.yml index d854b346..a40b0a73 100644 --- a/.github/workflows/flutter-main.yml +++ b/.github/workflows/flutter-main.yml @@ -5,11 +5,6 @@ on: branches: - 'main' -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: android: runs-on: ubuntu-latest diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 3365efd0..720e4862 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -15,9 +15,6 @@ permissions: contents: write env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/release-main.yml b/.github/workflows/release-main.yml index 6a0487e3..b8994406 100644 --- a/.github/workflows/release-main.yml +++ b/.github/workflows/release-main.yml @@ -10,9 +10,6 @@ permissions: contents: write env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc FLUTTER_VERSION: '3.47.0' jobs: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 426a6055..c7326b43 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -12,11 +12,6 @@ concurrency: group: tests-${{ github.ref }} cancel-in-progress: true -env: - GIT_CONFIG_COUNT: '1' - GIT_CONFIG_KEY_0: url.https://x-access-token:${{ secrets.KOMET_DEPS_TOKEN }}@github.com/KometTeam/flutter-webrtc.insteadOf - GIT_CONFIG_VALUE_0: https://github.com/KometTeam/flutter-webrtc - jobs: test: runs-on: ubuntu-latest @@ -47,6 +42,14 @@ jobs: - name: Flutter test run: flutter test + git-pins: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v5 + - name: Check git dependencies in pubspec.lock are reachable + run: tool/check_git_pins.sh + share-native: runs-on: ubuntu-latest timeout-minutes: 20 diff --git a/CLAUDE.md b/CLAUDE.md index 0f575e68..2316d015 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,6 +118,61 @@ thread, and opening the sticker panel froze the app for up to 300 ms. To run the engine test on the host, build the library with `cargo build --release` in `native/komet_tlottie/rust` and pass it as `TLOTTIE_LIB`. +## Cache and storage + +Settings → Storage (`StorageScreen`) shows what Komet keeps on disk by kind and clears the chosen +kinds. `CacheJanitor` (`lib/core/cache/cache_janitor.dart`) owns three caches: `MediaCache` +(`media_cache/`), the flutter_cache_manager image cache (`/libCachedImageData`, which notices +files removed behind its back) and the sticker frames (`tlottie_frames/`, own 256 MB cap). One +budget, `AppCacheLimit` (pref key still `media_cache_limit_bytes`), covers all three together, +and when it is exceeded the least recently used files go first, skipping anything touched in the +last two minutes. Writers report their bytes (`CacheJanitor.noteWrite`) into per-cache totals kept +in memory; a full pass runs only when a total crosses the budget or a cap, or the last measurement +is older than 15 minutes (the image cache grows without telling us). The pass lists and stats the +directories inside `Isolate.run`, so thousands of files cost the UI isolate one message, not one +event per file. Kept media (`keep_*`, already erased on the server) and the database are shown but +never evicted. A `MediaCache` file's kind is read from +its name, so build new names in `media_cache_names.dart` where `mediaCacheKindOf` can see them. + +## What's new + +Store builds (no self-updater) show «Что нового» once per build from `assets/whats_new/.txt`. +`WhatsNewDocument` (`lib/core/whats_new/`, plain Dart) parses it; `WhatsNewRunner` plays scenarios. + +- Lines without indentation are the notes; `//` lines are comments. +- `[words](#scenario)` makes those words tappable, `… → #scenario` at the end of a line makes the + whole line a tappable row. A link works in place of `#scenario`: `:settings/storage` (a MAX route, + same router as `max.ru/:…`), `max.ru/channel/123`, `https://…`. +- `#name` starts a scenario; its steps follow, indented, one per line, text in `"double quotes"`. + +| Step | Does | +|------|------| +| `close` | closes the sheet (any step that navigates closes it first anyway) | +| `tab chats\|calls\|contacts\|settings` | pops to the shell and switches the bottom tab | +| `open ` | opens a route or link (`:settings/appearance`, `max.ru/…`, `https://…`) | +| `check ` | shows the link check sheet for that address, as a tap on a link in a chat would; opens nothing, whichever button is pressed | +| `back` | pops the current screen | +| `scroll top\|bottom\|` | scrolls the current screen | +| `highlight ` | scrolls to the target and pulses it | +| `tap ` | scrolls to the target, flashes it and performs its action (opens, expands, switches) | +| `hint "text"` | scrolls to the target and shows `showHintBubble` next to it | +| `notify "text" ["button" #scenario]` | `showCustomNotification`, optionally with an action | +| `wait ` | pauses (0–10000) | +| `run #scenario` | runs another scenario | + +A target is a `SpotlightTarget(id: …)` around a widget; ids live in `SpotlightIds` +(`lib/core/whats_new/spotlight_ids.dart`), which is also what the parser checks against. To make a +new element reachable, add its id there and wrap the widget; give it `onActivate` (the same action +as its own tap) and list it in `SpotlightIds.tappable` to let `tap` press it. Toggles that change a +setting stay out of `tappable` — a scenario shows them, never flips them. `open` does not wait for +the opened screen to close (`Navigator.push` completes only on pop); later steps wait for their +target to appear instead. A target not built yet (lower in a +lazy list) is found by scrolling the screen's main list until it mounts. `dart run tool/whats_new.dart` +checks every language and counts characters against Google Play's 500; +`dart run tool/whats_new.dart play ru` prints the Play text without links and comments. The test +`whats_new_document_test.dart` fails on any mistake in the shipped files or when the languages +differ in scenarios or number of notes. + ## Keyboard and chat panels The chat follows Telegram: the composer's bottom is always `max(keyboard, visible sticker panel)` @@ -154,9 +209,16 @@ focus only after the keyboard has stayed closed for 250 ms, so a single zero-ins ## WebRTC plugin fork -`flutter_webrtc` is overridden with the private fork `KometTeam/flutter-webrtc` (upstream v1.5.2 + -patches), pinned by commit in `dependency_overrides` in `pubspec.yaml`. To change the plugin, commit -in the fork, push, and bump the `ref`. The patches: +`flutter_webrtc` comes from the public fork `KometTeam/flutter-webrtc` (upstream v1.5.2 + patches), +a git dependency pinned by commit in `dependencies` in `pubspec.yaml` — nothing else depends on the +plugin, so it needs no `dependency_overrides`, and a fresh clone builds without any token. To change +the plugin, commit in the fork, push, and bump the `ref` (then `flutter pub get` to refresh +`pubspec.lock`). The fork's `main` is protected against force-push and deletion, because pub clones +the fork and a commit no branch reaches is missing from a fresh clone (`Could not find a file named +"pubspec.yaml"`), while runs with a warm pub cache keep passing and hide it. CI caches pub +(`cache: true`), so the `git-pins` job in `tests.yml` runs `tool/check_git_pins.sh`: it mirrors +every git dependency of `pubspec.lock` the way pub does and fails when the `resolved-ref` is in no +branch or tag. The patches: - desktop camera open/close and `getStats` run on background threads — libwebrtc does both through `Thread::BlockingCall` on its worker thread, and on Linux the window is drawn on the platform @@ -164,9 +226,6 @@ in the fork, push, and bump the `ref`. The patches: - `VideoFrameTap` hands the frames of a video track to Dart: raw I420 on Linux/Windows, VP8 encoded with MediaCodec on Android. -CI fetches the fork with the repo secret `KOMET_DEPS_TOKEN` (read access to the fork): every Flutter -workflow rewrites the fork URL through workflow-level `GIT_CONFIG_*` env. - Call screen sharing follows MAX: in SERVER topology frames travel as VP8/VP9 over SFU data channels, not as an RTP track — `consumerScreenShare` to send (`ScreenSharePipeline`, libvpx encoder in an isolate on desktop), `producerScreenShare` to receive (`RemoteScreens`: libvpx → `ui.Image` on @@ -199,7 +258,9 @@ number, and `KOMET_REVIEW_PAYLOAD`, a session token encrypted with the app's own (Argon2id + ChaCha20-Poly1305). The key is derived from `:`, so the payload in the APK is worthless without the pair handed to the reviewer, and neither define is committed — `build-android-play.yml` reads them from the `KOMET_REVIEW_PHONE` and -`KOMET_REVIEW_PAYLOAD` secrets. Without both defines `ReviewAccess.enabled` is false and the login +`KOMET_REVIEW_PAYLOAD` secrets, `build-ios-appstore.yml` from `KOMET_REVIEW_PHONE_IOS` and +`KOMET_REVIEW_PAYLOAD_IOS`, so each store reviewer gets its own session and revoking one leaves +the other working. Without both defines `ReviewAccess.enabled` is false and the login screen behaves exactly as before. Entering the demo number skips `requestCode` and opens `CodeConfirmationScreen.review`, which @@ -217,6 +278,21 @@ printf '{"token":"…"}' | dart run tool/review_blob.dart '+7 999 999 99 99' '12 The tool derives the key exactly as `ReviewAccess` does and prints one space-free Cyrillic blob — that string is the secret's value. +## Login by call (foreign numbers) + +The server rarely sends an SMS to a non-Russian number, and the way it confirms one is decided by +the answer to `AUTH_REQUEST` (17), never by the client: + +- **`callOutParams` present** (`{trackId, ttl, pollingInterval}`, both in ms): the user calls a + robot. `CallOutConfirmationScreen` polls `AUTH_CHECK_CALL` (294, `{trackId}`) every + `pollingInterval` until `ttl` runs out — `status` 0 no number yet, 1 `callNumber` assigned, 2 + passed, 3 timed out. On 2 it sends `AUTH_BY_TRACK` (291, `{trackId}`), whose answer has the + same shape as `AUTH` after a code (`tokenAttrs`, `passwordChallenge`, `presetAvatars`), so 2FA, + registration and login go through the same `VerifiedLoginFlow` as `CodeConfirmationScreen`. + "Refresh number" is a fresh `START_AUTH`. +- **no `callOutParams`**: the code screen as usual, but for a non-`RU` country the server calls + the user and the code is the last 6 digits of the incoming number — the screen says so. + ## Architecture The codebase follows a strict layered architecture: diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 475a3841..7475b0e2 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -137,12 +137,8 @@ - - - - + android:exported="false" + tools:ignore="Instantiatable" /> = Build.VERSION_CODES.O) { @@ -68,13 +87,18 @@ class CallForegroundService : Service() { ctx.startService(intent) } } catch (e: Exception) { - Log.w("KometFcm", "ongoing FGS start failed: ${e.message}") + Log.w(TAG, "ongoing FGS start failed: ${e.message}") } } + fun refreshTypes() { + running?.updateTypes() + } + fun stop(ctx: Context) { CallState.inCall = false screenShare = false + caller = DEFAULT_CALLER val service = running if (service != null) { service.shutdown() @@ -92,6 +116,9 @@ class CallForegroundService : Service() { } } + private var foreground = false + private var activeTypes = 0 + override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { @@ -107,28 +134,45 @@ class CallForegroundService : Service() { private fun shutdown() { ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) + foreground = false + activeTypes = 0 stopSelf() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - when (intent?.action) { - ACTION_STOP -> shutdown() - ACTION_SCREEN_SHARE -> { - screenShare = intent.getBooleanExtra(EXTRA_SCREEN_SHARE, false) - val caller = intent.getStringExtra(CallConst.EXTRA_CALLER) ?: "Звонок" - CallNotifier.ensureChannel(this) - startAsForeground(caller) - } - else -> { - val caller = intent?.getStringExtra(CallConst.EXTRA_CALLER) ?: "Звонок" - CallNotifier.ensureChannel(this) - startAsForeground(caller) - } + if (intent?.action == ACTION_STOP) { + shutdown() + return START_NOT_STICKY + } + if (intent?.action == ACTION_SCREEN_SHARE) { + screenShare = intent.getBooleanExtra(EXTRA_SCREEN_SHARE, false) } + CallNotifier.ensureChannel(this) + startAsForeground() return START_NOT_STICKY } - private fun startAsForeground(caller: String) { + private fun updateTypes() { + if (!foreground || Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return + if (foregroundTypes().first() == activeTypes) return + startAsForeground() + } + + private fun micGranted(): Boolean = + ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == + PackageManager.PERMISSION_GRANTED + + private fun foregroundTypes(): List { + val playback = ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK + val base = if (micGranted()) ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE else playback + return buildList { + if (screenShare) add(base or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) + add(base) + if (base != playback) add(playback) + } + } + + private fun startAsForeground(): Boolean { val immutable = android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE val open = LaunchIntents.app(this).apply { @@ -154,24 +198,34 @@ class CallForegroundService : Service() { .setStyle(NotificationCompat.CallStyle.forOngoingCall(person, hangup)) .build() - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE - if (screenShare) { - types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION - } - startForeground(ONGOING_ID, notif, types) - } else { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + return try { startForeground(ONGOING_ID, notif) + foreground = true + true + } catch (e: Exception) { + Log.w(TAG, "startForeground failed: ${e.message}") + if (!foreground) stopSelf() + false } - } catch (e: Exception) { - Log.w("KometFcm", "startForeground failed: ${e.message}") - if (screenShare) { - screenShare = false - startAsForeground(caller) - return + } + + val wantedScreen = screenShare + for (types in foregroundTypes()) { + try { + startForeground(ONGOING_ID, notif, types) + } catch (e: Exception) { + Log.w(TAG, "startForeground(types=$types) failed: ${e.message}") + continue } - stopSelf() + foreground = true + activeTypes = types + val sharing = (types and ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) != 0 + screenShare = sharing + return sharing || !wantedScreen } + screenShare = false + if (!foreground) stopSelf() + return false } } diff --git a/android/app/src/main/kotlin/ru/komet/app/FkmChannel.kt b/android/app/src/main/kotlin/ru/komet/app/FkmChannel.kt index b949e616..468313fb 100644 --- a/android/app/src/main/kotlin/ru/komet/app/FkmChannel.kt +++ b/android/app/src/main/kotlin/ru/komet/app/FkmChannel.kt @@ -51,18 +51,32 @@ object FkmChannel { result.success(null) } - "showMessage" -> result.success(deliver(ctx, call, "showMessage")) + "setUnread" -> { + val count = call.argument("count") ?: 0 + if (FkmState.applyUnread(ctx, count)) FkmService.refresh(ctx) + result.success(null) + } - "showCall" -> result.success(deliver(ctx, call, "showCall")) + "showMessage" -> result.success( + render(ctx, call, "showMessage") { notifier, data -> + notifier.handle(data) + }, + ) + + "showCall" -> result.success( + render(ctx, call, "showCall") { notifier, data -> + notifier.handle(data) + }, + ) "editMessage" -> result.success( - update(ctx, call, "editMessage") { notifier, data -> + render(ctx, call, "editMessage") { notifier, data -> notifier.editMessage(data) }, ) "removeMessage" -> result.success( - update(ctx, call, "removeMessage") { notifier, data -> + render(ctx, call, "removeMessage") { notifier, data -> notifier.removeMessage(data) }, ) @@ -124,22 +138,7 @@ object FkmChannel { } // Отрисовка тянет аватарку по сети — только не на главном потоке. - private fun deliver(ctx: Context, call: MethodCall, tag: String): Boolean { - val data = call.argument>("data") ?: return false - worker.execute { - try { - KometNotifier(ctx).handle(data) - FkmState.countDelivered(ctx) - FkmService.refresh(ctx) - } catch (e: Exception) { - Log.w("Fkm", "$tag failed: ${e.message}") - } - } - return true - } - - // Правка и удаление ничего не «доставляют» — счётчик они не трогают. - private fun update( + private fun render( ctx: Context, call: MethodCall, tag: String, diff --git a/android/app/src/main/kotlin/ru/komet/app/FkmService.kt b/android/app/src/main/kotlin/ru/komet/app/FkmService.kt index 2764084a..072a00a0 100644 --- a/android/app/src/main/kotlin/ru/komet/app/FkmService.kt +++ b/android/app/src/main/kotlin/ru/komet/app/FkmService.kt @@ -17,7 +17,7 @@ import androidx.core.app.NotificationCompat object FkmState { private const val PREFS = "komet_fkm" private const val KEY_ENABLED = "enabled" - private const val KEY_DELIVERED = "delivered" + private const val KEY_UNREAD = "unread" @Volatile var enabled = false @@ -26,8 +26,10 @@ object FkmState { @Volatile var connected = false + // Непрочитанные считает Dart по чатам; здесь последнее присланное число, + // чтобы уведомление после ребута показывало его, пока движка нет. @Volatile - var delivered = 0 + var unread = 0 private set private fun prefs(ctx: Context) = @@ -36,26 +38,28 @@ object FkmState { fun restore(ctx: Context) { val p = prefs(ctx) enabled = p.getBoolean(KEY_ENABLED, false) - delivered = p.getInt(KEY_DELIVERED, 0) + unread = p.getInt(KEY_UNREAD, 0) } fun applyEnabled(ctx: Context, value: Boolean) { enabled = value - // Счётчик обнуляем только на выключении, чтобы перезапуск приложения - // не сбрасывал накопленное. + // После включения Dart пришлёт свежее число, старое было бы враньём. if (!value) { - delivered = 0 + unread = 0 connected = false } prefs(ctx).edit() .putBoolean(KEY_ENABLED, value) - .putInt(KEY_DELIVERED, delivered) + .putInt(KEY_UNREAD, unread) .apply() } - fun countDelivered(ctx: Context) { - delivered += 1 - prefs(ctx).edit().putInt(KEY_DELIVERED, delivered).apply() + fun applyUnread(ctx: Context, value: Int): Boolean { + val next = value.coerceAtLeast(0) + if (next == unread) return false + unread = next + prefs(ctx).edit().putInt(KEY_UNREAD, next).apply() + return true } } @@ -72,7 +76,16 @@ object FkmNotification { ctx.getString(R.string.fkm_status_inactive) } val title = ctx.getString(R.string.fkm_title) - val text = ctx.getString(R.string.fkm_status_line, status, FkmState.delivered) + val unread = FkmState.unread + val text = if (unread > 0) { + ctx.getString( + R.string.fkm_status_line, + status, + ctx.resources.getQuantityString(R.plurals.fkm_unread, unread, unread), + ) + } else { + status + } val immutable = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE val open = PendingIntent.getActivity( diff --git a/android/app/src/main/kotlin/ru/komet/app/MainActivity.kt b/android/app/src/main/kotlin/ru/komet/app/MainActivity.kt index c5ccdb1d..ba605ed2 100644 --- a/android/app/src/main/kotlin/ru/komet/app/MainActivity.kt +++ b/android/app/src/main/kotlin/ru/komet/app/MainActivity.kt @@ -350,26 +350,24 @@ class MainActivity : AudioServiceFragmentActivity() { result.success(p) } "notifyAccepted" -> { - val caller = call.argument("caller") ?: "Звонок" CallRinger.stop(call.argument("conversationId")) NotificationManagerCompat.from(this).cancel(CallConst.NOTIF_ID) - CallForegroundService.start(applicationContext, caller) + CallForegroundService.start(applicationContext, call.argument("caller")) result.success(null) } "ensureOngoing" -> { - val caller = call.argument("caller") ?: "Звонок" - CallForegroundService.start(applicationContext, caller) + CallForegroundService.start(applicationContext, call.argument("caller")) result.success(null) } "setScreenShare" -> { val enabled = call.argument("enabled") ?: false - val caller = call.argument("caller") ?: "Звонок" - CallForegroundService.setScreenShare( - applicationContext, - enabled, - caller, + result.success( + CallForegroundService.setScreenShare( + applicationContext, + enabled, + call.argument("caller"), + ), ) - result.success(null) } "dropOngoing" -> { CallForegroundService.stop(applicationContext) @@ -1041,6 +1039,7 @@ class MainActivity : AudioServiceFragmentActivity() { override fun onResume() { super.onResume() AppState.resumed = true + CallForegroundService.refreshTypes() stashChatOpen(intent, emit = true) } diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index 64d83e7a..0e46394b 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -5,7 +5,13 @@ Komet · сервис уведомлений Соединение активно Соединение не активно - %1$s · принято %2$d + %1$s · %2$s + + %d новое сообщение + %d новых сообщения + %d новых сообщений + %d новых сообщения + Это уведомление держит фоновое соединение с сервером, чтобы сообщения приходили без гугловых пушей. Убрать его можно, выключив FKM — кнопкой ниже или в Настройки → Уведомления → FKM. Выключить Удалено: diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 95b48be8..bd769f5a 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -7,7 +7,11 @@ Komet · notification service Connection active Connection inactive - %1$s · %2$d delivered + %1$s · %2$s + + %d new message + %d new messages + This notification is what keeps a background connection to the server, so messages arrive without Google push. To get rid of it, turn FKM off — with the button below, or in Settings → Notifications → FKM. Turn off Deleted: diff --git a/assets/wallpapers/patterns/bubbles.svg b/assets/wallpapers/patterns/bubbles.svg deleted file mode 100644 index 590fc102..00000000 --- a/assets/wallpapers/patterns/bubbles.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/assets/wallpapers/patterns/hearts.svg b/assets/wallpapers/patterns/hearts.svg deleted file mode 100644 index ac5f0d86..00000000 --- a/assets/wallpapers/patterns/hearts.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/assets/wallpapers/patterns/komet.svg b/assets/wallpapers/patterns/komet.svg new file mode 100644 index 00000000..845857ab --- /dev/null +++ b/assets/wallpapers/patterns/komet.svg @@ -0,0 +1 @@ + diff --git a/assets/wallpapers/patterns/planes.svg b/assets/wallpapers/patterns/planes.svg deleted file mode 100644 index 525b9dda..00000000 --- a/assets/wallpapers/patterns/planes.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/assets/wallpapers/patterns/plus.svg b/assets/wallpapers/patterns/plus.svg deleted file mode 100644 index fb558b6e..00000000 --- a/assets/wallpapers/patterns/plus.svg +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - diff --git a/assets/wallpapers/patterns/rings.svg b/assets/wallpapers/patterns/rings.svg deleted file mode 100644 index cbd62a41..00000000 --- a/assets/wallpapers/patterns/rings.svg +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/assets/wallpapers/patterns/stars.svg b/assets/wallpapers/patterns/stars.svg deleted file mode 100644 index 88c305a2..00000000 --- a/assets/wallpapers/patterns/stars.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/assets/whats_new/en.txt b/assets/whats_new/en.txt new file mode 100644 index 00000000..76602c61 --- /dev/null +++ b/assets/whats_new/en.txt @@ -0,0 +1,40 @@ +// Lines without indentation are the notes users see. +// [words](#scenario) makes those words tappable; "… → #scenario" at the end makes the whole line tappable. +// A link works instead of a #scenario too: :settings/storage, max.ru/channel/123, https://… +// #name starts a scenario, its steps follow indented. Commands and targets: CLAUDE.md, "What's new". +// Check the file and get the Google Play text: dart run tool/whats_new.dart + +• [Stories](#stories): reply, like, open the author's profile, hide their stories, save a story or report it. +• Video stories open faster, fill the screen properly and are no longer downloaded again on every view. +• Story replies now show up properly in chats. +• Calls: switching between the front and back camera works again, a call connects even if you turn the camera on before the other person answers, and calls connect more reliably on the first try. → #calls +• A chat with unread messages no longer opens with an empty gap instead of messages. +• Tabs switch instantly without flashing the screens in between. Appearance now has a switch to turn off animations. → #animations +• When MAX requires a sign-in password, Komet now shows a clear screen with instructions. +• Settings now have [Storage](#storage): see what takes up space, clear the cache and cap its size. +• Links are now checked: before you open a new site, Komet shows its address and highlights fake ones with swapped letters. → #links + +#stories + tab chats + scroll top + notify "Pull the chat list down to see stories at the top" + +#calls + tab calls + highlight nav.calls + +#animations + tab settings + tap settings.customization + tap settings.appearance + highlight appearance.animations + hint appearance.animations "Turn interface animations off here" + +#storage + tab settings + tap settings.storage + highlight storage.limit + +// The "о" in kоmet below is Cyrillic on purpose. +#links + check https://kоmet.example/login diff --git a/assets/whats_new/ru.txt b/assets/whats_new/ru.txt new file mode 100644 index 00000000..0be2c1df --- /dev/null +++ b/assets/whats_new/ru.txt @@ -0,0 +1,40 @@ +// Строки без отступа — пункты, их видит пользователь. +// [слова](#сценарий) — кликабельны эти слова; «… → #сценарий» в конце строки — вся строка. +// Вместо #сценария можно ссылку: :settings/storage, max.ru/канал/123, https://… +// #имя — сценарий, его шаги ниже с отступом. Команды и элементы — в CLAUDE.md, «What's new». +// Проверка файла и текст для Google Play: dart run tool/whats_new.dart +// СПАСИБО О ВЕЛiКi🚴‍♂️ КЛОД +• [Истории](#stories): можно ответить, поставить лайк, перейти в профиль автора, скрыть его истории, сохранить историю или пожаловаться. +• Видео в историях открываются быстрее, показываются в полный размер и больше не скачиваются заново при каждом просмотре. +• Ответы на истории теперь нормально отображаются в чате. +• Звонки: снова переключается фронтальная и основная камера, звонок соединяется, даже если включить камеру до ответа собеседника, и подключается надёжнее с первой попытки. → #calls +• Чат с непрочитанными больше не открывается с пустым местом вместо сообщений. +• Вкладки переключаются сразу, без мелькания экранов между ними. В Оформлении появился переключатель анимаций. → #animations +• Если MAX требует установить пароль для входа, Комета теперь показывает понятный экран с инструкцией. +• В настройках появилась [Память](#storage): видно, что сколько места занимает, кэш можно очистить и ограничить по размеру. +• Ссылки теперь проверяются: перед переходом на новый сайт Комета покажет его адрес, а поддельный адрес с подменёнными буквами подсветит. → #links + +#stories + tab chats + scroll top + notify "Потяните список чатов вниз — сверху появятся истории" + +#calls + tab calls + highlight nav.calls + +#animations + tab settings + tap settings.customization + tap settings.appearance + highlight appearance.animations + hint appearance.animations "Здесь можно выключить анимации интерфейса" + +#storage + tab settings + tap settings.storage + highlight storage.limit + +// В адресе ниже буква «о» в kоmet кириллическая, так и задумано. +#links + check https://kоmet.example/login diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 554e33bd..56fbbc5e 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -33,6 +33,8 @@ 9BDF85BC70348818AEF10CBA /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A63E96B763FA654541020DC2 /* Security.framework */; }; B1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */; }; B1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */; }; + D152A1B2C3D4E5F607182930 /* MinimalIcon-76@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = C152A1B2C3D4E5F607182930 /* MinimalIcon-76@2x.png */; }; + D167A1B2C3D4E5F607182930 /* MinimalIcon-83.5@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = C167A1B2C3D4E5F607182930 /* MinimalIcon-83.5@2x.png */; }; BB80EDFFF111F138D3411790 /* KometShareStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDAACAA16E141CC00CF7D7A6 /* KometShareStore.swift */; }; D3E790B969E6525B6B35F151 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6792C66B074C477FB31A4F02 /* ShareViewController.swift */; }; E835CC948F2F948DC3BBF405 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2AE8CB2654009FE276CACA4B /* Pods_RunnerTests.framework */; }; @@ -120,6 +122,8 @@ 9D7B0FFE63E0BD5D67D7758D /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@2x.png"; sourceTree = ""; }; A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon@3x.png"; sourceTree = ""; }; + C152A1B2C3D4E5F607182930 /* MinimalIcon-76@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon-76@2x.png"; sourceTree = ""; }; + C167A1B2C3D4E5F607182930 /* MinimalIcon-83.5@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "MinimalIcon-83.5@2x.png"; sourceTree = ""; }; A63E96B763FA654541020DC2 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; A92990150F2CFE8F72ACA01D /* ShareExtension-Bridging-Header.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "ShareExtension-Bridging-Header.h"; sourceTree = ""; }; D53D7B6C0957C1CD6DB59B64 /* KometShareAccounts.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = KometShareAccounts.swift; sourceTree = ""; }; @@ -247,6 +251,8 @@ 97C147021CF9000F007C117D /* Info.plist */, A1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png */, A1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png */, + C152A1B2C3D4E5F607182930 /* MinimalIcon-76@2x.png */, + C167A1B2C3D4E5F607182930 /* MinimalIcon-83.5@2x.png */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, @@ -430,6 +436,8 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, B1B2C3D41234567890ABCDEF /* MinimalIcon@2x.png in Resources */, B1B2C3D41234567890ABCDF0 /* MinimalIcon@3x.png in Resources */, + D152A1B2C3D4E5F607182930 /* MinimalIcon-76@2x.png in Resources */, + D167A1B2C3D4E5F607182930 /* MinimalIcon-83.5@2x.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index 1749179c..570acc82 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -25,6 +25,22 @@ + CFBundleIcons~ipad + + CFBundleAlternateIcons + + MinimalIcon + + CFBundleIconFiles + + MinimalIcon-76 + MinimalIcon-83.5 + + UIPrerenderedIcon + + + + CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion @@ -83,12 +99,16 @@ Face ID разблокирует Komet вместо кода-пароля. NSLocationWhenInUseUsageDescription Геолокация нужна, чтобы вы могли отправить своё местоположение в чат. + NSLocationAlwaysAndWhenInUseUsageDescription + Геолокация нужна, чтобы вы могли отправить своё местоположение в чат. NSMicrophoneUsageDescription Микрофон нужен для записи голосовых сообщений, видео и звонков. NSPhotoLibraryAddUsageDescription Доступ к галерее нужен, чтобы сохранять полученные фото и видео. NSPhotoLibraryUsageDescription Доступ к галерее нужен, чтобы отправлять фото и видео в чатах. + NSSpeechRecognitionUsageDescription + Распознавание речи нужно, чтобы превращать голосовые сообщения в текст. UIApplicationSceneManifest diff --git a/ios/Runner/MinimalIcon-76@2x.png b/ios/Runner/MinimalIcon-76@2x.png new file mode 100644 index 00000000..36c7f017 Binary files /dev/null and b/ios/Runner/MinimalIcon-76@2x.png differ diff --git a/ios/Runner/MinimalIcon-83.5@2x.png b/ios/Runner/MinimalIcon-83.5@2x.png new file mode 100644 index 00000000..8268caf3 Binary files /dev/null and b/ios/Runner/MinimalIcon-83.5@2x.png differ diff --git a/lib/backend/modules/account.dart b/lib/backend/modules/account.dart index e110cb74..8366cf66 100644 --- a/lib/backend/modules/account.dart +++ b/lib/backend/modules/account.dart @@ -221,17 +221,54 @@ class AccountModule { logger.i('Отправка OTP-кода (opcode=${Opcode.auth})'); - final packet = await _api.sendRequest(Opcode.auth, payload); + final packet = await _api.sendRequest(Opcode.auth, payload, silent: true); - final data = _requireMapPayload(packet, 'verifyCode'); + return _acceptVerification( + _requireMapPayload(packet, 'verifyCode'), + 'verifyCode', + ); + } + + Future checkCallOut(String trackId) async { + _ensureOnline(); + + final packet = await _api.sendRequest(Opcode.authCheckCall, { + 'trackId': trackId, + }); + + final check = CallOutCheck.fromPayload( + _requireMapPayload(packet, 'checkCallOut').cast(), + ); + logger.d( + '[${_api.debugTag}] checkCallOut: статус=${check.status?.name} ' + 'номер для звонка=${check.callNumber != null}', + ); + return check; + } + + Future loginByTrack(String trackId) async { + _ensureOnline(); + logger.i('Вход после звонка (opcode=${Opcode.authByTrack})'); + + final packet = await _api.sendRequest(Opcode.authByTrack, { + 'trackId': trackId, + }, silent: true); + + return _acceptVerification( + _requireMapPayload(packet, 'loginByTrack'), + 'loginByTrack', + ); + } + + Future _acceptVerification(Map data, String method) async { final result = VerifyCodeResult(payload: data.cast()); final loginToken = result.loginToken; final verifiedProfile = _profileFromVerifyPayload(result.payload); final accountId = result.accountId ?? verifiedProfile?.id; logger.d( - '[${_api.debugTag}] verifyCode: нужен пароль=${result.requiresPassword} ' + '[${_api.debugTag}] $method: нужен пароль=${result.requiresPassword} ' 'регистрация=${result.isRegistration} ' 'login-токен ${_describeSecret(loginToken)} accountId=$accountId ' 'профиль в ответе=${verifiedProfile != null} ' @@ -320,6 +357,7 @@ class AccountModule { int? accountId, String? token, LoginSyncParams? syncParams, + String? accountPhone, }) async { _ensureOnline(); @@ -362,7 +400,12 @@ class AccountModule { // #***! вошли по чужому токену, id узнаём из ответа if (resolvedAccountId == null) { - resolvedAccountId = extractAccountId(dataMap); + resolvedAccountId = await resolveLoginAccountId( + dataMap, + phone: accountPhone, + lookupByPhone: (phone) async => + (await ContactsModule.findByPhone(_api, phone, silent: true))?.id, + ); if (resolvedAccountId == null) { logger.e( 'login: accountId не найден в ответе; ' @@ -435,7 +478,7 @@ class AccountModule { } // #***! вход по чужому токену из дев меню - Future loginWithToken(String token) async { + Future loginWithToken(String token, {String? accountPhone}) async { if (token.isEmpty) { throw StateError('loginWithToken: пустой токен'); } @@ -464,7 +507,7 @@ class AccountModule { } logger.i('Вход по токену: сессия поднята со спуфом, выполняю login'); - return login(token: token); + return login(token: token, accountPhone: accountPhone); } // #***! Экспериментальный SMS-вход через веб. Веб-клиент MAX всегда шлёт код по @@ -1242,6 +1285,11 @@ class AccountModule { SyncKey.folderFiltersEnabled, serverConfig['enable-filters-for-folders'] == true ? '1' : '0', ); + await AppDatabase.setSyncValue( + accountId, + SyncKey.viewsCountEnabled, + serverConfig['views-count-enabled'] == true ? '1' : '0', + ); await _persistEntryBannerApps(accountId, serverConfig); final moneyBotId = parseIntOrNull( serverConfig[MoneyTransferApp.configKey], @@ -1318,11 +1366,22 @@ class AccountModule { throw Exception('requestCode: отсутствует token в ответе сервера'); } - logger.i('OTP-код запрошен, получен временный токен'); + final rawCallOut = data['callOutParams']; + final callOut = CallOutParams.tryParse(rawCallOut); + if (rawCallOut != null && callOut == null) { + logger.w('requestCode: callOutParams без trackId/ttl/pollingInterval'); + } + + logger.i( + callOut == null + ? 'OTP-код запрошен, получен временный токен' + : 'Сервер ждёт звонка с номера, опрос раз в ' + '${callOut.pollingInterval.inMilliseconds} мс', + ); logger.d( '[${_api.debugTag}] requestCode: ключи ответа=${data.keys.toList()}', ); - return RequestCodeResult(token: token); + return RequestCodeResult(token: token, callOut: callOut); } // #***! дальше три помощника diff --git a/lib/backend/modules/account/account_models.dart b/lib/backend/modules/account/account_models.dart index bf4257d6..e8a4759f 100644 --- a/lib/backend/modules/account/account_models.dart +++ b/lib/backend/modules/account/account_models.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import '../../../core/storage/app_database.dart'; +import '../../../core/utils/parse.dart'; // #***! модели аккаунта, авторизация приватность сессии int? _coerceAccountId(dynamic value) { @@ -50,6 +51,26 @@ int? extractAccountId(dynamic response) { _coerceAccountId(response['account_id']); } +typedef AccountIdByPhoneLookup = Future Function(String phone); + +// #***! LOGIN не всегда возвращает profile для уже известного серверу токена. +// В таком случае review-вход может восстановить id по номеру, который всё равно +// известен из специального сценария авторизации. +Future resolveLoginAccountId( + dynamic response, { + String? phone, + AccountIdByPhoneLookup? lookupByPhone, +}) async { + final embedded = extractAccountId(response); + if (embedded != null) return embedded; + + final phoneHint = phone?.trim(); + if (phoneHint == null || phoneHint.isEmpty || lookupByPhone == null) { + return null; + } + return lookupByPhone(phoneHint); +} + // #***! описание формы ответа для лога когда id не нашли String describeResponseShape(dynamic response) { if (response is! Map) return 'не-Map (${response.runtimeType})'; @@ -338,8 +359,70 @@ class WrongPasswordException implements Exception { // #***! временный токен сценария авторизации class RequestCodeResult { final String token; + final CallOutParams? callOut; + + const RequestCodeResult({required this.token, this.callOut}); +} + +class CallOutParams { + final String trackId; + final Duration ttl; + final Duration pollingInterval; - const RequestCodeResult({required this.token}); + const CallOutParams({ + required this.trackId, + required this.ttl, + required this.pollingInterval, + }); + + static CallOutParams? tryParse(Object? raw) { + if (raw is! Map) return null; + final trackId = raw['trackId']; + final ttl = parseIntOrNull(raw['ttl']); + final interval = parseIntOrNull(raw['pollingInterval']); + if (trackId is! String || trackId.isEmpty) return null; + if (ttl == null || ttl <= 0 || interval == null || interval <= 0) { + return null; + } + return CallOutParams( + trackId: trackId, + ttl: Duration(milliseconds: ttl), + pollingInterval: Duration(milliseconds: interval), + ); + } +} + +enum CallOutStatus { + numberNotAssigned(0), + numberAssigned(1), + verificationPassed(2), + verificationTimeout(3); + + const CallOutStatus(this.code); + final int code; + + static CallOutStatus? fromCode(Object? raw) { + final code = parseIntOrNull(raw); + for (final status in values) { + if (status.code == code) return status; + } + return null; + } +} + +class CallOutCheck { + final CallOutStatus? status; + final String? callNumber; + + const CallOutCheck({required this.status, this.callNumber}); + + factory CallOutCheck.fromPayload(Map payload) { + final number = payload['callNumber']; + return CallOutCheck( + status: CallOutStatus.fromCode(payload['status']), + callNumber: number is String && number.isNotEmpty ? number : null, + ); + } } class PresetAvatar { diff --git a/lib/backend/modules/banners.dart b/lib/backend/modules/banners.dart index e8d01f0b..5f904969 100644 --- a/lib/backend/modules/banners.dart +++ b/lib/backend/modules/banners.dart @@ -43,6 +43,7 @@ class BannersModule { // #***! _pinnedId держит баннер на экране чтоб не менялся под пальцем String? _pinnedId; Future? _syncing; + InformerBanner? _preview; bool get isEnabled => _enabled; int get showTime => _showTime; @@ -130,9 +131,16 @@ class BannersModule { return true; } + void preview(InformerBanner? banner) { + _preview = banner; + _recompute(); + } + + bool _isPreview(InformerBanner banner) => banner.id == _preview?.id; + // #***! первый показ фиксит время, от него срок жизни Future markShown(InformerBanner banner) async { - if (_pinnedId == banner.id) return; + if (_isPreview(banner) || _pinnedId == banner.id) return; final now = DateTime.now().millisecondsSinceEpoch; final current = stateOf(banner.id); _showState[banner.id] = current.copyWith( @@ -146,6 +154,7 @@ class BannersModule { // #***! закрыли крестиком, помним до истечения rerun Future close(InformerBanner banner) async { + if (_isPreview(banner)) return preview(null); final now = DateTime.now().millisecondsSinceEpoch; _showState[banner.id] = stateOf(banner.id).copyWith(closedAt: now); if (_pinnedId == banner.id) _pinnedId = null; @@ -155,6 +164,7 @@ class BannersModule { Future markClicked(InformerBanner banner) async { if (!banner.closesOnClick) return; + if (_isPreview(banner)) return preview(null); await close(banner); } @@ -207,6 +217,11 @@ class BannersModule { // #***! выбираем активный, закреплённый или самый приоритетный void _recompute() { + final preview = _preview; + if (preview != null) { + activeBanner.value = preview; + return; + } if (!_enabled) { activeBanner.value = null; return; diff --git a/lib/backend/modules/channel_stats.dart b/lib/backend/modules/channel_stats.dart new file mode 100644 index 00000000..f67ecfa4 --- /dev/null +++ b/lib/backend/modules/channel_stats.dart @@ -0,0 +1,56 @@ +import '../api.dart'; +import '../../core/protocol/opcode_map.dart'; +import '../../core/protocol/packet.dart'; +import '../../core/utils/logger.dart'; + +class ChannelStats { + const ChannelStats._(); + + static const int maxBatch = 100; + + static Future?> views( + Api api, + int chatId, + List messageIds, { + required bool countView, + }) async { + final payload = requestPayload(chatId, messageIds, countView: countView); + if ((payload['messageIds'] as List).isEmpty) return const {}; + try { + final packet = await api.sendRequest( + Opcode.msgGetStat, + payload, + silent: true, + ); + return packet.isOk ? parseViews(packet.payload) : null; + } on PacketError catch (e) { + logger.w('ChannelStats.views refused: $e'); + return null; + } catch (e) { + logger.w('ChannelStats.views: $e'); + return const {}; + } + } + + static Map requestPayload( + int chatId, + List messageIds, { + required bool countView, + }) => { + 'chatId': chatId, + 'messageIds': [ + for (final id in messageIds) ?int.tryParse(id), + ].take(maxBatch).toList(), + if (!countView) 'readOnly': true, + }; + + static Map parseViews(Object? payload) { + final stats = payload is Map ? payload['stats'] : null; + if (stats is! Map) return const {}; + return { + for (final MapEntry(:key, :value) in stats.entries) + if (value is Map && value['views'] is int) + key.toString(): value['views'] as int, + }; + } +} diff --git a/lib/backend/modules/channel_suggestions.dart b/lib/backend/modules/channel_suggestions.dart new file mode 100644 index 00000000..88ba0ec9 --- /dev/null +++ b/lib/backend/modules/channel_suggestions.dart @@ -0,0 +1,70 @@ +import '../api.dart'; +import '../../core/protocol/opcode_map.dart'; +import '../../core/utils/logger.dart'; +import '../../models/suggested_channel.dart'; + +class ChannelSuggestions { + const ChannelSuggestions._(); + + static const int _ownChannelsLimit = 20; + static const Duration _freshFor = Duration(minutes: 30); + static final Map< + ({int account, int chat}), + ({DateTime at, List channels}) + > + _recent = {}; + + static Future> forChannel( + Api api, + int chatId, { + required int accountId, + required Iterable ownChannelIds, + }) async { + final own = {...ownChannelIds}..remove(chatId); + final key = (account: accountId, chat: chatId); + final now = DateTime.now(); + _recent.removeWhere((_, entry) => now.difference(entry.at) >= _freshFor); + final channels = + _recent[key]?.channels ?? await _request(api, chatId, own, key); + return [ + for (final channel in channels) + if (!own.contains(channel.id)) channel, + ]; + } + + static Future> _request( + Api api, + int chatId, + Set own, + ({int account, int chat}) key, + ) async { + try { + final packet = await api.sendRequest(Opcode.chatSuggest, { + 'chatId': chatId, + 'userChatIds': [chatId, ...own.take(_ownChannelsLimit)], + }, silent: true); + final channels = parse( + packet.isOk ? packet.payload : null, + exclude: chatId, + ); + if (channels.isNotEmpty) { + _recent[key] = (at: DateTime.now(), channels: channels); + } + return channels; + } catch (e) { + logger.w('ChannelSuggestions.forChannel: $e'); + return const []; + } + } + + static List parse(Object? payload, {required int exclude}) { + final chats = payload is Map ? payload['chats'] : null; + if (chats is! List) return const []; + return [ + for (final raw in chats) + if (SuggestedChannel.fromServer(raw) case final channel? + when channel.id != exclude) + channel, + ]; + } +} diff --git a/lib/backend/modules/chats.dart b/lib/backend/modules/chats.dart index 4efb7d7b..4aca89f6 100644 --- a/lib/backend/modules/chats.dart +++ b/lib/backend/modules/chats.dart @@ -575,12 +575,12 @@ class ChatsModule { final row = Map.from(rows.first); if ((row['unread_count'] as int? ?? 0) == 0) return; - final ghost = KometSettings.ghostMode.value; - if (ghost) { - await _rememberGhostRead(accountId, chatId, rows.first, mark); + final readsStayLocal = _readsStayLocal; + if (readsStayLocal) { + await _rememberLocalRead(accountId, chatId, rows.first, mark, left: 0); } final msgIdNum = int.tryParse(messageId); - if (msgIdNum != null && !KometSettings.antiRead.value && !ghost) { + if (msgIdNum != null && !readsStayLocal) { try { await api.sendRequest(Opcode.chatMark, { 'type': 'READ_MESSAGE', @@ -611,9 +611,9 @@ class ChatsModule { int mark, { required int remaining, }) async { - final ghost = KometSettings.ghostMode.value; + final readsStayLocal = _readsStayLocal; final msgIdNum = int.tryParse(messageId); - if (msgIdNum != null && !KometSettings.antiRead.value && !ghost) { + if (msgIdNum != null && !readsStayLocal) { try { await api.sendRequest(Opcode.chatMark, { 'type': 'READ_MESSAGE', @@ -626,11 +626,11 @@ class ChatsModule { final rows = await AppDatabase.loadChat(accountId, chatId); if (rows.isEmpty) return; - if (ghost) { - await _rememberGhostRead(accountId, chatId, rows.first, mark); + final next = remaining < 0 ? 0 : remaining; + if (readsStayLocal) { + await _rememberLocalRead(accountId, chatId, rows.first, mark, left: next); } final cached = CachedChat.fromDbRow(rows.first); - final next = remaining < 0 ? 0 : remaining; final currentMark = cached.participants[accountId] ?? 0; final nextMark = mark > currentMark ? mark : currentMark; if (cached.unreadCount == next && nextMark == currentMark) { @@ -665,6 +665,7 @@ class ChatsModule { } if (unread == null) return null; + await GhostReadStore.instance.forget(accountId, chatId); await _updateChat(accountId, chatId, (chat) { final participants = Map.from(chat.participants) ..[accountId] = mark - 1; @@ -932,31 +933,81 @@ class ChatsModule { unawaited(ChatInfoFetch.get(chatId)); } - Future _rememberGhostRead( + static bool get _readsStayLocal => + KometSettings.ghostMode.value || KometSettings.antiRead.value; + + Future _rememberLocalRead( int accountId, int chatId, Map row, - int mark, - ) { + int mark, { + required int left, + }) { final cached = CachedChat.fromDbRow(row); - return GhostReadStore.instance.remember( + return GhostReadStore.instance.noteLocalRead( accountId, chatId, mark: mark, - unread: cached.unreadCount, - ownMark: cached.participants[accountId] ?? 0, + left: left, + serverUnread: cached.unreadCount, + serverOwnMark: cached.participants[accountId] ?? 0, + ); + } + + CachedChat _withLocalRead(int accountId, CachedChat server) { + final local = GhostReadStore.instance.of(accountId, server.id); + if (local == null) return server; + final serverMark = server.participants[accountId] ?? 0; + if (serverMark >= local.mark) { + unawaited(GhostReadStore.instance.forget(accountId, server.id)); + return server; + } + unawaited( + GhostReadStore.instance.noteServer( + accountId, + server.id, + unread: server.unreadCount, + ownMark: serverMark, + ), + ); + return server.copyWith( + unreadCount: local.unreadFor( + server.unreadCount, + lastMessageTime: server.lastMsgTime, + ), + participants: Map.from(server.participants) + ..[accountId] = local.mark, + ); + } + + int _unreadWithLocalRead( + int accountId, + int chatId, + int serverUnread, { + int? lastMessageTime, + }) { + final local = GhostReadStore.instance.of(accountId, chatId); + if (local == null) return serverUnread; + unawaited( + GhostReadStore.instance.noteServer( + accountId, + chatId, + unread: serverUnread, + ), ); + return local.unreadFor(serverUnread, lastMessageTime: lastMessageTime); } Future restoreGhostReads() async { + await GhostReadStore.instance.load(); final entries = GhostReadStore.instance.snapshot(); for (final entry in entries) { final read = entry.read; await _updateChat(entry.accountId, entry.chatId, (chat) { final participants = Map.from(chat.participants) - ..[entry.accountId] = read.ownMark; + ..[entry.accountId] = read.serverOwnMark; return chat.copyWith( - unreadCount: read.unread, + unreadCount: read.serverUnread, participants: participants, ); }); @@ -1285,7 +1336,12 @@ class ChatsModule { ); } else if (unread != null) { final newRow = Map.from(rows.first); - newRow['unread_count'] = unread; + newRow['unread_count'] = _unreadWithLocalRead( + accountId, + chatId, + unread, + lastMessageTime: cachedChat.lastMsgTime, + ); await _commitChatContent([(rows.first, newRow)]); } _messageEventsController.add( @@ -1389,7 +1445,14 @@ class ChatsModule { if (senderId != null) newRow['last_msg_sender'] = senderId; newRow['last_msg_status'] = 'sent'; } - if (unread != null) newRow['unread_count'] = unread; + if (unread != null) { + newRow['unread_count'] = _unreadWithLocalRead( + accountId, + chatId, + unread, + lastMessageTime: newRow['last_msg_time'] as int?, + ); + } if (msgIdInt != null && status != 'REMOVED' && @@ -1478,7 +1541,14 @@ class ChatsModule { newRow['last_msg_sender'] = null; newRow['last_msg_status'] = null; } - if (unread != null) newRow['unread_count'] = unread; + if (unread != null) { + newRow['unread_count'] = _unreadWithLocalRead( + accountId, + chatId, + unread, + lastMessageTime: newRow['last_msg_time'] as int?, + ); + } await _commitChatContent([(chatRow, newRow)]); } @@ -1630,19 +1700,43 @@ class ChatsModule { final ownRead = userId == accountId; final serverUnread = payload['unread']; final lastTime = cached.lastMsgTime; + final local = ownRead + ? GhostReadStore.instance.of(accountId, chatId) + : null; + final keepsLocal = local != null && mark < local.mark; + if (local != null && !keepsLocal) { + await GhostReadStore.instance.forget(accountId, chatId); + } + if (keepsLocal) { + await GhostReadStore.instance.noteServer( + accountId, + chatId, + ownMark: mark, + ); + } final unread = !ownRead ? cached.unreadCount : serverUnread is int - ? serverUnread + ? (keepsLocal + ? _unreadWithLocalRead( + accountId, + chatId, + serverUnread, + lastMessageTime: lastTime, + ) + : serverUnread) : lastTime != null && mark >= lastTime ? 0 : cached.unreadCount; - if (cached.participants[userId] == mark && unread == cached.unreadCount) { + final shownMark = keepsLocal ? local.mark : mark; + if (cached.participants[userId] == shownMark && + unread == cached.unreadCount) { return; } final updated = cached.copyWith( unreadCount: unread, - participants: Map.from(cached.participants)..[userId] = mark, + participants: Map.from(cached.participants) + ..[userId] = shownMark, ); await _commitChatContent([(rows.first, updated.toDbRow())]); if (ownRead && unread == 0) { @@ -1747,7 +1841,7 @@ class ChatsModule { existing = {id: CachedChat.fromDbRow(existingRow)}; } } - final parsed = parseChatRow( + final serverChat = parseChatRow( chat, accountId, accountId, @@ -1757,10 +1851,11 @@ class ChatsModule { existing, cachedAt, ); - if (parsed == null) { + if (serverChat == null) { logger.w('cacheServerChat: parse returned null for chat=${chat['id']}'); return null; } + final parsed = _withLocalRead(accountId, serverChat); final ex = existing[parsed.id]; final listState = !inList ? ChatListState.notInList @@ -1844,7 +1939,7 @@ class ChatsModule { for (final c in chats.whereType()) { final map = c.cast(); ChatMembersStore.instance.applyChatPayload(map); - final parsed = parseChatRow( + final serverChat = parseChatRow( map, accountId, currentUserId, @@ -1854,7 +1949,8 @@ class ChatsModule { existing, cachedAt, ); - if (parsed == null) continue; + if (serverChat == null) continue; + final parsed = _withLocalRead(accountId, serverChat); final row = parsed.toDbRow(); row['in_list'] = chatListStateForStatus( map['status'], diff --git a/lib/backend/modules/cloud_storage.dart b/lib/backend/modules/cloud_storage.dart index 456c7696..50a07d31 100644 --- a/lib/backend/modules/cloud_storage.dart +++ b/lib/backend/modules/cloud_storage.dart @@ -161,14 +161,33 @@ class CloudStorageModule { } } - static Future> fetchFiles( + static const int pageSize = 100; + + static Future<({List files, int? oldestTime})> fetchPage( MessagesModule messages, int accountId, int chatId, { - int count = 200, + int? before, }) async { - final msgs = await messages.fetchHistory(accountId, chatId, count: count); - return _cloudFilesFrom(msgs, chatId, accountId).toList(); + final fetched = await messages.fetchHistory( + accountId, + chatId, + fromTime: before, + count: pageSize, + ); + final msgs = before == null + ? fetched + : [ + for (final m in fetched) + if (m.time < before) m, + ]; + int? oldest; + for (final m in msgs) { + if (oldest == null || m.time < oldest) oldest = m.time; + } + final files = _cloudFilesFrom(msgs, chatId, accountId).toList() + ..sort((a, b) => b.time.compareTo(a.time)); + return (files: files, oldestTime: oldest); } // Fetches only the last few messages to find a newly uploaded file — avoids full 200-msg reload diff --git a/lib/backend/modules/complaints.dart b/lib/backend/modules/complaints.dart index 2d29d736..9f32d661 100644 --- a/lib/backend/modules/complaints.dart +++ b/lib/backend/modules/complaints.dart @@ -14,6 +14,7 @@ class ComplaintReason { class ComplaintsModule { static const int channelTypeId = 2; static const int userTypeId = 6; + static const int storyTypeId = 9; // #***! справочник в рамках сессии не меняется, держим в памяти static Map>? _cache; diff --git a/lib/backend/modules/file_uploader.dart b/lib/backend/modules/file_uploader.dart index 83d53bbc..9312b8a6 100644 --- a/lib/backend/modules/file_uploader.dart +++ b/lib/backend/modules/file_uploader.dart @@ -68,6 +68,8 @@ class FileUploader { bool encryptedPayload = false, void Function()? beforeSend, int? scheduledTime, + int? replyToMessageId, + int? replySourceChatId, Duration autoForceAfter = const Duration(seconds: 1), Duration overallTimeout = const Duration(minutes: 5), Duration progressThrottle = const Duration(milliseconds: 16), @@ -167,6 +169,8 @@ class FileUploader { text: text, encryptedPayload: encryptedPayload, scheduledTime: scheduledTime, + replyToMessageId: replyToMessageId, + replySourceChatId: replySourceChatId, beforeSend: () { if (!identical(api.session, initialSession)) { throw StateError('Account changed during upload'); diff --git a/lib/backend/modules/messages.dart b/lib/backend/modules/messages.dart index 390c0ccc..9805f9a4 100644 --- a/lib/backend/modules/messages.dart +++ b/lib/backend/modules/messages.dart @@ -478,6 +478,8 @@ class ReplyInfo { return ''; case AttachmentType.forward: return 'Переслано'; + case AttachmentType.storyReply: + return 'История'; case AttachmentType.unknown: return 'Вложение'; } @@ -1156,21 +1158,16 @@ class MessagesModule { int? replyToMessageId, int? replySourceChatId, List> elements = const [], + List> attaches = const [], void Function()? beforeSend, }) async { final message = { 'text': text, 'cid': -_nextCid(), 'elements': elements, - 'attaches': [], + 'attaches': [...attaches], }; - if (replyToMessageId != null) { - message['link'] = { - 'type': 'REPLY', - 'chatId': replySourceChatId ?? chatId, - 'messageId': replyToMessageId, - }; - } + _linkReply(message, chatId, replyToMessageId, replySourceChatId); if (scheduledTime != null) { message['delayedAttributes'] = { 'timeToFire': scheduledTime, @@ -1189,6 +1186,20 @@ class MessagesModule { ); } + static void _linkReply( + Map message, + int chatId, + int? replyToMessageId, + int? replySourceChatId, + ) { + if (replyToMessageId == null) return; + message['link'] = { + 'type': 'REPLY', + 'chatId': replySourceChatId ?? chatId, + 'messageId': replyToMessageId, + }; + } + // #***! системное сообщение Future sendControlMessage( int chatId, @@ -1844,6 +1855,8 @@ class MessagesModule { Duration retryDelay = const Duration(seconds: 1), void Function()? beforeSend, bool encryptedPayload = false, + int? replyToMessageId, + int? replySourceChatId, }) async { final message = { 'isLive': false, @@ -1858,6 +1871,7 @@ class MessagesModule { ], }; if (text != null && text.isNotEmpty) message['text'] = text; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); if (scheduledTime != null) { message['delayedAttributes'] = { 'timeToFire': scheduledTime, @@ -1900,6 +1914,8 @@ class MessagesModule { int maxAttempts = 20, Duration retryDelay = const Duration(seconds: 1), void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { final message = { 'cid': -_nextCid(), @@ -1909,6 +1925,7 @@ class MessagesModule { ], }; if (caption != null && caption.isNotEmpty) message['text'] = caption; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); if (scheduledTime != null) { message['delayedAttributes'] = { 'timeToFire': scheduledTime, @@ -1963,6 +1980,8 @@ class MessagesModule { int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { final message = { 'isLive': false, @@ -1974,6 +1993,7 @@ class MessagesModule { ], }; if (caption != null && caption.isNotEmpty) message['text'] = caption; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); if (scheduledTime != null) { message['delayedAttributes'] = { 'timeToFire': scheduledTime, @@ -2028,6 +2048,8 @@ class MessagesModule { int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { final message = { 'isLive': false, @@ -2043,6 +2065,7 @@ class MessagesModule { }, ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); if (scheduledTime != null) { message['delayedAttributes'] = { 'timeToFire': scheduledTime, @@ -2097,6 +2120,8 @@ class MessagesModule { int maxAttempts = 30, Duration retryDelay = const Duration(seconds: 1), void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { final message = { 'isLive': false, @@ -2114,6 +2139,7 @@ class MessagesModule { }, ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); final payload = {'chatId': chatId, 'message': message, 'notify': notify}; return _sendWithNotReadyRetry?>( @@ -2133,22 +2159,22 @@ class MessagesModule { double zoom = 15, bool notify = true, void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { - final payload = { - 'chatId': chatId, - 'message': { - 'cid': -_nextCid(), - 'attaches': [ - { - '_type': 'LOCATION', - 'latitude': latitude, - 'longitude': longitude, - 'zoom': zoom, - }, - ], - }, - 'notify': notify, + final message = { + 'cid': -_nextCid(), + 'attaches': [ + { + '_type': 'LOCATION', + 'latitude': latitude, + 'longitude': longitude, + 'zoom': zoom, + }, + ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); + final payload = {'chatId': chatId, 'message': message, 'notify': notify}; final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); @@ -2159,17 +2185,17 @@ class MessagesModule { int contactId, { bool notify = true, void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { - final payload = { - 'chatId': chatId, - 'message': { - 'cid': -_nextCid(), - 'attaches': [ - {'_type': 'CONTACT', 'contactId': contactId}, - ], - }, - 'notify': notify, + final message = { + 'cid': -_nextCid(), + 'attaches': [ + {'_type': 'CONTACT', 'contactId': contactId}, + ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); + final payload = {'chatId': chatId, 'message': message, 'notify': notify}; final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); @@ -2186,27 +2212,27 @@ class MessagesModule { bool anonymous = true, bool notify = true, void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { final settings = (anonymous ? _pollAnonymousFlag : 0) | (multiple ? _pollMultipleFlag : 0); - final payload = { - 'chatId': chatId, - 'message': { - 'cid': -_nextCid(), - 'attaches': [ - { - '_type': 'POLL', - 'title': title, - 'settings': settings, - 'answers': [ - for (final a in answers) {'text': a}, - ], - }, - ], - }, - 'notify': notify, + final message = { + 'cid': -_nextCid(), + 'attaches': [ + { + '_type': 'POLL', + 'title': title, + 'settings': settings, + 'answers': [ + for (final a in answers) {'text': a}, + ], + }, + ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); + final payload = {'chatId': chatId, 'message': message, 'notify': notify}; final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); @@ -2229,17 +2255,17 @@ class MessagesModule { int stickerId, { bool notify = true, void Function()? beforeSend, + int? replyToMessageId, + int? replySourceChatId, }) async { - final payload = { - 'chatId': chatId, - 'message': { - 'cid': -_nextCid(), - 'attaches': [ - {'_type': 'STICKER', 'stickerId': stickerId}, - ], - }, - 'notify': notify, + final message = { + 'cid': -_nextCid(), + 'attaches': [ + {'_type': 'STICKER', 'stickerId': stickerId}, + ], }; + _linkReply(message, chatId, replyToMessageId, replySourceChatId); + final payload = {'chatId': chatId, 'message': message, 'notify': notify}; final response = await _sendUserMessage(payload, beforeSend: beforeSend); return _sentMessageMap(response); diff --git a/lib/backend/modules/outgoing_reply.dart b/lib/backend/modules/outgoing_reply.dart new file mode 100644 index 00000000..62ac5314 --- /dev/null +++ b/lib/backend/modules/outgoing_reply.dart @@ -0,0 +1,88 @@ +import 'messages.dart'; + +class OutgoingReply { + const OutgoingReply._(this.message, this.messageId, this.sourceChatId); + + static OutgoingReply? of(CachedMessage? message, {int? sourceChatId}) { + if (message == null) return null; + final id = int.tryParse(message.id); + if (id == null) return null; + return OutgoingReply._(message, id, sourceChatId); + } + + static OutgoingReply? fromPayload( + Map? payload, { + required int accountId, + required int chatId, + }) { + final link = payload?['link']; + if (link is! Map || (link['type'] as String?)?.toUpperCase() != 'REPLY') { + return null; + } + final quoted = link['message']; + if (quoted is! Map) return null; + final id = int.tryParse('${quoted['id']}'); + if (id == null) return null; + final sender = quoted['sender']; + final time = quoted['time']; + final forward = quoted['link']; + final source = link['chatId']; + return OutgoingReply._( + CachedMessage( + id: '$id', + accountId: accountId, + chatId: chatId, + senderId: sender is int ? sender : 0, + text: quoted['text'] as String?, + time: time is int ? time : 0, + payload: { + 'attaches': quoted['attaches'] ?? const [], + if (forward is Map) 'link': forward, + }, + ), + id, + source is int && source != chatId ? source : null, + ); + } + + final CachedMessage message; + final int messageId; + final int? sourceChatId; + + Map linkIn(int chatId) { + final sourceLink = message.payload?['link']; + return { + 'type': 'REPLY', + 'chatId': sourceChatId ?? chatId, + 'message': { + 'id': messageId, + 'sender': message.senderId, + 'text': message.text, + 'time': message.time, + 'attaches': message.payload?['attaches'] ?? const [], + if (sourceLink is Map && sourceLink['type'] == 'FORWARD') + 'link': sourceLink, + }, + }; + } + + CachedMessage quotedIn(CachedMessage outgoing) => outgoing.copyWith( + payload: {...?outgoing.payload, 'link': linkIn(outgoing.chatId)}, + ); + + static CachedMessage keepQuote(CachedMessage sent, CachedMessage? local) { + if (_quotesMessage(sent.payload)) return sent; + final localPayload = local?.payload; + if (!_quotesMessage(localPayload)) return sent; + return sent.copyWith( + payload: {...?sent.payload, 'link': localPayload!['link']}, + ); + } + + static bool _quotesMessage(Map? payload) { + final link = payload?['link']; + return link is Map && + (link['type'] as String?)?.toUpperCase() == 'REPLY' && + link['message'] is Map; + } +} diff --git a/lib/backend/modules/stories.dart b/lib/backend/modules/stories.dart index b5198066..5ed447f5 100644 --- a/lib/backend/modules/stories.dart +++ b/lib/backend/modules/stories.dart @@ -4,6 +4,7 @@ import 'dart:math' as math; import 'package:flutter/foundation.dart'; +import '../../core/config/komet_settings.dart'; import '../../core/protocol/opcode_map.dart'; import '../../core/protocol/packet.dart'; import '../../core/storage/app_database.dart'; @@ -22,6 +23,9 @@ class StoriesModule { static const _previewsKey = 'stories_previews'; static const _peersKey = 'stories_peers'; static const _progressKey = 'stories_progress'; + static const _hiddenAuthorsKey = 'stories_hidden_authors'; + static const _quietViewsKey = 'stories_quiet_views'; + static const Duration _quietViewFallbackTtl = Duration(hours: 48); final Api _api; @@ -32,6 +36,12 @@ class StoriesModule { /// ownerId → storyId, на котором пользователь остановил просмотр. final Map _lastViewed = {}; + final Set _hiddenAuthors = {}; + + final Map> _quietViews = {}; + + bool isAuthorHidden(int ownerId) => _hiddenAuthors.contains(ownerId); + int? _accountId; StreamSubscription? _pushSub; @@ -112,12 +122,33 @@ class StoriesModule { }); } } + + final rawHidden = await AppDatabase.getSyncValue(acc, _hiddenAuthorsKey); + if (rawHidden != null && rawHidden.isNotEmpty) { + final list = jsonDecode(rawHidden); + if (list is List) _hiddenAuthors.addAll(list.whereType()); + } + + final rawQuiet = await AppDatabase.getSyncValue(acc, _quietViewsKey); + if (rawQuiet != null && rawQuiet.isNotEmpty) { + _restoreQuietViews(jsonDecode(rawQuiet)); + } _bump(); } catch (e) { logger.w('StoriesModule.loadCache: $e'); } } + Future _persistHiddenAuthors() async { + final acc = await _acc(); + if (acc == null) return; + await AppDatabase.setSyncValue( + acc, + _hiddenAuthorsKey, + jsonEncode(_hiddenAuthors.toList()), + ); + } + // #***! три ключа в sync_state, кольца истории и позиции Future _persistPreviews() async { final acc = await _acc(); @@ -137,6 +168,39 @@ class StoriesModule { await AppDatabase.setSyncValue(acc, _peersKey, jsonEncode(map)); } + void _restoreQuietViews(Object? decoded) { + if (decoded is! Map) return; + final now = _nowMs(); + decoded.forEach((ownerKey, stories) { + final ownerId = int.tryParse('$ownerKey'); + if (ownerId == null || stories is! Map) return; + final views = _quietViews[ownerId] ??= {}; + stories.forEach((storyKey, expiresAt) { + final storyId = int.tryParse('$storyKey'); + final until = expiresAt is int ? expiresAt : int.tryParse('$expiresAt'); + if (storyId == null || until == null || until < now) return; + views.putIfAbsent(storyId, () => until); + }); + if (views.isEmpty) _quietViews.remove(ownerId); + }); + } + + Future _persistQuietViews() async { + final acc = await _acc(); + if (acc == null) return; + final now = _nowMs(); + final map = >{}; + _quietViews.forEach((ownerId, views) { + views.removeWhere((_, until) => until < now); + if (views.isEmpty) return; + map['$ownerId'] = { + for (final entry in views.entries) '${entry.key}': entry.value, + }; + }); + _quietViews.removeWhere((_, views) => views.isEmpty); + await AppDatabase.setSyncValue(acc, _quietViewsKey, jsonEncode(map)); + } + Future _persistProgress() async { final acc = await _acc(); if (acc == null) return; @@ -165,7 +229,10 @@ class StoriesModule { // #***! порядок колец, сначала непрочитанные потом по свежести /// Кольца-превью, отсортированные: сначала непрочитанные, затем по времени. List get previews { - final list = _previews.values.where((p) => !p.isEmpty).toList(); + final list = _previews.values + .where((p) => !p.isEmpty) + .map(_withQuietViews) + .toList(); list.sort((a, b) { if (a.hasUnread != b.hasUnread) return a.hasUnread ? -1 : 1; return b.updateTime.compareTo(a.updateTime); @@ -175,7 +242,32 @@ class StoriesModule { bool get hasAny => previews.isNotEmpty; - StoryPreview? previewFor(int ownerId) => _previews[ownerId]; + StoryPreview? previewFor(int ownerId) { + final preview = _previews[ownerId]; + return preview == null ? null : _withQuietViews(preview); + } + + StoryPreview _withQuietViews(StoryPreview preview) { + final views = _quietViews[preview.owner.ownerId]; + if (views == null || views.isEmpty) return preview; + final stories = _peerStories[preview.owner.ownerId]; + final int read; + if (stories == null) { + final now = _nowMs(); + read = + preview.readCount + + views.values.where((until) => until >= now).length; + } else { + var prefix = math.min(preview.readCount, stories.length); + while (prefix < stories.length && views.containsKey(stories[prefix].id)) { + prefix++; + } + read = prefix; + } + final capped = math.min(read, preview.totalCount); + if (capped <= preview.readCount) return preview; + return preview.copyWith(readCount: capped); + } // #***! превью чужих владельцев, отдельно от ленты final Map _peerPreviews = {}; @@ -186,9 +278,9 @@ class StoriesModule { StoryPreview? previewOf(int ownerId) { final feed = _previews[ownerId]; - if (feed != null) return feed.isEmpty ? null : feed; + if (feed != null) return feed.isEmpty ? null : _withQuietViews(feed); final peer = _peerPreviews[ownerId]; - return (peer == null || peer.isEmpty) ? null : peer; + return (peer == null || peer.isEmpty) ? null : _withQuietViews(peer); } // #***! пачками по 20, silent потому что фон @@ -251,7 +343,7 @@ class StoriesModule { for (final raw in rawPeers) { final peer = PeerStories.fromMap(raw); if (peer == null) continue; - _peerStories[peer.owner.ownerId] = peer.stories; + _setPeerStories(peer.owner.ownerId, peer.stories); changed = true; } } @@ -260,6 +352,17 @@ class StoriesModule { List? cachedStories(int ownerId) => _peerStories[ownerId]; + void _setPeerStories(int ownerId, List stories) { + _peerStories[ownerId] = stories; + final views = _quietViews[ownerId]; + if (views == null) return; + final alive = {for (final story in stories) story.id}; + final before = views.length; + views.removeWhere((storyId, _) => !alive.contains(storyId)); + if (views.isEmpty) _quietViews.remove(ownerId); + if (views.length != before) unawaited(_persistQuietViews()); + } + // #***! пуш об изменении колец /// Подписка на серверные пуши обновления колец (NOTIF_STORIES_UPDATE). void attach() { @@ -286,7 +389,7 @@ class StoriesModule { // #***! пустое кольцо значит истории кончились void _applyPreview(StoryPreview preview) { - if (preview.isEmpty) { + if (preview.isEmpty || _hiddenAuthors.contains(preview.owner.ownerId)) { _previews.remove(preview.owner.ownerId); _peerStories.remove(preview.owner.ownerId); } else { @@ -351,7 +454,7 @@ class StoriesModule { for (final raw in rawPeers) { final peer = PeerStories.fromMap(raw); if (peer == null) continue; - _peerStories[peer.owner.ownerId] = peer.stories; + _setPeerStories(peer.owner.ownerId, peer.stories); if (peer.owner.ownerId == owner.ownerId) result = peer.stories; } } @@ -394,13 +497,20 @@ class StoriesModule { // #***! отметка просмотра, счётчик поднимаем сразу чтоб кольцо гасло без задержки /// Отметить историю просмотренной. Оптимистично поднимает readCount кольца. Future mark(StoryOwner owner, int storyId) async { + if (KometSettings.antiStoryView.value) { + _markQuietly(owner.ownerId, storyId); + return true; + } if (_api.state != SessionState.online) return false; try { final ok = await _api.sendRequestOk(Opcode.storiesMark, { 'owner': owner.toMap(), 'storyId': storyId, }); - if (ok) _markReadLocally(owner.ownerId); + if (ok) { + _forgetQuietView(owner.ownerId, storyId); + _markReadLocally(owner.ownerId); + } return ok; } catch (e) { logger.w('StoriesModule.mark: $e'); @@ -408,6 +518,32 @@ class StoriesModule { } } + bool _viewedQuietly(int ownerId, int storyId) => + _quietViews[ownerId]?.containsKey(storyId) ?? false; + + void _markQuietly(int ownerId, int storyId) { + if (storyId == 0 || _viewedQuietly(ownerId, storyId)) return; + final stories = _peerStories[ownerId] ?? const []; + final index = stories.indexWhere((s) => s.id == storyId); + final serverRead = + (_previews[ownerId] ?? _peerPreviews[ownerId])?.readCount; + if (index >= 0 && serverRead != null && index < serverRead) return; + final story = index < 0 ? null : stories[index]; + final expiresAt = story != null && story.time > 0 && story.expiration > 0 + ? _normMs(story.time) + story.expiration + : _nowMs() + _quietViewFallbackTtl.inMilliseconds; + (_quietViews[ownerId] ??= {})[storyId] = expiresAt; + _bump(); + unawaited(_persistQuietViews()); + } + + void _forgetQuietView(int ownerId, int storyId) { + final views = _quietViews[ownerId]; + if (views == null || views.remove(storyId) == null) return; + if (views.isEmpty) _quietViews.remove(ownerId); + unawaited(_persistQuietViews()); + } + void _markReadLocally(int ownerId) { final preview = _previews[ownerId]; if (preview == null) return; @@ -417,6 +553,84 @@ class StoriesModule { unawaited(_persistPreviews()); } + static const StoryReaction like = StoryReaction(id: '❤️'); + + Future react(Story story, StoryReaction? reaction) async { + if (_api.state != SessionState.online) return false; + try { + final ok = await _api.sendRequestOk(Opcode.storiesReact, { + 'owner': story.owner.toMap(), + 'storyId': story.id, + if (reaction != null) 'reaction': reaction.toMap(), + }); + if (ok) { + _replaceStory( + reaction == null + ? story.copyWith(clearReaction: true) + : story.copyWith(reaction: reaction), + ); + } + return ok; + } catch (e) { + logger.w('StoriesModule.react: $e'); + return false; + } + } + + void _replaceStory(Story updated) { + final ownerId = updated.owner.ownerId; + final list = _peerStories[ownerId]; + if (list == null) return; + final index = list.indexWhere((s) => s.id == updated.id); + if (index < 0) return; + _peerStories[ownerId] = [...list]..[index] = updated; + unawaited(_persistPeers()); + } + + Future storyById(StoryOwner owner, int storyId) async { + try { + final packet = await _api + .sendRequest(Opcode.storiesGetByStoryId, { + 'owner': owner.toMap(), + 'storyIds': [storyId], + }, silent: true) + .timeout(const Duration(seconds: 3)); + final data = packet.payload; + final raw = data is Map ? data['stories'] : null; + if (raw is! List) return null; + for (final item in raw) { + final story = Story.fromMap(item); + if (story != null && story.id == storyId) return story; + } + } catch (e) { + logger.w('StoriesModule.storyById: $e'); + } + return null; + } + + Future setAuthorHidden(int ownerId, bool hidden) async { + try { + final packet = await _api.sendRequest(Opcode.contactUpdate, { + 'contactId': ownerId, + 'action': hidden ? 'HIDE_STORIES' : 'SHOW_STORIES', + }); + if (!packet.isOk) return false; + } catch (e) { + logger.w('StoriesModule.setAuthorHidden: $e'); + return false; + } + if (hidden) { + _hiddenAuthors.add(ownerId); + if (_previews.remove(ownerId) != null) unawaited(_persistPreviews()); + } else { + _hiddenAuthors.remove(ownerId); + unawaited(loadFeed()); + } + _bump(); + unawaited(_persistHiddenAuthors()); + return true; + } + // #***! публикация, settings 1 всем 2 только контактам /// Публикация фото-истории. [photoToken] — токен уже загруженного фото. /// [settings]: 1 = видно всем, 2 = только контактам. [expiration] — TTL, мс. @@ -563,9 +777,11 @@ class StoriesModule { // #***! сброс при смене аккаунта void clear() { + _hiddenAuthors.clear(); _previews.clear(); _peerStories.clear(); _lastViewed.clear(); + _quietViews.clear(); _accountId = null; _bump(); } diff --git a/lib/backend/modules/story_reply_sender.dart b/lib/backend/modules/story_reply_sender.dart new file mode 100644 index 00000000..d0919548 --- /dev/null +++ b/lib/backend/modules/story_reply_sender.dart @@ -0,0 +1,86 @@ +import '../../core/cache/message_session_cache.dart'; +import '../../core/crypto/e2ee_service.dart'; +import '../../core/crypto/outgoing_message_policy.dart'; +import '../../core/storage/app_database.dart'; +import '../../core/storage/token_storage.dart'; +import '../../core/utils/logger.dart'; +import '../../main.dart'; +import '../../models/story.dart'; +import 'chats.dart'; +import 'messages.dart'; + +enum StoryReplyOutcome { sent, encryptedChat, failed } + +abstract final class StoryReplySender { + static Future<({StoryReplyOutcome outcome, int chatId})> send( + Story story, + String text, + ) async { + final session = api.session; + final accountId = await TokenStorage.getActiveAccountId(); + if (accountId == null || accountId == 0) { + return (outcome: StoryReplyOutcome.failed, chatId: 0); + } + final ownerId = story.owner.ownerId; + final chatId = + await AppDatabase.findDialogChatByParticipant(accountId, ownerId) ?? + (accountId ^ ownerId); + try { + await E2eeService.instance.ensureLoaded(accountId); + } catch (_) { + return (outcome: StoryReplyOutcome.failed, chatId: chatId); + } + if (OutgoingMessagePolicy.requiresEncryption(accountId, chatId)) { + return (outcome: StoryReplyOutcome.encryptedChat, chatId: chatId); + } + + final attach = { + '_type': 'STORY_REPLY', + 'owner': story.owner.toMap(), + 'storyId': story.id, + }; + try { + final sent = await messagesModule.sendMessage( + accountId, + chatId, + text, + attaches: [attach], + beforeSend: () { + if (session == null || !identical(api.session, session)) { + throw StateError('Account changed during story reply'); + } + OutgoingMessagePolicy.requireSupported(accountId, chatId); + }, + ); + final id = int.tryParse(sent.id); + if (id != null && id != 0) { + await _persist( + CachedMessage.fromPushPayload(accountId, chatId, { + 'id': sent.id, + 'sender': accountId, + 'time': messageIdToTime(id), + 'text': sent.text ?? text, + 'elements': ?sent.elements, + 'attaches': sent.attaches ?? [attach], + }), + ); + } + return (outcome: StoryReplyOutcome.sent, chatId: chatId); + } catch (e) { + logger.w('Ответ на историю не отправился: $e'); + return (outcome: StoryReplyOutcome.failed, chatId: chatId); + } + } + + static Future _persist(CachedMessage message) async { + try { + await chats.storeSentMessages(message.accountId, message.chatId, [ + message, + ]); + await chats.applyOutgoingMessage(message, status: 'sent'); + } catch (e) { + logger.w('Ответ на историю не сохранился: $e'); + } + MessageSessionCache.append(message.accountId, message.chatId, [message]); + } +} diff --git a/lib/backend/modules/upload_service.dart b/lib/backend/modules/upload_service.dart index 437882ac..f8058d3e 100644 --- a/lib/backend/modules/upload_service.dart +++ b/lib/backend/modules/upload_service.dart @@ -1,7 +1,9 @@ import 'dart:async'; +import 'dart:convert' show base64Decode; import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import '../../core/cache/message_session_cache.dart'; import '../../core/crypto/outgoing_message_policy.dart'; @@ -16,11 +18,14 @@ import '../../models/upload_bytes.dart'; import 'chats.dart' show chats; import 'file_uploader.dart'; import 'messages.dart'; +import 'outgoing_reply.dart'; import 'upload_notification_service.dart'; export 'upload_notification_service.dart' show UploadKind; export '../../models/upload_bytes.dart'; +typedef UploadedPhoto = ({File file, String token, bool temporary}); + // #***! события очереди наружу sealed class UploadJobEvent { const UploadJobEvent({ @@ -344,6 +349,7 @@ class UploadService { required String caption, CachedMessage? placeholder, int? scheduledTime, + OutgoingReply? reply, }) { return _run( UploadJob._( @@ -356,25 +362,45 @@ class UploadService { scheduledTime: scheduledTime, ), (job) async { - final tokens = await _uploadPhotos(jobs, job); - if (job.isCancelled) throw const UploadCancelled(); - final kept = [ - for (var i = 0; i < tokens.length; i++) - if (!job.isSlotCancelled(i)) tokens[i], - ]; - if (kept.isEmpty) throw const UploadCancelled(); - if (kept.any((token) => token == null)) { - throw const UploadFailure('upload_failed'); + final uploaded = List.filled(jobs.length, null); + try { + final tokens = await _uploadPhotos( + jobs, + job, + onUploaded: (index, photo) => uploaded[index] = photo, + ); + if (job.isCancelled) throw const UploadCancelled(); + final keptSlots = [ + for (var i = 0; i < tokens.length; i++) + if (!job.isSlotCancelled(i)) i, + ]; + final kept = [for (final i in keptSlots) tokens[i]]; + if (kept.isEmpty) throw const UploadCancelled(); + if (kept.any((token) => token == null)) { + throw const UploadFailure('upload_failed'); + } + final sent = await messagesModule.sendPhotoMessage( + chatId, + kept.cast(), + caption: caption.isEmpty ? null : caption, + scheduledTime: scheduledTime, + beforeSend: job.ensureSendAllowed, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, + ); + if (sent == null) return null; + final real = CachedMessage.fromPushPayload(accountId, chatId, sent); + await _seedPhotoCache(real, [ + for (final i in keptSlots) ?uploaded[i], + ]); + return real; + } finally { + for (final photo in uploaded) { + if (photo != null && photo.temporary) { + unawaited(photo.file.delete().catchError((_) => photo.file)); + } + } } - final sent = await messagesModule.sendPhotoMessage( - chatId, - kept.cast(), - caption: caption.isEmpty ? null : caption, - scheduledTime: scheduledTime, - beforeSend: job.ensureSendAllowed, - ); - if (sent == null) return null; - return CachedMessage.fromPushPayload(accountId, chatId, sent); }, ); } @@ -388,6 +414,7 @@ class UploadService { required String caption, CachedMessage? placeholder, int? scheduledTime, + OutgoingReply? reply, }) { return _run( UploadJob._( @@ -422,9 +449,13 @@ class UploadService { caption: caption.isEmpty ? null : caption, scheduledTime: scheduledTime, beforeSend: job.ensureSendAllowed, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ); if (sent == null) return null; - return CachedMessage.fromPushPayload(accountId, chatId, sent); + final real = CachedMessage.fromPushPayload(accountId, chatId, sent); + await _seedVideoThumbnail(real, placeholder); + return real; }, ); } @@ -438,6 +469,7 @@ class UploadService { required int durationMs, required Uint8List wave, CachedMessage? placeholder, + OutgoingReply? reply, }) { return _sendRecording( accountId: accountId, @@ -458,6 +490,8 @@ class UploadService { duration: durationMs, wave: wave, beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ), ); } @@ -470,6 +504,7 @@ class UploadService { required File file, required int durationMs, CachedMessage? placeholder, + OutgoingReply? reply, }) { return _sendRecording( accountId: accountId, @@ -489,6 +524,8 @@ class UploadService { token, duration: durationMs, beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ), ); } @@ -521,6 +558,7 @@ class UploadService { placeholder: placeholder, ), (job) async { + var delivered = false; try { final info = await requestUpload(job.ensureSendAllowed); if (info == null || info.url.isEmpty) { @@ -537,11 +575,14 @@ class UploadService { job.markUploaded(); final sent = await send(info.token, job.ensureSendAllowed); if (sent == null) return null; + delivered = true; return CachedMessage.fromPushPayload(accountId, chatId, sent); } finally { - try { - await file.delete(); - } catch (_) {} + if (delivered || job.isCancelled) { + try { + await file.delete(); + } catch (_) {} + } } }, ); @@ -559,6 +600,7 @@ class UploadService { String? text, int? scheduledTime, bool encryptedPayload = false, + OutgoingReply? reply, }) { return _run( UploadJob._( @@ -582,6 +624,7 @@ class UploadService { size: size, text: text, scheduledTime: scheduledTime, + reply: reply, ); FileHistoryCache.add( FileHistoryEntry( @@ -632,6 +675,7 @@ class UploadService { required int size, String? text, int? scheduledTime, + OutgoingReply? reply, }) async { final result = Completer(); late final StreamSubscription sub; @@ -644,6 +688,8 @@ class UploadService { text: text, encryptedPayload: job.encryptedPayload, scheduledTime: scheduledTime, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, beforeSend: job.ensureSendAllowed, ) .listen( @@ -766,7 +812,7 @@ class UploadService { } // #***! настоящее в базу, временное удаляем - final message = real!; + final message = OutgoingReply.keepQuote(real!, job.placeholder); try { await AppDatabase.saveMessages([message.toDbRow()]); if (message.id != job.id) { @@ -830,8 +876,9 @@ class UploadService { // #***! фото пулом воркеров, первая ошибка рубит весь альбом Future> _uploadPhotos( List<({File file, GalleryItem? item})> jobs, - UploadJob job, - ) async { + UploadJob job, { + void Function(int index, UploadedPhoto photo)? onUploaded, + }) async { final tokens = List.filled(jobs.length, null); var nextIndex = 0; var failed = false; @@ -841,7 +888,14 @@ class UploadService { final i = nextIndex++; if (i >= jobs.length) return; if (job.isSlotCancelled(i)) continue; - final token = await _uploadOnePhoto(jobs[i], i, job); + final token = await _uploadOnePhoto( + jobs[i], + i, + job, + onUploaded: onUploaded == null + ? null + : (photo) => onUploaded(i, photo), + ); if (token == null) { if (job.isSlotCancelled(i)) continue; failed = true; @@ -861,14 +915,16 @@ class UploadService { Future _uploadOnePhoto( ({File file, GalleryItem? item}) photo, int index, - UploadJob job, - ) => uploadPhoto( + UploadJob job, { + void Function(UploadedPhoto photo)? onUploaded, + }) => uploadPhoto( photo.file, item: photo.item, cancel: job.slotCancelled(index), onProgress: (sent, total) => job.report(index, sent, total), onRetry: () => job.resetSlot(index), beforeSend: job.ensureSendAllowed, + onUploaded: onUploaded, ); // #***! перед заливкой пережимаем, три попытки с растущей паузой @@ -879,8 +935,10 @@ class UploadService { required void Function(int sent, int total) onProgress, VoidCallback? onRetry, VoidCallback? beforeSend, + void Function(UploadedPhoto photo)? onUploaded, }) async { var stopped = false; + var handedOver = false; unawaited(cancel.then((_) => stopped = true)); File file; try { @@ -910,7 +968,17 @@ class UploadService { onProgress: onProgress, cancel: cancel, ); - if (token != null) return token; + if (token != null) { + if (onUploaded != null) { + onUploaded(( + file: file, + token: token, + temporary: file.path != source.path, + )); + handedOver = true; + } + return token; + } } catch (e) { logger.w('uploadPhoto attempt ${attempt + 1}: $e'); } @@ -918,12 +986,73 @@ class UploadService { } return null; } finally { - if (file.path != source.path) { + if (file.path != source.path && !handedOver) { unawaited(file.delete().catchError((_) => file)); } } } + static Future _seedPhotoCache( + CachedMessage message, + List uploaded, + ) async { + final photos = [...?message.attachments?.whereType()]; + final byToken = {for (final photo in uploaded) photo.token: photo.file}; + final sameOrder = photos.length == uploaded.length; + for (var i = 0; i < photos.length; i++) { + final photo = photos[i]; + if (photo.isGif) continue; + final file = + byToken[photo.photoToken] ?? (sameOrder ? uploaded[i].file : null); + if (file == null) continue; + await _seedImageCache(photo.baseUrl, file.openRead()); + } + } + + static Future _seedVideoThumbnail( + CachedMessage message, + CachedMessage? placeholder, + ) async { + final sent = message.attachments?.whereType().firstOrNull; + final local = placeholder?.attachments + ?.whereType() + .firstOrNull; + final thumbnail = sent?.thumbnail; + final url = thumbnail != null && thumbnail.isNotEmpty + ? thumbnail + : sent?.baseUrl; + final bytes = _dataUriBytes(local?.previewData); + if (bytes == null || bytes.isEmpty) return; + await _seedImageCache(url, Stream.value(bytes)); + } + + static Uint8List? _dataUriBytes(String? dataUri) { + if (dataUri == null || !dataUri.startsWith('data:')) return null; + final comma = dataUri.indexOf(','); + if (comma < 0) return null; + try { + return base64Decode(dataUri.substring(comma + 1)); + } catch (_) { + return null; + } + } + + static Future _seedImageCache( + String? url, + Stream> source, + ) async { + if (url == null || url.isEmpty || url.startsWith('data:')) return; + try { + await DefaultCacheManager().putFileStream( + url, + source, + fileExtension: 'jpg', + ); + } catch (e) { + logger.w('UploadService: не удалось положить отправленное в кэш: $e'); + } + } + // #***! имя файла из пути иначе photo.jpg String _photoFilename(File file) { final segments = file.uri.pathSegments; diff --git a/lib/core/cache/cache_janitor.dart b/lib/core/cache/cache_janitor.dart new file mode 100644 index 00000000..288bfdf1 --- /dev/null +++ b/lib/core/cache/cache_janitor.dart @@ -0,0 +1,405 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import '../config/app_cache_limit.dart'; +import '../media/tlottie/tlottie_disk_cache.dart'; +import '../storage/app_database.dart'; +import '../utils/logger.dart'; +import '../utils/media_cache.dart'; +import '../utils/media_cache_names.dart'; + +enum StorageCategory { + photos, + videos, + files, + voice, + stickers, + keptMedia, + database, +} + +extension StorageCategoryRole on StorageCategory { + bool get clearable => this != StorageCategory.database; + + bool get evictable => clearable && this != StorageCategory.keptMedia; +} + +class StorageReport { + const StorageReport(this.bytes); + + final Map bytes; + + int of(StorageCategory category) => bytes[category] ?? 0; + + int get total => bytes.values.fold(0, (sum, size) => sum + size); +} + +enum CacheStore { media, images, stickerFrames } + +typedef _ListedFile = ({String path, int size, int modified}); + +class CacheJanitor { + CacheJanitor._(); + static final CacheJanitor instance = CacheJanitor._(); + + static const Duration startupDelay = Duration(seconds: 30); + static const Duration _debounce = Duration(seconds: 3); + static const Duration _freshness = Duration(minutes: 2); + static const Duration _remeasureEvery = Duration(minutes: 15); + static const List<_Area> _areas = [ + _MediaArea(), + _ImageArea(), + _StickerFramesArea(), + ]; + + Timer? _timer; + Future _queue = Future.value(); + final Map _estimate = {}; + DateTime? _measuredAt; + + void schedule([Duration delay = _debounce]) { + if (kIsWeb) return; + _timer?.cancel(); + _timer = Timer(delay, () { + _timer = null; + unawaited(trim()); + }); + } + + void noteWrite(CacheStore store, int bytes) { + if (kIsWeb) return; + final measuredAt = _measuredAt; + final stale = + measuredAt == null || + DateTime.now().difference(measuredAt) > _remeasureEvery; + if (!stale) { + _estimate.update(store, (size) => size + bytes, ifAbsent: () => bytes); + if (!_exceedsLimits()) return; + } + if (_timer?.isActive ?? false) return; + schedule(); + } + + Future trim() => + _serial(_trim).catchError((Object error) { + logger.w('[cache] не удалось подрезать кэш: $error'); + return null; + }); + + Future scan() => + _serial(() async => _report(await _collect())); + + Future<({int freed, StorageReport report})> clear( + Set categories, + ) => _serial(() async { + final entries = await _collect(); + final doomed = { + for (final entry in entries) + if (entry.category.clearable && categories.contains(entry.category)) + entry, + }; + final freed = await _remove(doomed); + final remaining = _without(entries, doomed); + _remember(remaining); + return (freed: freed, report: await _report(remaining)); + }); + + @visibleForTesting + bool get debugPassScheduled => _timer?.isActive ?? false; + + @visibleForTesting + void debugMeasured(Map estimate) { + _estimate + ..clear() + ..addAll(estimate); + _measuredAt = DateTime.now(); + } + + @visibleForTesting + void resetForTesting() { + _timer?.cancel(); + _timer = null; + _queue = Future.value(); + _estimate.clear(); + _measuredAt = null; + } + + Future _serial(Future Function() action) { + final next = _queue.then((_) => action()); + _queue = next.then((_) {}, onError: (Object _, StackTrace _) {}); + return next; + } + + bool _exceedsLimits() { + for (final area in _areas) { + final cap = area.capBytes; + if (cap != null && (_estimate[area.store] ?? 0) > cap) return true; + } + final budget = AppCacheLimit.current.value; + if (budget == AppCacheLimit.unlimited) return false; + return _estimate.values.fold(0, (sum, size) => sum + size) > budget; + } + + Future _trim() async { + final entries = await _collect(); + final now = DateTime.now(); + final budget = AppCacheLimit.current.value; + final pool = <_Entry>[]; + final doomed = <_Entry>{}; + + for (final area in _areas) { + final evictable = [ + for (final entry in entries) + if (identical(entry.area, area) && entry.category.evictable) entry, + ]..sort(_oldestFirst); + final cap = area.capBytes; + var areaBytes = evictable.fold(0, (sum, entry) => sum + entry.size); + for (final entry in evictable) { + if (cap != null && areaBytes > cap && !_isFresh(entry, now)) { + doomed.add(entry); + areaBytes -= entry.size; + } else { + pool.add(entry); + } + } + } + + if (budget != AppCacheLimit.unlimited) { + var total = pool.fold(0, (sum, entry) => sum + entry.size); + pool.sort(_oldestFirst); + for (final entry in pool) { + if (total <= budget) break; + if (_isFresh(entry, now)) continue; + doomed.add(entry); + total -= entry.size; + } + } + + if (doomed.isNotEmpty) await _remove(doomed); + final remaining = _without(entries, doomed); + _remember(remaining); + return _report(remaining); + } + + Future> _collect() async { + final directories = await Future.wait([ + for (final area in _areas) _directoryOf(area), + ]); + final listed = await _listInBackground(directories); + final entries = <_Entry>[]; + for (var i = 0; i < _areas.length; i++) { + final area = _areas[i]; + for (final file in listed[i]) { + final name = p.basename(file.path); + if (!area.accepts(name)) continue; + entries.add( + _Entry( + area, + file.path, + name, + file.size, + DateTime.fromMillisecondsSinceEpoch(file.modified), + area.categoryOf(name), + ), + ); + } + } + _remember(entries); + return entries; + } + + static Future _directoryOf(_Area area) async { + try { + return await area.directory(); + } catch (error) { + logger.w('[cache] нет папки ${area.store.name}: $error'); + return null; + } + } + + void _remember(List<_Entry> entries) { + _estimate.clear(); + for (final entry in entries) { + if (!entry.category.evictable) continue; + _estimate.update( + entry.area.store, + (size) => size + entry.size, + ifAbsent: () => entry.size, + ); + } + _measuredAt = DateTime.now(); + } + + Future _report(List<_Entry> entries) async { + final bytes = {}; + for (final entry in entries) { + bytes.update( + entry.category, + (size) => size + entry.size, + ifAbsent: () => entry.size, + ); + } + bytes[StorageCategory.database] = await AppDatabase.fileBytes(); + return StorageReport(bytes); + } + + Future _remove(Set<_Entry> doomed) async { + final media = [ + for (final entry in doomed) + if (entry.area.store == CacheStore.media) entry.name, + ]; + final files = [ + for (final entry in doomed) + if (entry.area.store != CacheStore.media) entry.path, + ]; + var freed = 0; + if (media.isNotEmpty) freed += await MediaCache.remove(media); + if (files.isNotEmpty) freed += await _deleteInBackground(files); + return freed; + } + + static List<_Entry> _without(List<_Entry> entries, Set<_Entry> doomed) => [ + for (final entry in entries) + if (!doomed.contains(entry)) entry, + ]; + + static int _oldestFirst(_Entry a, _Entry b) => + a.modified.compareTo(b.modified); + + static bool _isFresh(_Entry entry, DateTime now) => + now.difference(entry.modified) < _freshness; + + static Future>> _listInBackground( + List directories, + ) => Isolate.run(() => _listDirectories(directories)); + + static Future _deleteInBackground(List paths) => + Isolate.run(() => _deleteFiles(paths)); +} + +List> _listDirectories(List directories) => [ + for (final directory in directories) + directory == null ? const <_ListedFile>[] : _listDirectory(directory), +]; + +List<_ListedFile> _listDirectory(String path) { + final directory = Directory(path); + if (!directory.existsSync()) return const []; + final files = <_ListedFile>[]; + for (final entity in directory.listSync(followLinks: false)) { + if (entity is! File) continue; + try { + final stat = entity.statSync(); + files.add(( + path: entity.path, + size: stat.size, + modified: stat.modified.millisecondsSinceEpoch, + )); + } catch (_) {} + } + return files; +} + +int _deleteFiles(List paths) { + var freed = 0; + for (final path in paths) { + final file = File(path); + try { + final size = file.lengthSync(); + file.deleteSync(); + freed += size; + } catch (_) {} + } + return freed; +} + +class _Entry { + const _Entry( + this.area, + this.path, + this.name, + this.size, + this.modified, + this.category, + ); + + final _Area area; + final String path; + final String name; + final int size; + final DateTime modified; + final StorageCategory category; +} + +abstract class _Area { + const _Area(this.store); + + final CacheStore store; + + int? get capBytes => null; + + Future directory(); + + bool accepts(String name) => true; + + StorageCategory categoryOf(String name); +} + +class _MediaArea extends _Area { + const _MediaArea() : super(CacheStore.media); + + @override + Future directory() => MediaCache.directoryPath(); + + @override + bool accepts(String name) => !name.endsWith('.part'); + + @override + StorageCategory categoryOf(String name) => switch (mediaCacheKindOf(name)) { + MediaCacheKind.photo => StorageCategory.photos, + MediaCacheKind.video => StorageCategory.videos, + MediaCacheKind.voice => StorageCategory.voice, + MediaCacheKind.file => StorageCategory.files, + MediaCacheKind.kept => StorageCategory.keptMedia, + }; +} + +class _ImageArea extends _Area { + const _ImageArea() : super(CacheStore.images); + + static const Set _animationExtensions = {'.json', '.tgs', '.lottie'}; + static Future? _path; + + @override + Future directory() => _path ??= getTemporaryDirectory().then( + (base) => p.join(base.path, DefaultCacheManager.key), + ); + + @override + StorageCategory categoryOf(String name) => + _animationExtensions.contains(p.extension(name).toLowerCase()) + ? StorageCategory.stickers + : StorageCategory.photos; +} + +class _StickerFramesArea extends _Area { + const _StickerFramesArea() : super(CacheStore.stickerFrames); + + @override + int? get capBytes => TlottieDiskCache.maxBytes; + + @override + Future directory() => TlottieDiskCache.instance.directoryPath(); + + @override + bool accepts(String name) => TlottieDiskCache.holds(name); + + @override + StorageCategory categoryOf(String name) => StorageCategory.stickers; +} diff --git a/lib/core/calls/call_bridge.dart b/lib/core/calls/call_bridge.dart index be5e0290..aebc1702 100644 --- a/lib/core/calls/call_bridge.dart +++ b/lib/core/calls/call_bridge.dart @@ -95,15 +95,17 @@ class CallBridge { } } - Future setScreenShare(bool enabled, {String? caller}) async { - if (!_android) return; + Future setScreenShare(bool enabled, {String? caller}) async { + if (!_android) return true; try { - await _method.invokeMethod('setScreenShare', { - 'enabled': enabled, - 'caller': caller, - }); + return await _method.invokeMethod('setScreenShare', { + 'enabled': enabled, + 'caller': caller, + }) ?? + true; } catch (e) { logger.w('CallBridge.setScreenShare: enabled=$enabled $e'); + return !enabled; } } diff --git a/lib/core/calls/call_controller.dart b/lib/core/calls/call_controller.dart index db23b087..d85f2d9e 100644 --- a/lib/core/calls/call_controller.dart +++ b/lib/core/calls/call_controller.dart @@ -9,6 +9,7 @@ import '../utils/logger.dart'; import '../utils/parse.dart'; import 'call_bridge.dart'; import 'call_link.dart'; +import 'call_permissions.dart'; import 'call_session.dart'; import 'conversation_params.dart'; import 'ws2_signaling.dart'; @@ -194,6 +195,7 @@ class CallController { // #***! исходящий звонок Future startOutgoing(int calleeId, {bool isVideo = false}) => _startExclusive(() async { + await CallPermissions.requireMicrophone(); final out = await _calls!.initiateCall(calleeId, isVideo: isVideo); final config = Ws2Config.fromEndpoint( out.endpoint, @@ -217,6 +219,7 @@ class CallController { // #***! вход по ссылке Future joinByLink(String token, {bool isVideo = false}) => _startExclusive(() async { + await CallPermissions.requireMicrophone(); final params = await _calls!.joinByLink(token, isVideo: isVideo); final config = Ws2Config.fromEndpoint( params.endpoint, @@ -247,6 +250,7 @@ class CallController { // #***! принятие входящего Future acceptIncoming(IncomingCall call) async { + await CallPermissions.requireMicrophone(); _pending = null; CallBridge.instance.cancelIncoming(conversationId: call.conversationId); final config = Ws2Config.fromVcp( diff --git a/lib/core/calls/call_permissions.dart b/lib/core/calls/call_permissions.dart new file mode 100644 index 00000000..d27402b6 --- /dev/null +++ b/lib/core/calls/call_permissions.dart @@ -0,0 +1,65 @@ +import 'package:flutter/foundation.dart'; +import 'package:permission_handler/permission_handler.dart'; + +enum CallMicrophoneAccess { granted, denied, permanentlyDenied } + +class CallMicrophonePermissionException implements Exception { + const CallMicrophonePermissionException(this.access); + + final CallMicrophoneAccess access; + + bool get permanentlyDenied => + access == CallMicrophoneAccess.permanentlyDenied; + + @override + String toString() => 'CallMicrophonePermissionException($access)'; +} + +typedef CallPermissionStatusReader = Future Function(); +typedef CallPermissionRequester = Future Function(); + +abstract final class CallPermissions { + static bool get _needsRuntimeMicrophonePermission => + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS); + + static Future ensureMicrophone({ + bool? needsRuntimePermission, + CallPermissionStatusReader? readStatus, + CallPermissionRequester? request, + }) async { + if (!(needsRuntimePermission ?? _needsRuntimeMicrophonePermission)) { + return CallMicrophoneAccess.granted; + } + + final current = + await (readStatus ?? (() => Permission.microphone.status))(); + if (current.isGranted) return CallMicrophoneAccess.granted; + if (current.isPermanentlyDenied || current.isRestricted) { + return CallMicrophoneAccess.permanentlyDenied; + } + + final requested = await (request ?? Permission.microphone.request)(); + if (requested.isGranted) return CallMicrophoneAccess.granted; + if (requested.isPermanentlyDenied || requested.isRestricted) { + return CallMicrophoneAccess.permanentlyDenied; + } + return CallMicrophoneAccess.denied; + } + + static Future requireMicrophone({ + bool? needsRuntimePermission, + CallPermissionStatusReader? readStatus, + CallPermissionRequester? request, + }) async { + final access = await ensureMicrophone( + needsRuntimePermission: needsRuntimePermission, + readStatus: readStatus, + request: request, + ); + if (access != CallMicrophoneAccess.granted) { + throw CallMicrophonePermissionException(access); + } + } +} diff --git a/lib/core/calls/call_session.dart b/lib/core/calls/call_session.dart index 2782b984..a8ae860c 100644 --- a/lib/core/calls/call_session.dart +++ b/lib/core/calls/call_session.dart @@ -44,6 +44,7 @@ enum CallNotice { micMutedByAdmin, cameraMutedByAdmin, screenMutedByAdmin, + micUnavailable, } class CallRecord { @@ -149,7 +150,9 @@ class CallSession { // #***! флаги своей и чужой стороны bool _muted = false; + bool _micUnavailable = false; bool _speakerOn = false; + bool _speakerChosen = false; bool _accepted = false; bool _peerMuted = false; bool _peerVideo = false; @@ -161,6 +164,13 @@ class CallSession { final List _pendingCandidates = []; Future _tail = Future.value(); + String? _remoteDevice; + bool _opponentAccepted = false; + final Map _parkedAnswers = {}; + final Map> _parkedCandidates = {}; + Timer? _p2pWatchdog; + static const Duration _p2pConnectLimit = Duration(seconds: 10); + // #***! участники и их видео, экран звонка подписан final Map _participants = {}; final Map _participantStreams = {}; @@ -440,6 +450,7 @@ class CallSession { bool get peerIsKomet => _peerIsKomet; bool get isMuted => _muted; + bool get micUnavailable => _micUnavailable; bool get audioTransmitting => !_muted || LaunchFlags.noMute; String? get micDeviceId => _micDeviceId; String? get pulseSource => _pulseSource; @@ -495,7 +506,6 @@ class CallSession { await signaling.connect(); logger.i('[call] signaling connected to ${ws2Config.uri.host}'); logger.i('[call] ws2 url ${_maskedUrl()}'); - unawaited(_wakeSignalingIfSilent(signaling)); Timer(const Duration(seconds: 10), () { if (_ended || _gotConnection) return; logger.w( @@ -517,45 +527,6 @@ class CallSession { ); } - // #***! сигналка молчит, дёргаем командой иначе висим до таймаута - /// Кадры ws2 приходят в broadcast-канал Rust-ядра, а подписка на него - /// создаётся уже после того, как сокет открыт: нотификацию `connection`, - /// присланную сразу после хэндшейка, ядро выбрасывает. Если её нет — толкаем - /// сервер командой (ответы идут по sequence и гонке не подвержены). - Future _wakeSignalingIfSilent(Ws2Signaling signaling) async { - await Future.delayed(const Duration(milliseconds: 1200)); - if (_ended || _gotConnection || _signaling != signaling) return; - - logger.w('[call] "connection" не пришла за 1.2 с — бужу ws2'); - try { - final response = await signaling.sendCommand( - 'change-media-settings', - extra: { - 'mediaSettings': { - 'isVideoEnabled': _localVideo, - 'isAudioEnabled': !_muted, - 'isScreenSharingEnabled': _screenAnnounced, - 'isAnimojiEnabled': false, - }, - }, - ); - logger.i('[call] ws2 wake ok: $response'); - } catch (e) { - logger.w('[call] ws2 wake failed: $e'); - return; - } - - await Future.delayed(const Duration(milliseconds: 1200)); - if (_ended || _gotConnection || _signaling != signaling) return; - - logger.w('[call] всё ещё тихо — шлю accept-call вслепую'); - try { - await accept(activate: false); - } catch (e) { - logger.w('[call] accept-call failed: $e'); - } - } - // #***! обрыв сигналки void _onSignalingLost() { if (_ended || _reconnecting) return; @@ -639,6 +610,10 @@ class CallSession { _screenSender = null; _remoteDescSet = false; _pendingCandidates.clear(); + _parkedAnswers.clear(); + _parkedCandidates.clear(); + _remoteDevice = null; + _p2pWatchdog?.cancel(); _accepted = false; _mediaConnected = false; _sfuSessionId = null; @@ -787,8 +762,8 @@ class CallSession { await _onTransmittedData(msg); break; case 'accepted-call': - _onAcceptedCall(msg); _setState(CallSessionState.active); + await _onAcceptedCall(msg); break; case 'options-changed': final options = msg['options']; @@ -983,7 +958,7 @@ class CallSession { } } - void _onAcceptedCall(Map msg) { + Future _onAcceptedCall(Map msg) async { final id = _participantIdFrom(msg['participantId']); if (id == null || id == ws2Config.userId) return; _upsertParticipant( @@ -993,6 +968,60 @@ class CallSession { muteStates: msg['muteStates'], ); _notifyInfo(); + if (_topology == 'SERVER' || (_peerId != null && id != _peerId)) return; + _armP2pWatchdog(); + await _bindOpponentDevice(_deviceOf(msg['peerId'])); + } + + static String? _deviceOf(Object? peerId) { + final raw = peerId is Map ? peerId['id'] : peerId; + final id = raw?.toString(); + return id == null || id.isEmpty ? null : id; + } + + bool get _awaitingOpponentDevice => + role == CallRole.caller && !_opponentAccepted; + + Future _bindOpponentDevice(String? device) async { + _opponentAccepted = true; + _remoteDevice = device ?? _parkedAnswers.keys.firstOrNull; + final chosen = _remoteDevice; + final answer = chosen == null ? null : _parkedAnswers[chosen]; + final candidates = chosen == null ? null : _parkedCandidates[chosen]; + final dropped = _parkedAnswers.keys.where((d) => d != chosen).toList(); + _parkedAnswers.clear(); + _parkedCandidates.clear(); + logger.i( + '[call][p2p] opponent picked up on device $chosen, ' + 'parked answer=${answer != null} candidates=${candidates?.length ?? 0} ' + 'dropped devices=$dropped', + ); + final pc = _pc; + if (pc == null) return; + if (candidates != null) _pendingCandidates.addAll(candidates); + try { + if (answer != null) { + _applyRemoteSdp(answer, _peerId); + await _acceptRemoteSdp(pc, 'answer', answer); + } else if (_remoteDescSet) { + await _flushCandidates(); + } + } catch (e) { + logger.w('[call][p2p] parked answer from $chosen rejected: $e'); + } + } + + void _armP2pWatchdog() { + _p2pWatchdog?.cancel(); + if (_topology == 'SERVER' || _mediaConnected) return; + _p2pWatchdog = Timer(_p2pConnectLimit, () { + if (_ended || _mediaConnected || _topology == 'SERVER') return; + logger.w( + '[call][p2p] no media ${_p2pConnectLimit.inSeconds} s after the ' + 'answer, switching to SERVER', + ); + unawaited(switchToServerTopology()); + }); } void _applyConversation(Map conversation) { @@ -1362,11 +1391,18 @@ class CallSession { final pc = await _createPc(ice); _pc = pc; await _addLocalMedia(pc); - if (role != CallRole.callee) await _addVideoTransceiver(pc); + if (role != CallRole.callee) { + await _reserveAudioSender(pc); + await _addVideoTransceiver(pc); + } await _setupKometProbe(pc); - if (_isDesktop) await _preferVp8Codecs(pc); + if (_isDesktop) { + await _preferVp8Codecs(pc); + } else { + await _preferH264Codecs(pc); + } if (role == CallRole.caller) { _setState(CallSessionState.ringing); @@ -1431,6 +1467,7 @@ class CallSession { _mediaConnected = connected; _notifyInfo(); if (connected) { + _p2pWatchdog?.cancel(); _iceRestarts = 0; if (_topology != 'SERVER') _startP2pStats(pc); if (role == CallRole.joiner || _topology == 'SERVER') { @@ -1455,6 +1492,10 @@ class CallSession { // #***! свои дорожки, микрофон всегда видео по требованию Future _addLocalMedia(RTCPeerConnection pc) async { + if (_wantVideo && _speakerFollowsVideo && !_speakerOn) { + _speakerOn = true; + _notifyInfo(); + } await _prepareAudioSession(); await _disposeMicStream(); try { @@ -1466,21 +1507,69 @@ class CallSession { await _resetMicRoute(); } await _selectMicInsideEngine(); - _localStream = await navigator.mediaDevices.getUserMedia({ - 'audio': AudioDevices.micConstraints( - _micDeviceId, - monitorCapture: _monitorCapture, - ), - 'video': _wantVideo, - }); - for (final track in _localStream!.getTracks()) { - final sender = await pc.addTrack(track, _localStream!); - if (track.kind == 'audio') _audioSender = sender; + final stream = await _openLocalStream(); + _localStream = stream; + if (stream != null) { + for (final track in stream.getTracks()) { + final sender = await pc.addTrack(track, stream); + if (track.kind == 'audio') _audioSender = sender; + } } _applyAudioTracks(); await applyAudioRoute(); } + Object get _micConstraints => AudioDevices.micConstraints( + _micDeviceId, + monitorCapture: _monitorCapture, + ); + + Future _openLocalStream() async { + if (_micUnavailable) return null; + if (_wantVideo) { + try { + return await navigator.mediaDevices.getUserMedia({ + 'audio': _micConstraints, + 'video': true, + }); + } catch (e) { + logger.w('[call] камера недоступна, открываю только микрофон: $e'); + } + } + try { + return await navigator.mediaDevices.getUserMedia({ + 'audio': _micConstraints, + 'video': false, + }); + } catch (e) { + logger.w('[call] микрофон недоступен, остаюсь в звонке без него: $e'); + _micUnavailable = true; + _muted = true; + _notifyInfo(); + _notice(CallNotice.micUnavailable); + return null; + } + } + + Future _reserveAudioSender(RTCPeerConnection pc) async { + if (_audioSender != null) return; + final transceiver = await pc.addTransceiver( + kind: RTCRtpMediaType.RTCRtpMediaTypeAudio, + init: RTCRtpTransceiverInit(direction: TransceiverDirection.SendRecv), + ); + _audioSender = transceiver.sender; + } + + Future _adoptOfferedAudio(RTCPeerConnection pc) async { + if (_topology == 'SERVER' || _audioSender != null) return; + final offered = (await pc.getTransceivers()) + .where((t) => t.mid.isNotEmpty && t.receiver.track?.kind == 'audio') + .firstOrNull; + if (offered == null) return; + await offered.setDirection(TransceiverDirection.SendRecv); + _audioSender = offered.sender; + } + // #***! на мобилках микрофон выбирает движок Future _selectMicInsideEngine() async { final deviceId = _micDeviceId; @@ -1584,10 +1673,7 @@ class CallSession { final sender = _audioSender; if (sender == null) return; final stream = await navigator.mediaDevices.getUserMedia({ - 'audio': AudioDevices.micConstraints( - _micDeviceId, - monitorCapture: _monitorCapture, - ), + 'audio': _micConstraints, 'video': false, }); final tracks = stream.getAudioTracks(); @@ -1614,12 +1700,22 @@ class CallSession { // #***! громкая связь Future setSpeaker(bool on) async { + _speakerChosen = true; if (_speakerOn == on) return; _speakerOn = on; await applyAudioRoute(); _notifyInfo(); } + bool get _speakerFollowsVideo => _canRouteAudio && !_speakerChosen; + + Future _speakerForVideo() async { + if (!_speakerFollowsVideo || _speakerOn) return; + _speakerOn = true; + _notifyInfo(); + await applyAudioRoute(); + } + Future _prepareAudioSession() async { if (!_canRouteAudio) return; if (defaultTargetPlatform == TargetPlatform.android) { @@ -1638,12 +1734,37 @@ class CallSession { Future applyAudioRoute() async { if (!_canRouteAudio) return; try { - await Helper.setSpeakerphoneOn(_speakerOn); + if (_speakerOn && !_speakerChosen) { + await _speakerUnlessHeadset(); + } else { + await Helper.setSpeakerphoneOn(_speakerOn); + } } catch (e) { logger.w('[call] setSpeakerphoneOn($_speakerOn) недоступен: $e'); } } + static Future _speakerUnlessHeadset() async { + if (defaultTargetPlatform == TargetPlatform.android && + !await _headsetConnected()) { + await Helper.setSpeakerphoneOn(true); + return; + } + await Helper.setSpeakerphoneOnButPreferBluetooth(); + } + + static Future _headsetConnected() async { + try { + final outputs = await Helper.audiooutputs; + return outputs.any( + (o) => o.deviceId == 'bluetooth' || o.deviceId == 'wired-headset', + ); + } catch (e) { + logger.w('[call] список аудиовыходов недоступен: $e'); + return false; + } + } + static bool get _canRouteAudio => defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS; @@ -1949,7 +2070,8 @@ class CallSession { } // #***! сервер сам выделяет слоты под нашу камеру и экран, экранный узнаём по s в mid - ({String? camera, String? screen}) _sendSlotMids(String sdp) { + ({String? audio, String? camera, String? screen}) _sendSlotMids(String sdp) { + String? audio; String? camera; String? screen; String? kind; @@ -1958,7 +2080,12 @@ class CallSession { void flush() { final id = mid; - if (kind != 'video' || id == null) return; + if (id == null) return; + if (kind == 'audio') { + if (recvOnly) audio ??= id; + return; + } + if (kind != 'video') return; if (id.contains('s')) { screen ??= id; } else if (recvOnly) { @@ -1980,18 +2107,20 @@ class CallSession { } } flush(); - return (camera: camera, screen: screen); + return (audio: audio, camera: camera, screen: screen); } Future _prepareSendSlots(RTCPeerConnection pc, String offerSdp) async { final slots = _sendSlotMids(offerSdp); logger.i( - '[call][sfu] send slots camera=${slots.camera} screen=${slots.screen}', + '[call][sfu] send slots audio=${slots.audio} camera=${slots.camera} ' + 'screen=${slots.screen}', ); - if (slots.camera == null && slots.screen == null) return; for (final transceiver in await pc.getTransceivers()) { final mid = transceiver.mid; - if (mid == slots.camera) { + if (mid == slots.audio) { + if (_audioSender == null) await _claimAudioSlot(transceiver); + } else if (mid == slots.camera) { _videoSender = await _claimSendSlot(transceiver, _cameraStream) ?? _videoSender; } else if (mid == slots.screen) { @@ -2001,6 +2130,17 @@ class CallSession { } } + Future _claimAudioSlot(RTCRtpTransceiver transceiver) async { + try { + await transceiver.setDirection(TransceiverDirection.SendOnly); + } catch (e) { + logger.w('[call][sfu] audio slot ${transceiver.mid} setDirection: $e'); + return; + } + _audioSender = transceiver.sender; + logger.i('[call][sfu] audio slot mid=${transceiver.mid} без микрофона'); + } + Future _claimSendSlot( RTCRtpTransceiver transceiver, MediaStream? source, @@ -2859,6 +2999,27 @@ class CallSession { }); } + Future _preferH264Codecs(RTCPeerConnection pc) async { + const order = ['video/h264', 'video/vp8']; + try { + final caps = await getRtpSenderCapabilities('video'); + final all = caps.codecs ?? const []; + String mime(RTCRtpCodecCapability c) => c.mimeType.toLowerCase(); + if (!all.any((c) => mime(c) == order.first)) return; + final preferred = [ + for (final kind in order) ...all.where((c) => mime(c) == kind), + ...all.where((c) => !order.contains(mime(c))), + ]; + for (final t in await pc.getTransceivers()) { + try { + await t.setCodecPreferences(preferred); + } catch (_) {} + } + } catch (e) { + logger.t('[call] setCodecPreferences недоступен: $e'); + } + } + Future _preferVp8Codecs(RTCPeerConnection pc) async { try { final caps = await getRtpSenderCapabilities('video'); @@ -2888,73 +3049,59 @@ class CallSession { final data = msg['data']; if (data is! Map) return; + final device = _deviceOf(msg['peerId']); + final bound = _remoteDevice; + if (device != null && bound != null && device != bound) { + logger.i( + '[call][p2p] ${data['sdp'] is Map ? 'sdp' : 'candidate'} from ' + 'device $device ignored, the call is on $bound', + ); + return; + } + final park = device != null && bound == null && _awaitingOpponentDevice; + final sdp = data['sdp']; if (sdp is Map) { final type = sdp['type'] as String?; final desc = sdp['sdp'] as String?; if (type == null || desc == null) return; - _applyRemoteSdp(desc, _participantIdFrom(msg['participantId'])); - logger.t( - '[call] remote $type video: ${_videoDir(desc)} ' - 'codecs=[${_videoCodecs(desc)}] ufrag=${_iceUfrag(desc)}', - ); - - if (type == 'answer' && - pc.signalingState != - RTCSignalingState.RTCSignalingStateHaveLocalOffer) { - final applied = await pc.getRemoteDescription(); + if (park) { + if (type == 'answer') _parkedAnswers[device] = desc; logger.i( - '[call][p2p] extra answer ignored (state=${pc.signalingState}) ' - 'device=${data['deviceIdx'] ?? msg['deviceIdx']} ' - 'ufrag=${_iceUfrag(desc)} applied=${_iceUfrag(applied?.sdp ?? '')} ' - 'video=[${_videoCodecs(desc)}] m=[${_mLineDetails(desc)}]', + '[call][p2p] $type from device $device parked until the opponent ' + 'picks up', ); return; } + if (type == 'offer' && role != CallRole.caller) _remoteDevice ??= device; - if (type == 'offer' && - pc.signalingState == - RTCSignalingState.RTCSignalingStateHaveLocalOffer) { - logger.w('[call] offer glare, rolling back local offer'); - await pc.setLocalDescription(RTCSessionDescription(null, 'rollback')); - } - - await pc.setRemoteDescription(RTCSessionDescription(desc, type)); - _remoteDescSet = true; - await _flushCandidates(); - - if (type == 'offer') { - await _adoptOfferedVideo(pc); - final answer = await pc.createAnswer({}); - await pc.setLocalDescription(answer); - logger.t('[call] our answer video: ${_videoDir(answer.sdp ?? '')}'); - final peerId = _peerId; - if (peerId != null) { - await _signaling?.transmitSdp( - participantId: peerId, - participantType: _peerType, - deviceIdx: _peerDeviceIdx, - type: answer.type!, - sdp: _labelLocalTracks(answer.sdp!), - ); - } - if (_current == CallSessionState.connecting) { - _setState(CallSessionState.ringing); - } - } - unawaited(_collectReceivers()); + _applyRemoteSdp(desc, _participantIdFrom(msg['participantId'])); + logger.t( + '[call] remote $type video: ${_videoDir(desc)} ' + 'codecs=[${_videoCodecs(desc)}] ufrag=${_iceUfrag(desc)}', + ); + await _acceptRemoteSdp( + pc, + type, + desc, + deviceIdx: data['deviceIdx'] ?? msg['deviceIdx'], + ); return; } final candidate = data['candidate']; if (candidate is Map) { - _applyRemoteCandidate(candidate['candidate']); final ice = RTCIceCandidate( candidate['candidate'] as String?, candidate['sdpMid'] as String?, candidate['sdpMLineIndex'] as int?, ); + if (park) { + _parkedCandidates.putIfAbsent(device, () => []).add(ice); + return; + } + _applyRemoteCandidate(candidate['candidate']); if (_remoteDescSet) { try { await pc.addCandidate(ice); @@ -2965,6 +3112,60 @@ class CallSession { } } + Future _acceptRemoteSdp( + RTCPeerConnection pc, + String type, + String desc, { + Object? deviceIdx, + }) async { + if (type == 'answer' && + pc.signalingState != + RTCSignalingState.RTCSignalingStateHaveLocalOffer) { + final applied = await pc.getRemoteDescription(); + logger.i( + '[call][p2p] extra answer ignored (state=${pc.signalingState}) ' + 'device=$deviceIdx ' + 'ufrag=${_iceUfrag(desc)} applied=${_iceUfrag(applied?.sdp ?? '')} ' + 'video=[${_videoCodecs(desc)}] m=[${_mLineDetails(desc)}]', + ); + return; + } + + if (type == 'offer' && + pc.signalingState == + RTCSignalingState.RTCSignalingStateHaveLocalOffer) { + logger.w('[call] offer glare, rolling back local offer'); + await pc.setLocalDescription(RTCSessionDescription(null, 'rollback')); + } + + await pc.setRemoteDescription(RTCSessionDescription(desc, type)); + _remoteDescSet = true; + await _flushCandidates(); + + if (type == 'offer') { + await _adoptOfferedAudio(pc); + await _adoptOfferedVideo(pc); + if (_isDesktop) await _preferVp8Codecs(pc); + final answer = await pc.createAnswer({}); + await pc.setLocalDescription(answer); + logger.t('[call] our answer video: ${_videoDir(answer.sdp ?? '')}'); + final peerId = _peerId; + if (peerId != null) { + await _signaling?.transmitSdp( + participantId: peerId, + participantType: _peerType, + deviceIdx: _peerDeviceIdx, + type: answer.type!, + sdp: _labelLocalTracks(answer.sdp!), + ); + } + if (_current == CallSessionState.connecting) { + _setState(CallSessionState.ringing); + } + } + unawaited(_collectReceivers()); + } + // #***! придержанные кандидаты отправляем в соединение Future _flushCandidates() async { final pc = _pc; @@ -3039,9 +3240,50 @@ class CallSession { // #***! мьют, дорожку не убираем а глушим иначе собеседник увидит разрыв Future setMuted(bool muted) async { + if (!muted && _micUnavailable && !await _restoreMic()) { + _notifyInfo(); + _notice(CallNotice.micUnavailable); + return; + } await _applyMuted(muted, announce: true); } + Future _restoreMic() async { + final pc = _pc; + if (pc == null) return false; + try { + if (_audioSender == null) { + await _addMicTrack(pc); + } else { + await _replaceMicTrack(); + } + } catch (e) { + logger.w('[call] микрофон по-прежнему недоступен: $e'); + return false; + } + if (_audioTracks.isEmpty) return false; + _micUnavailable = false; + logger.i('[call] микрофон подключён в идущем звонке'); + return true; + } + + Future _addMicTrack(RTCPeerConnection pc) async { + final stream = await navigator.mediaDevices.getUserMedia({ + 'audio': _micConstraints, + 'video': false, + }); + final track = stream.getAudioTracks().firstOrNull; + if (track == null) { + await _disposeStream(stream); + throw StateError('нет аудиодорожки'); + } + track.enabled = audioTransmitting; + _audioSender = await pc.addTrack(track, stream); + final previous = _micStream; + _micStream = stream; + await _disposeStream(previous); + } + Future _applyMuted(bool muted, {bool announce = false}) async { _muted = muted; _applyAudioTracks(); @@ -3131,13 +3373,22 @@ class CallSession { if (sender == null) return false; for (final t in await pc.getTransceivers()) { if (t.sender.senderId != sender.senderId) continue; - final direction = await t.getCurrentDirection(); - return direction == TransceiverDirection.SendRecv || - direction == TransceiverDirection.SendOnly; + final current = await t.getCurrentDirection(); + if (current != null) return _sends(current); + final awaitingAnswer = + pc.signalingState == + RTCSignalingState.RTCSignalingStateHaveLocalOffer; + return awaitingAnswer && + t.mid.isNotEmpty && + _sends(await t.getDirection()); } return false; } + static bool _sends(TransceiverDirection direction) => + direction == TransceiverDirection.SendRecv || + direction == TransceiverDirection.SendOnly; + // #***! включение камеры Future switchCamera() async { if (!_localVideo || _pc == null) return; @@ -3172,10 +3423,22 @@ class CallSession { if (_localVideo) await _startCamera(deviceId: deviceId); } + bool get _holdsOneCameraAtATime => !_isDesktop; + Future _startCamera({String? deviceId}) async { final pc = _pc; if (pc == null) return; + final released = _cameraStream != null && _holdsOneCameraAtATime; + if (released) { + try { + await _videoSender?.replaceTrack(null); + } catch (_) {} + await _disposeStream(_cameraStream); + _cameraStream = null; + _notifyInfo(); + } + final opening = Stopwatch()..start(); _cameraOpening = true; final MediaStream stream; @@ -3184,6 +3447,9 @@ class CallSession { 'video': CameraDevices.constraints(deviceId ?? AppCamera.deviceId), 'audio': false, }); + } catch (_) { + if (released) await _stopCamera(); + rethrow; } finally { _cameraOpening = false; } @@ -3203,6 +3469,7 @@ class CallSession { } _localVideo = true; + await _speakerForVideo(); if (await _videoNegotiatedForSending(pc)) { logger.i('[call] camera on without renegotiation'); } else { @@ -3294,7 +3561,9 @@ class CallSession { if (!_isDesktop) { if (defaultTargetPlatform == TargetPlatform.android) { if (!await Helper.requestCapturePermission()) return null; - await CallBridge.instance.setScreenShare(true); + if (!await CallBridge.instance.setScreenShare(true)) { + throw StateError('система не дала звонку права на запись экрана'); + } } return navigator.mediaDevices.getDisplayMedia({ 'video': true, @@ -3399,6 +3668,7 @@ class CallSession { _collectDebounce?.cancel(); _slotProbeTimer?.cancel(); _videoStatsTimer?.cancel(); + _p2pWatchdog?.cancel(); try { await _probeChannel?.close(); } catch (_) {} @@ -3494,7 +3764,10 @@ class CallSession { _peerVideo = video; _peerScreen = screen; _notifyInfo(); - if (video || screen) unawaited(_collectReceivers()); + if (video || screen) { + unawaited(_collectReceivers()); + unawaited(_speakerForVideo()); + } } } diff --git a/lib/core/config/app_media_cache.dart b/lib/core/config/app_cache_limit.dart similarity index 59% rename from lib/core/config/app_media_cache.dart rename to lib/core/config/app_cache_limit.dart index 5dda1438..a101765d 100644 --- a/lib/core/config/app_media_cache.dart +++ b/lib/core/config/app_cache_limit.dart @@ -2,22 +2,20 @@ import 'package:flutter/foundation.dart'; import 'persisted_setting.dart'; -// #***! потолок кэша медиа, 0 значит не чистить вообще -class AppMediaCacheLimit { +// #***! потолок всего вытесняемого кэша, 0 значит не чистить вообще +class AppCacheLimit { static const prefKey = 'media_cache_limit_bytes'; - static const int defaultValue = 500 * 1024 * 1024; // 500 МБ + static const int defaultValue = 1024 * 1024 * 1024; - /// Значение «без лимита» — вытеснение из кэша отключено. static const int unlimited = 0; - // #***! пресеты для ползунка, от 100 МБ до безлимита - /// Доступные пресеты лимита, байты (0 — без лимита). static const List presets = [ - 100 * 1024 * 1024, 250 * 1024 * 1024, 500 * 1024 * 1024, 1024 * 1024 * 1024, 2 * 1024 * 1024 * 1024, + 5 * 1024 * 1024 * 1024, + 10 * 1024 * 1024 * 1024, unlimited, ]; diff --git a/lib/core/config/app_fonts.dart b/lib/core/config/app_fonts.dart index 5b83f694..b61abe4f 100644 --- a/lib/core/config/app_fonts.dart +++ b/lib/core/config/app_fonts.dart @@ -44,6 +44,45 @@ class AppFont { bool get isCustom => id.startsWith(AppFonts.customPrefix); } +@immutable +class AppTextScaler extends TextScaler { + const AppTextScaler(this.system, this.factor); + + final TextScaler system; + final double factor; + + @override + double scale(double fontSize) => system.scale(fontSize) * factor; + + @override + double get textScaleFactor => scale(1); + + @override + bool operator ==(Object other) => + other is AppTextScaler && + other.system == system && + other.factor == factor; + + @override + int get hashCode => Object.hash(system, factor); +} + +class AppTextScaling extends StatelessWidget { + const AppTextScaling({super.key, required this.factor, required this.child}); + + final double factor; + final Widget child; + + @override + Widget build(BuildContext context) { + final media = MediaQuery.of(context); + return MediaQuery( + data: media.copyWith(textScaler: AppTextScaler(media.textScaler, factor)), + child: child, + ); + } +} + // #***! реестр шрифтов class AppFonts { static const String prefKey = 'app_font'; diff --git a/lib/core/config/app_frost.dart b/lib/core/config/app_frost.dart index 307129bd..53b3a12f 100644 --- a/lib/core/config/app_frost.dart +++ b/lib/core/config/app_frost.dart @@ -8,6 +8,7 @@ class AppFrost { static const double mediaBackdropSigma = 30; static const double glassAlpha = 0.28; static const double blurPanelAlpha = 0.55; + static const double controlAlpha = 0.72; static const double scrimAlpha = 0.4; // #***! подкрашиваем блюр темой иначе он грязный @@ -16,6 +17,8 @@ class AppFrost { static Color blurPanelTint(ColorScheme cs) => glassTint(cs, blurPanelAlpha); + static Color controlTint(ColorScheme cs) => glassTint(cs, controlAlpha); + static Color scrim([double alpha = scrimAlpha]) => Colors.black.withValues(alpha: alpha); diff --git a/lib/core/config/app_motion.dart b/lib/core/config/app_motion.dart new file mode 100644 index 00000000..6c24bcf5 --- /dev/null +++ b/lib/core/config/app_motion.dart @@ -0,0 +1,26 @@ +import 'package:flutter/foundation.dart'; + +import 'persisted_setting.dart'; + +class AppMotion { + static const prefKey = 'app_animations_enabled'; + static const bool defaultValue = true; + + static final _setting = PersistedSetting( + prefKey: prefKey, + defaultValue: defaultValue, + read: (prefs, key) => prefs.getBool(key), + write: (prefs, key, value) async { + await prefs.setBool(key, value); + }, + ); + + static ValueNotifier get enabled => _setting.current; + + static Future load() => _setting.load(); + + static Future save(bool value) => _setting.save(value); + + static Duration of(Duration duration) => + enabled.value ? duration : Duration.zero; +} diff --git a/lib/core/config/chat_wallpaper_themes.dart b/lib/core/config/chat_wallpaper_themes.dart index 1de160ac..c871c422 100644 --- a/lib/core/config/chat_wallpaper_themes.dart +++ b/lib/core/config/chat_wallpaper_themes.dart @@ -1,161 +1,153 @@ import 'package:flutter/material.dart'; -import '../utils/tiled_svg.dart'; +@immutable +class WallpaperPattern { + final String asset; + final Color inkStart; + final Color inkEnd; + final Color glow; + + const WallpaperPattern({ + required this.asset, + required this.inkStart, + required this.inkEnd, + required this.glow, + }); +} -// #***! встроенные обои, градиент плюс SVG узор @immutable class ChatWallpaperTheme { final String id; - final List colors; - final AlignmentGeometry begin; - final AlignmentGeometry end; - final String? pattern; - final Color patternColor; - final double patternOpacity; - final double tileSize; + final Color top; + final Color bottom; + final Alignment begin; + final Alignment end; + final Color accent; final bool dark; + final WallpaperPattern? pattern; const ChatWallpaperTheme({ required this.id, - required this.colors, - this.begin = Alignment.topLeft, - this.end = Alignment.bottomRight, + required this.top, + required this.bottom, + required this.accent, + required this.dark, + this.begin = Alignment.topCenter, + this.end = Alignment.bottomCenter, this.pattern, - this.patternColor = Colors.white, - this.patternOpacity = 0.1, - this.tileSize = 130, - this.dark = true, }); Gradient get gradient => - LinearGradient(colors: colors, begin: begin, end: end); - - // #***! цвет пузыря под обои - Color get bubbleTint => colors.first; - - // #***! один виджет и для фона и для превью, отличается масштабом плитки - Widget buildBackground() => _ChatWallpaperThemeView(theme: this); - - Widget buildPreview() => - _ChatWallpaperThemeView(theme: this, tileScale: 0.42); -} - -// #***! градиент, сверху узор -class _ChatWallpaperThemeView extends StatelessWidget { - final ChatWallpaperTheme theme; - final double tileScale; - - const _ChatWallpaperThemeView({required this.theme, this.tileScale = 1}); - - @override - Widget build(BuildContext context) { - return Stack( - fit: StackFit.expand, - children: [ - DecoratedBox(decoration: BoxDecoration(gradient: theme.gradient)), - if (theme.pattern != null) - TiledSvgPattern( - asset: theme.pattern!, - color: theme.patternColor, - opacity: theme.patternOpacity, - tileSize: theme.tileSize * tileScale, - ), - ], - ); - } + LinearGradient(begin: begin, end: end, colors: [top, bottom]); } -const String _kPatternDir = 'assets/wallpapers/patterns'; - -// #***! сами пресеты, dark false значит текст и узор чёрные const List kChatWallpaperThemes = [ ChatWallpaperTheme( - id: 'ocean', - colors: [Color(0xFF2A7B9B), Color(0xFF57C1EB), Color(0xFF246FA8)], - pattern: '$_kPatternDir/bubbles.svg', - patternOpacity: 0.1, + id: 'komet', + top: Color(0xFF111214), + bottom: Color(0xFF222326), + begin: Alignment.topLeft, + end: Alignment.bottomRight, + accent: Color(0xFF767676), + dark: true, + pattern: WallpaperPattern( + asset: 'assets/wallpapers/patterns/komet.svg', + inkStart: Color(0xFF33363B), + inkEnd: Color(0xFF44474D), + glow: Color(0xFF6A6F78), + ), ), ChatWallpaperTheme( - id: 'sunset', - colors: [Color(0xFFFF7E5F), Color(0xFFFEB47B)], - pattern: '$_kPatternDir/hearts.svg', - patternOpacity: 0.12, + id: 'graphite', + top: Color(0xFF262626), + bottom: Color(0xFF1B1B1B), + accent: Color(0xFF767676), + dark: true, ), ChatWallpaperTheme( - id: 'lavender', - colors: [Color(0xFF9D50BB), Color(0xFF6E48AA)], - pattern: '$_kPatternDir/stars.svg', - patternOpacity: 0.11, + id: 'ink', + top: Color(0xFF1B2335), + bottom: Color(0xFF121827), + accent: Color(0xFF4A6FA5), + dark: true, ), ChatWallpaperTheme( - id: 'mint', - colors: [Color(0xFF43E97B), Color(0xFF38F9D7)], - pattern: '$_kPatternDir/plus.svg', - patternColor: Colors.black, - patternOpacity: 0.06, - tileSize: 66, - dark: false, + id: 'pine', + top: Color(0xFF19241F), + bottom: Color(0xFF111915), + accent: Color(0xFF4E8A6C), + dark: true, ), ChatWallpaperTheme( - id: 'graphite', - colors: [Color(0xFF232526), Color(0xFF414345)], - pattern: '$_kPatternDir/plus.svg', - patternOpacity: 0.06, - tileSize: 66, + id: 'plum', + top: Color(0xFF241D2A), + bottom: Color(0xFF18131D), + accent: Color(0xFF7D5D96), + dark: true, ), ChatWallpaperTheme( - id: 'sky', - colors: [Color(0xFF2193B0), Color(0xFF6DD5ED)], - pattern: '$_kPatternDir/planes.svg', - patternOpacity: 0.11, + id: 'umber', + top: Color(0xFF2A221D), + bottom: Color(0xFF1D1714), + accent: Color(0xFF9C6B47), + dark: true, ), ChatWallpaperTheme( - id: 'peach', - colors: [Color(0xFFFFD3A5), Color(0xFFFD6585)], - pattern: '$_kPatternDir/rings.svg', - patternColor: Colors.black, - patternOpacity: 0.05, + id: 'paper', + top: Color(0xFFF3F1EC), + bottom: Color(0xFFE7E3DB), + accent: Color(0xFF7A7A7A), dark: false, ), ChatWallpaperTheme( - id: 'forest', - colors: [Color(0xFF134E5E), Color(0xFF71B280)], - pattern: '$_kPatternDir/rings.svg', - patternOpacity: 0.09, - ), - ChatWallpaperTheme( - id: 'grape', - colors: [Color(0xFF4776E6), Color(0xFF8E54E9)], - pattern: '$_kPatternDir/stars.svg', - patternOpacity: 0.11, + id: 'fog', + top: Color(0xFFE8EBEF), + bottom: Color(0xFFDBE0E6), + accent: Color(0xFF56708F), + dark: false, ), ChatWallpaperTheme( - id: 'night', - colors: [Color(0xFF0F2027), Color(0xFF203A43), Color(0xFF2C5364)], - pattern: '$_kPatternDir/stars.svg', - patternOpacity: 0.08, + id: 'sage', + top: Color(0xFFE5E9E2), + bottom: Color(0xFFD6DDD3), + accent: Color(0xFF5B7F5C), + dark: false, ), ChatWallpaperTheme( - id: 'rose', - colors: [Color(0xFFF4C4F3), Color(0xFFFC67FA)], - pattern: '$_kPatternDir/hearts.svg', - patternOpacity: 0.14, + id: 'sand', + top: Color(0xFFF0E8DD), + bottom: Color(0xFFE3D8C8), + accent: Color(0xFF9A7650), + dark: false, ), ChatWallpaperTheme( - id: 'amber', - colors: [Color(0xFFF7971E), Color(0xFFFFD200)], - pattern: '$_kPatternDir/bubbles.svg', - patternColor: Colors.black, - patternOpacity: 0.05, + id: 'powder', + top: Color(0xFFF1E6E6), + bottom: Color(0xFFE4D5D6), + accent: Color(0xFF9C5E68), dark: false, ), ]; -// #***! поиск по id, незнакомый значит обои выпилили из сборки +const Map _retiredThemes = { + 'ocean': 'ink', + 'night': 'ink', + 'sky': 'fog', + 'sunset': 'sand', + 'peach': 'sand', + 'amber': 'sand', + 'lavender': 'plum', + 'grape': 'plum', + 'mint': 'sage', + 'forest': 'pine', + 'rose': 'powder', +}; + ChatWallpaperTheme? chatWallpaperThemeById(String? id) { if (id == null) return null; + final current = _retiredThemes[id] ?? id; for (final theme in kChatWallpaperThemes) { - if (theme.id == id) return theme; + if (theme.id == current) return theme; } return null; } diff --git a/lib/core/config/komet_settings.dart b/lib/core/config/komet_settings.dart index f61db51d..8ac447fe 100644 --- a/lib/core/config/komet_settings.dart +++ b/lib/core/config/komet_settings.dart @@ -12,6 +12,7 @@ class KometSettings { static const _kShowTypingTime = 'komet_show_typing_time'; static const _kGhostMode = 'komet_ghost_mode'; static const _kAntiRead = 'komet_anti_read'; + static const _kAntiStoryView = 'komet_anti_story_view'; static const _kSelfOnlineCheck = 'komet_self_online_check'; static const _kHideAllChatsFolder = 'komet_hide_all_chats_folder'; static const _kShowHiddenChats = 'komet_show_hidden_chats'; @@ -25,6 +26,10 @@ class KometSettings { static const _kAutoplayAnimoji = 'komet_autoplay_animoji'; static const _kAutoplayVideoNote = 'komet_autoplay_video_note'; static const _kRecordDebugLogs = 'komet_record_debug_logs'; + static const _kDebugSnow = 'komet_debug_snow'; + static const _kHideChannelRecommendations = + 'komet_hide_channel_recommendations'; + static const _kRecommendationsHiddenIn = 'komet_recommendations_hidden_in'; // #***! каждая настройка это ValueNotifier, юишка подписана напрямую static final ValueNotifier viewDeleted = ValueNotifier(false); @@ -34,6 +39,7 @@ class KometSettings { static final ValueNotifier showTypingTime = ValueNotifier(false); static final ValueNotifier ghostMode = ValueNotifier(false); static final ValueNotifier antiRead = ValueNotifier(false); + static final ValueNotifier antiStoryView = ValueNotifier(false); static final ValueNotifier selfOnlineCheck = ValueNotifier(true); static final ValueNotifier hideAllChatsFolder = ValueNotifier(false); static final ValueNotifier showHiddenChats = ValueNotifier(false); @@ -47,6 +53,13 @@ class KometSettings { static final ValueNotifier autoplayAnimoji = ValueNotifier(true); static final ValueNotifier autoplayVideoNote = ValueNotifier(true); static final ValueNotifier recordDebugLogs = ValueNotifier(true); + static final ValueNotifier debugSnow = ValueNotifier(false); + static final ValueNotifier hideChannelRecommendations = ValueNotifier( + false, + ); + static final ValueNotifier> recommendationsHiddenIn = ValueNotifier( + const {}, + ); // #***! читаем всё разом на старте static Future load() async { @@ -65,6 +78,9 @@ class KometSettings { BuildProfile.stealthPresence && (prefs.getBool(_kGhostMode) ?? false); antiRead.value = BuildProfile.stealthPresence && (prefs.getBool(_kAntiRead) ?? false); + antiStoryView.value = + BuildProfile.stealthPresence && + (prefs.getBool(_kAntiStoryView) ?? false); selfOnlineCheck.value = prefs.getBool(_kSelfOnlineCheck) ?? true; hideAllChatsFolder.value = prefs.getBool(_kHideAllChatsFolder) ?? false; showHiddenChats.value = prefs.getBool(_kShowHiddenChats) ?? false; @@ -79,6 +95,14 @@ class KometSettings { autoplayAnimoji.value = prefs.getBool(_kAutoplayAnimoji) ?? true; autoplayVideoNote.value = prefs.getBool(_kAutoplayVideoNote) ?? true; recordDebugLogs.value = prefs.getBool(_kRecordDebugLogs) ?? true; + debugSnow.value = prefs.getBool(_kDebugSnow) ?? false; + hideChannelRecommendations.value = + prefs.getBool(_kHideChannelRecommendations) ?? false; + recommendationsHiddenIn.value = { + for (final raw + in prefs.getStringList(_kRecommendationsHiddenIn) ?? const []) + ?int.tryParse(raw), + }; } // #***! дальше по сеттеру на настройку, память потом диск @@ -125,6 +149,12 @@ class KometSettings { await prefs.setBool(_kAntiRead, value); } + static Future setAntiStoryView(bool value) async { + antiStoryView.value = value; + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_kAntiStoryView, value); + } + static Future setSelfOnlineCheck(bool value) async { selfOnlineCheck.value = value; final prefs = await SharedPreferences.getInstance(); @@ -188,4 +218,21 @@ class KometSettings { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_kRecordDebugLogs, value); } + + static Future setDebugSnow(bool value) => + _setFlag(debugSnow, _kDebugSnow, value); + + static Future setHideChannelRecommendations(bool value) => + _setFlag(hideChannelRecommendations, _kHideChannelRecommendations, value); + + static Future hideRecommendationsIn(int chatId) async { + final hidden = recommendationsHiddenIn.value; + if (hidden.contains(chatId)) return; + final next = {...hidden, chatId}; + recommendationsHiddenIn.value = next; + final prefs = await SharedPreferences.getInstance(); + await prefs.setStringList(_kRecommendationsHiddenIn, [ + for (final id in next) '$id', + ]); + } } diff --git a/lib/core/config/whats_new.dart b/lib/core/config/whats_new.dart new file mode 100644 index 00000000..885791ef --- /dev/null +++ b/lib/core/config/whats_new.dart @@ -0,0 +1,66 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart' show rootBundle; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../utils/logger.dart'; +import '../whats_new/whats_new_document.dart'; +import 'build_profile.dart'; + +abstract final class WhatsNew { + static const String _seenBuildKey = 'whats_new_seen_build'; + static const String _notesDir = 'assets/whats_new'; + static const String _fallbackLanguage = 'en'; + + static final ValueNotifier pendingVersion = ValueNotifier(null); + static int? _build; + + static bool get enabled => !BuildProfile.selfUpdate; + + static Future load() async { + if (!enabled) return; + final info = await PackageInfo.fromPlatform(); + final build = int.tryParse(info.buildNumber); + if (build == null) return; + _build = build; + final prefs = await SharedPreferences.getInstance(); + final seen = prefs.getInt(_seenBuildKey); + if (seen == null) { + await prefs.setInt(_seenBuildKey, build); + return; + } + if (build > seen) pendingVersion.value = info.version; + } + + static Future dismiss() async { + if (pendingVersion.value == null) return; + pendingVersion.value = null; + final build = _build; + if (build == null) return; + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt(_seenBuildKey, build); + } + + static Future preview(bool on) async { + if (!on) { + pendingVersion.value = null; + return; + } + pendingVersion.value = (await PackageInfo.fromPlatform()).version; + } + + static Future document(String languageCode) async { + final String source; + try { + source = await rootBundle.loadString('$_notesDir/$languageCode.txt'); + } on FlutterError { + if (languageCode == _fallbackLanguage) return WhatsNewDocument.empty; + return document(_fallbackLanguage); + } + final parsed = WhatsNewDocument.parse(source); + for (final problem in parsed.problems) { + logger.w('[whats-new] $languageCode.txt, $problem'); + } + return parsed; + } +} diff --git a/lib/core/links/link_inspector.dart b/lib/core/links/link_inspector.dart new file mode 100644 index 00000000..2bfe12f6 --- /dev/null +++ b/lib/core/links/link_inspector.dart @@ -0,0 +1,412 @@ +import 'punycode.dart'; + +enum LinkScript { latin, cyrillic, greek, armenian } + +enum LinkWarningKind { + textMismatch, + userInfo, + mixedScripts, + lookalikeScript, + invisibleCharacters, + ipAddress, + unusualScheme, +} + +typedef LinkLetter = ({String letter, LinkScript script}); + +class LinkWarning { + const LinkWarning(this.kind, {this.value = '', this.letters = const []}); + + final LinkWarningKind kind; + final String value; + final List letters; +} + +class LinkInspection { + const LinkInspection({ + required this.url, + required this.address, + required this.host, + required this.hostStart, + required this.hostEnd, + required this.flagged, + required this.warnings, + }); + + final String url; + final String address; + final String host; + final int hostStart; + final int hostEnd; + final Set flagged; + final List warnings; + + bool get suspicious => warnings.isNotEmpty; +} + +const Set _ordinarySchemes = { + 'http', + 'https', + 'mailto', + 'tel', + 'geo', + 'komet', + 'max', +}; + +const Map _latinLookalikes = { + LinkScript.cyrillic: 'асеорхуіјѕһԁԛԝӏү', + LinkScript.greek: 'αικνορτυχ', + LinkScript.armenian: 'ոսօհզ', +}; + +final RegExp _ipHost = RegExp( + r'^(?:\[[0-9a-f:.]*\]|[0-9.]+|0x[0-9a-f]+(?:\.[0-9a-fx]+)*)$', + caseSensitive: false, +); + +final RegExp _domainTld = RegExp(r'^\p{L}{2,}$', unicode: true); + +final RegExp _schemePrefix = RegExp( + r'^[a-z][a-z0-9+.-]*:', + caseSensitive: false, +); + +final RegExp _hostWithPort = RegExp( + r'^[^\s/:?#@]+\.[^\s/:?#@]+:\d+(?:[/?#]|$)', +); + +String linkWithScheme(String url) { + final trimmed = url.trim(); + if (trimmed.isEmpty) return trimmed; + if (trimmed.startsWith('//')) return 'https:$trimmed'; + final hasScheme = + _schemePrefix.hasMatch(trimmed) && !_hostWithPort.hasMatch(trimmed); + return hasScheme ? trimmed : 'https://$trimmed'; +} + +LinkInspection inspectLink(String url, {String? shownText}) { + final raw = linkWithScheme(url); + final scheme = _schemeOf(raw); + final parts = _AuthorityParts.of(raw); + final address = _AddressBuilder(); + final warnings = []; + + if (parts == null) { + address.add(raw); + if (address.hasInvisible) { + warnings.add(const LinkWarning(LinkWarningKind.invisibleCharacters)); + } + if (scheme.isNotEmpty && !_ordinarySchemes.contains(scheme)) { + warnings.add(LinkWarning(LinkWarningKind.unusualScheme, value: scheme)); + } + return LinkInspection( + url: raw, + address: address.text, + host: '', + hostStart: -1, + hostEnd: -1, + flagged: address.flagged, + warnings: warnings, + ); + } + + final asciiHost = raw.substring(parts.hostStart, parts.hostEnd); + final decodedHost = _percentDecoded(asciiHost).toLowerCase(); + final host = decodePunycodeHost(decodedHost) ?? decodedHost; + final scripts = _ScriptReport.of(host); + + address.add(raw.substring(0, parts.userInfoStart)); + if (parts.hasUserInfo) { + address.add( + raw.substring(parts.userInfoStart, parts.hostStart), + flag: true, + ); + } + final hostStart = address.length; + address.add(host, flagAt: scripts.flagged); + final hostEnd = address.length; + address.add(_readableTail(raw.substring(parts.hostEnd))); + + final shownHost = shownText == null ? null : _hostShownBy(shownText); + if (shownHost != null && !_sameSite(shownHost, host)) { + warnings.add(LinkWarning(LinkWarningKind.textMismatch, value: shownHost)); + } + if (parts.hasUserInfo) { + warnings.add(LinkWarning(LinkWarningKind.userInfo, value: host)); + } + if (scripts.mixed.isNotEmpty) { + warnings.add( + LinkWarning(LinkWarningKind.mixedScripts, letters: scripts.mixed), + ); + } + if (scripts.lookalike.isNotEmpty) { + warnings.add( + LinkWarning(LinkWarningKind.lookalikeScript, letters: scripts.lookalike), + ); + } + if (address.hasInvisible) { + warnings.add(const LinkWarning(LinkWarningKind.invisibleCharacters)); + } + if (host.isNotEmpty && _ipHost.hasMatch(host)) { + warnings.add(LinkWarning(LinkWarningKind.ipAddress, value: host)); + } + if (scheme.isNotEmpty && !_ordinarySchemes.contains(scheme)) { + warnings.add(LinkWarning(LinkWarningKind.unusualScheme, value: scheme)); + } + + return LinkInspection( + url: raw, + address: address.text, + host: host, + hostStart: hostStart, + hostEnd: hostEnd, + flagged: address.flagged, + warnings: warnings, + ); +} + +bool _isInvisible(int rune) => + rune < 0x20 || + rune == 0x7F || + rune == 0xA0 || + rune == 0xAD || + rune == 0x34F || + rune == 0x61C || + rune == 0x115F || + rune == 0x1160 || + rune == 0x17B4 || + rune == 0x17B5 || + rune == 0x180E || + (rune >= 0x2000 && rune <= 0x200F) || + (rune >= 0x2028 && rune <= 0x202F) || + (rune >= 0x205F && rune <= 0x206F) || + rune == 0x3000 || + rune == 0x3164 || + rune == 0xFEFF || + rune == 0xFFA0 || + (rune >= 0xE0000 && rune <= 0xE007F); + +LinkScript? _scriptOf(int rune) { + if ((rune >= 0x41 && rune <= 0x5A) || (rune >= 0x61 && rune <= 0x7A)) { + return LinkScript.latin; + } + if (rune >= 0xC0 && rune <= 0x24F && rune != 0xD7 && rune != 0xF7) { + return LinkScript.latin; + } + if (rune >= 0x1E00 && rune <= 0x1EFF) return LinkScript.latin; + if ((rune >= 0x400 && rune <= 0x52F) || + (rune >= 0x1C80 && rune <= 0x1C8F) || + (rune >= 0x2DE0 && rune <= 0x2DFF) || + (rune >= 0xA640 && rune <= 0xA69F)) { + return LinkScript.cyrillic; + } + if ((rune >= 0x370 && rune <= 0x3FF) || (rune >= 0x1F00 && rune <= 0x1FFF)) { + return LinkScript.greek; + } + if (rune >= 0x530 && rune <= 0x58F) return LinkScript.armenian; + return null; +} + +String _schemeOf(String raw) { + final prefix = _schemePrefix.firstMatch(raw)?.group(0); + if (prefix == null) return ''; + return prefix.substring(0, prefix.length - 1).toLowerCase(); +} + +String _readableTail(String tail) { + final decoded = _percentDecodedFull(tail); + return decoded.runes.any(_isInvisible) ? tail : decoded; +} + +String _percentDecoded(String value) { + try { + return Uri.decodeComponent(value); + } on ArgumentError { + return value; + } on FormatException { + return value; + } +} + +String _percentDecodedFull(String value) { + try { + return Uri.decodeFull(value); + } on ArgumentError { + return value; + } on FormatException { + return value; + } +} + +String? _hostShownBy(String shownText) { + final text = shownText.trim(); + if (text.isEmpty || text.contains(RegExp(r'\s'))) return null; + final candidate = text.contains('://') ? text : 'https://$text'; + final parts = _AuthorityParts.of(candidate); + if (parts == null) return null; + final decoded = _percentDecoded( + candidate.substring(parts.hostStart, parts.hostEnd), + ).toLowerCase(); + final host = decodePunycodeHost(decoded) ?? decoded; + final labels = host.split('.'); + if (labels.length < 2 || labels.any((l) => l.isEmpty)) return null; + if (!_domainTld.hasMatch(labels.last)) return null; + return host; +} + +bool _sameSite(String a, String b) { + String bare(String host) => + host.startsWith('www.') ? host.substring(4) : host; + final left = bare(a); + final right = bare(b); + return left == right || left.endsWith('.$right') || right.endsWith('.$left'); +} + +class _AuthorityParts { + const _AuthorityParts({ + required this.userInfoStart, + required this.hostStart, + required this.hostEnd, + }); + + final int userInfoStart; + final int hostStart; + final int hostEnd; + + bool get hasUserInfo => hostStart > userInfoStart; + + static _AuthorityParts? of(String raw) { + final schemeEnd = raw.indexOf('://'); + if (schemeEnd <= 0) return null; + final start = schemeEnd + 3; + var end = raw.length; + for (var i = start; i < raw.length; i++) { + final unit = raw[i]; + if (unit == '/' || unit == '?' || unit == '#' || unit == r'\') { + end = i; + break; + } + } + final at = end > start ? raw.lastIndexOf('@', end - 1) : -1; + final hostStart = at >= start ? at + 1 : start; + var hostEnd = end; + if (hostStart < end && raw[hostStart] == '[') { + final close = raw.indexOf(']', hostStart); + if (close >= 0 && close < end) hostEnd = close + 1; + } else { + final colon = raw.indexOf(':', hostStart); + if (colon >= 0 && colon < end) hostEnd = colon; + } + return _AuthorityParts( + userInfoStart: start, + hostStart: hostStart, + hostEnd: hostEnd, + ); + } +} + +class _ScriptReport { + _ScriptReport(); + + final Set flagged = {}; + final List mixed = []; + final List lookalike = []; + + static _ScriptReport of(String host) { + final report = _ScriptReport(); + final labels = host.split('.'); + final tldIsAscii = labels.last.codeUnits.every((unit) => unit < 0x80); + var offset = 0; + for (final label in labels) { + report._inspectLabel(label, offset, tldIsAscii: tldIsAscii); + offset += label.length + 1; + } + return report; + } + + void _inspectLabel(String label, int offset, {required bool tldIsAscii}) { + final byScript = >{}; + var at = offset; + for (final rune in label.runes) { + final letter = String.fromCharCode(rune); + final script = _scriptOf(rune); + if (script != null) { + (byScript[script] ??= []).add((at: at, letter: letter)); + } + at += letter.length; + } + if (byScript.length > 1) { + final majority = byScript.entries.reduce((a, b) { + if (a.value.length != b.value.length) { + return a.value.length > b.value.length ? a : b; + } + return a.key == LinkScript.latin ? a : b; + }).key; + byScript.forEach((script, letters) { + if (script == majority) return; + for (final entry in letters) { + flagged.add(entry.at); + _addLetter(mixed, entry.letter, script); + } + }); + return; + } + if (byScript.length != 1 || !tldIsAscii) return; + final only = byScript.entries.single; + final lookalikes = _latinLookalikes[only.key]; + if (lookalikes == null) return; + if (!only.value.every((entry) => lookalikes.contains(entry.letter))) { + return; + } + for (final entry in only.value) { + flagged.add(entry.at); + _addLetter(lookalike, entry.letter, only.key); + } + } + + static void _addLetter( + List into, + String letter, + LinkScript script, + ) { + if (into.any((l) => l.letter == letter)) return; + into.add((letter: letter, script: script)); + } +} + +class _AddressBuilder { + final StringBuffer _buffer = StringBuffer(); + final Set flagged = {}; + bool hasInvisible = false; + + int get length => _buffer.length; + + String get text => _buffer.toString(); + + void add(String text, {bool flag = false, Set flagAt = const {}}) { + var offset = 0; + for (final rune in text.runes) { + final char = String.fromCharCode(rune); + if (_isInvisible(rune)) { + hasInvisible = true; + _flagged(_marker(rune)); + } else if (flag || flagAt.contains(offset)) { + _flagged(char); + } else { + _buffer.write(char); + } + offset += char.length; + } + } + + void _flagged(String text) { + for (var i = 0; i < text.length; i++) { + flagged.add(_buffer.length + i); + } + _buffer.write(text); + } + + static String _marker(int rune) => + '[U+${rune.toRadixString(16).toUpperCase().padLeft(4, '0')}]'; +} diff --git a/lib/core/links/punycode.dart b/lib/core/links/punycode.dart new file mode 100644 index 00000000..eeca44fa --- /dev/null +++ b/lib/core/links/punycode.dart @@ -0,0 +1,85 @@ +const String _prefix = 'xn--'; + +const int _base = 36; +const int _tMin = 1; +const int _tMax = 26; +const int _skew = 38; +const int _damp = 700; +const int _initialBias = 72; +const int _initialN = 128; +const int _maxCodePoint = 0x10FFFF; + +String? decodePunycodeLabel(String label) { + if (!label.toLowerCase().startsWith(_prefix)) return label; + return _decode(label.substring(_prefix.length)); +} + +String? decodePunycodeHost(String host) { + final labels = host.split('.'); + final decoded = []; + for (final label in labels) { + final unicode = decodePunycodeLabel(label); + if (unicode == null) return null; + decoded.add(unicode); + } + return decoded.join('.'); +} + +String? _decode(String input) { + if (input.isEmpty) return null; + final output = []; + final delimiter = input.lastIndexOf('-'); + final basicLength = delimiter < 0 ? 0 : delimiter; + for (var j = 0; j < basicLength; j++) { + final unit = input.codeUnitAt(j); + if (unit >= 0x80) return null; + output.add(unit); + } + + var n = _initialN; + var bias = _initialBias; + var i = 0; + var index = basicLength > 0 ? basicLength + 1 : 0; + while (index < input.length) { + final oldI = i; + var weight = 1; + for (var k = _base; ; k += _base) { + if (index >= input.length) return null; + final digit = _digitValue(input.codeUnitAt(index++)); + if (digit < 0) return null; + i += digit * weight; + if (i > _maxCodePoint * (output.length + 1)) return null; + final threshold = k <= bias + ? _tMin + : (k >= bias + _tMax ? _tMax : k - bias); + if (digit < threshold) break; + weight *= _base - threshold; + } + final length = output.length + 1; + bias = _adapt(i - oldI, length, oldI == 0); + n += i ~/ length; + i %= length; + if (n > _maxCodePoint || (n >= 0xD800 && n <= 0xDFFF)) return null; + output.insert(i, n); + i++; + } + return String.fromCharCodes(output); +} + +int _digitValue(int unit) { + if (unit >= 0x30 && unit <= 0x39) return unit - 0x30 + 26; + if (unit >= 0x41 && unit <= 0x5A) return unit - 0x41; + if (unit >= 0x61 && unit <= 0x7A) return unit - 0x61; + return -1; +} + +int _adapt(int delta, int points, bool first) { + var value = first ? delta ~/ _damp : delta ~/ 2; + value += value ~/ points; + var k = 0; + while (value > ((_base - _tMin) * _tMax) ~/ 2) { + value ~/= _base - _tMin; + k += _base; + } + return k + ((_base - _tMin + 1) * value) ~/ (value + _skew); +} diff --git a/lib/core/media/audio_file_metadata.dart b/lib/core/media/audio_file_metadata.dart new file mode 100644 index 00000000..bb6aa5d0 --- /dev/null +++ b/lib/core/media/audio_file_metadata.dart @@ -0,0 +1,199 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:audio_metadata_reader/audio_metadata_reader.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; +import 'package:image/image.dart' as img; + +import '../utils/media_cache.dart'; +import 'audio_file_track.dart'; + +class AudioFileMetadataInfo { + const AudioFileMetadataInfo({ + this.title, + this.artist, + this.album, + this.artworkUri, + }); + + final String? title; + final String? artist; + final String? album; + final Uri? artworkUri; +} + +abstract final class AudioFileMetadata { + static const int _cacheVersion = 2; + static const int _artworkMaxEdge = 160; + static final Map> _cache = {}; + static int _parseCount = 0; + + static Future read( + File file, { + required String cacheName, + }) async { + try { + final stat = await file.stat(); + final key = '${file.path}:${stat.size}'; + return await _cache.putIfAbsent(key, () => _read(file, cacheName, stat)); + } catch (_) { + return null; + } + } + + static Future enrich(AudioFileTrack track) async { + final metadata = await read(File(track.path), cacheName: track.cacheName); + if (metadata == null) return track; + final source = _text(metadata.artist) ?? _text(metadata.album); + return track.copyWith( + name: _text(metadata.title) ?? track.name, + sourceName: source ?? track.sourceName, + thumbnailUrl: metadata.artworkUri?.toString() ?? track.thumbnailUrl, + ); + } + + @visibleForTesting + static int get parseCountForTesting => _parseCount; + + @visibleForTesting + static void resetMemoryForTesting() => _cache.clear(); + + @visibleForTesting + static void resetForTesting() { + _cache.clear(); + _parseCount = 0; + } + + static Future _read( + File file, + String cacheName, + FileStat stat, + ) async { + final digest = sha1.convert(utf8.encode(cacheName)).toString(); + final metadataFile = await MediaCache.fileFor('audiometa_$digest.json'); + final artworkFile = await MediaCache.fileFor('audioart_$digest.jpg'); + final cached = await _readDiskCache(metadataFile, artworkFile, stat); + if (cached != null) return cached; + + _parseCount++; + final parsed = await Isolate.run( + () => _parseAudioMetadata(file.path, _artworkMaxEdge), + ); + final artwork = parsed?.artwork; + Uri? artworkUri; + if (artwork != null) { + await artworkFile.writeAsBytes( + artwork.materialize().asUint8List(), + flush: true, + ); + artworkUri = artworkFile.uri; + } else if (await artworkFile.exists()) { + await artworkFile.delete(); + } + + final info = AudioFileMetadataInfo( + title: _text(parsed?.title), + artist: _text(parsed?.artist), + album: _text(parsed?.album), + artworkUri: artworkUri, + ); + await metadataFile.writeAsString( + jsonEncode({ + 'version': _cacheVersion, + 'sourceSize': stat.size, + 'title': info.title, + 'artist': info.artist, + 'album': info.album, + 'hasArtwork': artworkUri != null, + }), + flush: true, + ); + return info; + } + + static Future _readDiskCache( + File metadataFile, + File artworkFile, + FileStat source, + ) async { + if (!await metadataFile.exists()) return null; + try { + final decoded = jsonDecode(await metadataFile.readAsString()); + if (decoded is! Map) return null; + if (decoded['version'] != _cacheVersion || + decoded['sourceSize'] != source.size) { + return null; + } + final hasArtwork = decoded['hasArtwork'] == true; + if (hasArtwork && !await artworkFile.exists()) return null; + return AudioFileMetadataInfo( + title: _text(decoded['title']?.toString()), + artist: _text(decoded['artist']?.toString()), + album: _text(decoded['album']?.toString()), + artworkUri: hasArtwork ? artworkFile.uri : null, + ); + } catch (_) { + return null; + } + } + + static String? _text(String? value) { + final normalized = value?.trim(); + return normalized == null || normalized.isEmpty ? null : normalized; + } +} + +({ + String? title, + String? artist, + String? album, + TransferableTypedData? artwork, +})? +_parseAudioMetadata(String path, int artworkMaxEdge) { + try { + final metadata = readMetadata(File(path), getImage: true); + Picture? picture; + for (final candidate in metadata.pictures) { + if (candidate.pictureType == PictureType.coverFront) { + picture = candidate; + break; + } + picture ??= candidate; + } + + TransferableTypedData? artwork; + if (picture != null && picture.bytes.isNotEmpty) { + final decoded = img.decodeImage(picture.bytes); + if (decoded != null) { + final resized = + decoded.width <= artworkMaxEdge && decoded.height <= artworkMaxEdge + ? decoded + : decoded.width >= decoded.height + ? img.copyResize( + decoded, + width: artworkMaxEdge, + interpolation: img.Interpolation.average, + ) + : img.copyResize( + decoded, + height: artworkMaxEdge, + interpolation: img.Interpolation.average, + ); + artwork = TransferableTypedData.fromList([ + img.encodeJpg(resized, quality: 82), + ]); + } + } + + return ( + title: metadata.title, + artist: metadata.artist ?? metadata.albumArtist, + album: metadata.album, + artwork: artwork, + ); + } catch (_) { + return null; + } +} diff --git a/lib/core/media/audio_file_track.dart b/lib/core/media/audio_file_track.dart index 3ee6d8d2..fb26784e 100644 --- a/lib/core/media/audio_file_track.dart +++ b/lib/core/media/audio_file_track.dart @@ -1,3 +1,14 @@ +enum AudioFileOrigin { message, downloads } + +typedef AudioFileEnricher = + Future Function(AudioFileTrack track); + +typedef AudioFileActivator = + Future Function( + AudioFileTrack track, { + required String notificationChannelName, + }); + // #***! аудиофайл в плеере плюс откуда он взялся class AudioFileTrack { const AudioFileTrack({ @@ -9,6 +20,7 @@ class AudioFileTrack { this.messageId, this.messageTime, this.thumbnailUrl, + this.origin = AudioFileOrigin.message, }); final String cacheName; @@ -19,4 +31,21 @@ class AudioFileTrack { final String? messageId; final int? messageTime; final String? thumbnailUrl; + final AudioFileOrigin origin; + + AudioFileTrack copyWith({ + String? name, + String? sourceName, + String? thumbnailUrl, + }) => AudioFileTrack( + cacheName: cacheName, + path: path, + name: name ?? this.name, + sourceName: sourceName ?? this.sourceName, + chatId: chatId, + messageId: messageId, + messageTime: messageTime, + thumbnailUrl: thumbnailUrl ?? this.thumbnailUrl, + origin: origin, + ); } diff --git a/lib/core/media/audio_playback_controller.dart b/lib/core/media/audio_playback_controller.dart index 39356456..5c8d4464 100644 --- a/lib/core/media/audio_playback_controller.dart +++ b/lib/core/media/audio_playback_controller.dart @@ -107,12 +107,16 @@ class AudioPlaybackController { bufferedPosition.value = Duration.zero; duration.value = Duration.zero; await _handler.load(track); - await _handler.play(); + unawaited(_handler.play()); } - Future toggle() { + Future toggle() async { _pausedByCall = false; - return playing.value ? _handler.pause() : _handler.play(); + if (playing.value) { + await _handler.pause(); + } else { + unawaited(_handler.play()); + } } Future seek(Duration value) => _handler.seek(value); diff --git a/lib/core/media/auto_download_gate.dart b/lib/core/media/auto_download_gate.dart index 02f03541..f35fb6d6 100644 --- a/lib/core/media/auto_download_gate.dart +++ b/lib/core/media/auto_download_gate.dart @@ -1,18 +1,97 @@ +import 'dart:async'; +import 'dart:collection'; + import 'package:flutter/foundation.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; + +enum ManualLoad { unknown, missing, loaded } + +class _GateState extends ValueNotifier { + _GateState() : super(ManualLoad.unknown); + + bool probing = false; + + bool get watched => hasListeners; +} class AutoDownloadGate { AutoDownloadGate._(); - static final Map> _loaded = {}; + @visibleForTesting + static int capacity = 512; + + static final LinkedHashMap _states = LinkedHashMap(); + + @visibleForTesting + static Future Function(String key) isCached = _inImageCache; + + @visibleForTesting + static int get size => _states.length; + + @visibleForTesting + static void reset() { + _states.clear(); + isCached = _inImageCache; + capacity = 512; + } - static ValueListenable listen(String key) => - _loaded.putIfAbsent(key, () => ValueNotifier(false)); + static ValueListenable listen(String key) => _state(key); static bool allows(bool autoEnabled, String key) => - autoEnabled || (_loaded[key]?.value ?? false); + autoEnabled || _resolved(key) == ManualLoad.loaded; + + static bool awaitsTap(bool autoEnabled, String key) => + !autoEnabled && _resolved(key) == ManualLoad.missing; + + static void loadManually(String key) => + _state(key).value = ManualLoad.loaded; + + static _GateState _state(String key) { + final existing = _states.remove(key); + if (existing != null) { + _states[key] = existing; + return existing; + } + final created = _states[key] = _GateState(); + _evictIdle(); + return created; + } - static void loadManually(String key) { - final notifier = _loaded.putIfAbsent(key, () => ValueNotifier(false)); - notifier.value = true; + static void _evictIdle() { + var excess = _states.length - capacity; + if (excess <= 0) return; + final idle = []; + for (final entry in _states.entries) { + if (excess == 0) break; + if (entry.value.watched) continue; + idle.add(entry.key); + excess--; + } + for (final key in idle) { + _states.remove(key)?.dispose(); + } } + + static ManualLoad _resolved(String key) { + final state = _state(key); + if (state.value == ManualLoad.unknown && !state.probing) { + state.probing = true; + unawaited(_probe(key, state)); + } + return state.value; + } + + static Future _probe(String key, _GateState state) async { + var cached = false; + try { + cached = await isCached(key); + } catch (_) {} + if (!identical(_states[key], state)) return; + state.probing = false; + if (state.value != ManualLoad.unknown) return; + state.value = cached ? ManualLoad.loaded : ManualLoad.missing; + } + + static Future _inImageCache(String key) async => + await DefaultCacheManager().getFileFromCache(key) != null; } diff --git a/lib/core/media/thumbhash.dart b/lib/core/media/thumbhash.dart new file mode 100644 index 00000000..fee698f8 --- /dev/null +++ b/lib/core/media/thumbhash.dart @@ -0,0 +1,125 @@ +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:image/image.dart' as img; + +Uint8List? thumbHashToPng(List hash) { + final decoded = thumbHashToRgba(hash); + if (decoded == null) return null; + final image = img.Image.fromBytes( + width: decoded.width, + height: decoded.height, + bytes: decoded.rgba.buffer, + numChannels: 4, + ); + return img.encodePng(image); +} + +({int width, int height, Uint8List rgba})? thumbHashToRgba(List hash) { + if (hash.length < 5) return null; + final header24 = hash[0] | (hash[1] << 8) | (hash[2] << 16); + final header16 = hash[3] | (hash[4] << 8); + final lDc = (header24 & 63) / 63; + final pDc = ((header24 >> 6) & 63) / 31.5 - 1; + final qDc = ((header24 >> 12) & 63) / 31.5 - 1; + final lScale = ((header24 >> 18) & 31) / 31; + final hasAlpha = (header24 >> 23) != 0; + final pScale = ((header16 >> 3) & 63) / 63; + final qScale = ((header16 >> 9) & 63) / 63; + final isLandscape = (header16 >> 15) != 0; + final lx = math.max(3, isLandscape ? (hasAlpha ? 5 : 7) : header16 & 7); + final ly = math.max(3, isLandscape ? header16 & 7 : (hasAlpha ? 5 : 7)); + if (hasAlpha && hash.length < 6) return null; + final aDc = hasAlpha ? (hash[5] & 15) / 15 : 1.0; + final aScale = hasAlpha ? (hash[5] >> 4) / 15 : 0.0; + + final acStart = hasAlpha ? 6 : 5; + var acIndex = 0; + List? channel(int nx, int ny, double scale) { + final ac = []; + for (var cy = 0; cy < ny; cy++) { + for (var cx = cy > 0 ? 0 : 1; cx * ny < nx * (ny - cy); cx++) { + final at = acStart + (acIndex >> 1); + if (at >= hash.length) return null; + final nibble = (hash[at] >> ((acIndex & 1) << 2)) & 15; + acIndex++; + ac.add((nibble / 7.5 - 1) * scale); + } + } + return ac; + } + + final lAc = channel(lx, ly, lScale); + final pAc = channel(3, 3, pScale * 1.25); + final qAc = channel(3, 3, qScale * 1.25); + final aAc = hasAlpha ? channel(5, 5, aScale) : const []; + if (lAc == null || pAc == null || qAc == null || aAc == null) return null; + + final ratio = _approximateAspect(hash); + final width = (ratio > 1 ? 32 : 32 * ratio).round(); + final height = (ratio > 1 ? 32 / ratio : 32).round(); + if (width <= 0 || height <= 0) return null; + + final rgba = Uint8List(width * height * 4); + final fx = List.filled(math.max(lx, hasAlpha ? 5 : 3), 0); + final fy = List.filled(math.max(ly, hasAlpha ? 5 : 3), 0); + var i = 0; + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++, i += 4) { + var l = lDc; + var p = pDc; + var q = qDc; + var a = aDc; + for (var cx = 0; cx < fx.length; cx++) { + fx[cx] = math.cos(math.pi / width * (x + 0.5) * cx); + } + for (var cy = 0; cy < fy.length; cy++) { + fy[cy] = math.cos(math.pi / height * (y + 0.5) * cy); + } + var j = 0; + for (var cy = 0; cy < ly; cy++) { + final fy2 = fy[cy] * 2; + for (var cx = cy > 0 ? 0 : 1; cx * ly < lx * (ly - cy); cx++, j++) { + l += lAc[j] * fx[cx] * fy2; + } + } + j = 0; + for (var cy = 0; cy < 3; cy++) { + final fy2 = fy[cy] * 2; + for (var cx = cy > 0 ? 0 : 1; cx < 3 - cy; cx++, j++) { + final f = fx[cx] * fy2; + p += pAc[j] * f; + q += qAc[j] * f; + } + } + if (hasAlpha) { + j = 0; + for (var cy = 0; cy < 5; cy++) { + final fy2 = fy[cy] * 2; + for (var cx = cy > 0 ? 0 : 1; cx < 5 - cy; cx++, j++) { + a += aAc[j] * fx[cx] * fy2; + } + } + } + final b = l - 2 / 3 * p; + final r = (3 * l - b + q) / 2; + final g = r - q; + rgba[i] = _channel(r); + rgba[i + 1] = _channel(g); + rgba[i + 2] = _channel(b); + rgba[i + 3] = _channel(a); + } + } + return (width: width, height: height, rgba: rgba); +} + +int _channel(double value) => (255 * value.clamp(0.0, 1.0)).toInt(); + +double _approximateAspect(List hash) { + final header = hash[3]; + final hasAlpha = hash[2] & 0x80 != 0; + final isLandscape = hash[4] & 0x80 != 0; + final lx = isLandscape ? (hasAlpha ? 5 : 7) : header & 7; + final ly = isLandscape ? header & 7 : (hasAlpha ? 5 : 7); + return ly == 0 ? 0 : lx / ly; +} diff --git a/lib/core/media/tlottie/tlottie_disk_cache.dart b/lib/core/media/tlottie/tlottie_disk_cache.dart index 2ea58503..9e2a4168 100644 --- a/lib/core/media/tlottie/tlottie_disk_cache.dart +++ b/lib/core/media/tlottie/tlottie_disk_cache.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:path_provider/path_provider.dart'; +import '../../cache/cache_janitor.dart'; import '../../utils/logger.dart'; // #***! кадры кэшируем на диск, рендерить заново слишком дорого @@ -14,12 +15,9 @@ class TlottieDiskCache { static const _extension = '.ktlf'; static const _legacyDirName = 'rlottie_frames'; // #***! под кадры отдаём 256 МБ - static const int _maxBytes = 256 * 1024 * 1024; - static const Duration _evictDelay = Duration(seconds: 2); + static const int maxBytes = 256 * 1024 * 1024; - Directory? _dir; Future? _dirFuture; - Timer? _evictTimer; Future _directory() { return _dirFuture ??= () async { @@ -27,7 +25,6 @@ class TlottieDiskCache { final dir = Directory('${base.path}/tlottie_frames'); if (!await dir.exists()) await dir.create(recursive: true); unawaited(_dropLegacy(base)); - _dir = dir; return dir; }(); } @@ -52,48 +49,10 @@ class TlottieDiskCache { return '${dir.path}/${_key(url, px)}'; } - void noteWritten() { - _evictTimer?.cancel(); - _evictTimer = Timer(_evictDelay, () { - _evictTimer = null; - unawaited(_evict()); - }); - } + void noteWritten(int bytes) => + CacheJanitor.instance.noteWrite(CacheStore.stickerFrames, bytes); - // #***! вытеснение по времени доступа - Future _evict() async { - try { - final dir = _dir ?? await _directory(); - final files = await dir - .list() - .where((e) => e is File && e.path.endsWith(_extension)) - .cast() - .toList(); - var total = 0; - final stats = <(File, FileStat)>[]; - for (final f in files) { - final st = await f.stat(); - total += st.size; - stats.add((f, st)); - } - if (total <= _maxBytes) return; - stats.sort((a, b) => a.$2.modified.compareTo(b.$2.modified)); - for (final (file, st) in stats) { - if (total <= _maxBytes) break; - total -= st.size; - await file.delete().catchError((_) => file); - } - } catch (e) { - logger.w('TlottieDiskCache.evict failed: $e'); - } - } + Future directoryPath() async => (await _directory()).path; - Future clear() async { - try { - final dir = await _directory(); - if (await dir.exists()) await dir.delete(recursive: true); - _dir = null; - _dirFuture = null; - } catch (_) {} - } + static bool holds(String name) => name.endsWith(_extension); } diff --git a/lib/core/media/tlottie/tlottie_engine.dart b/lib/core/media/tlottie/tlottie_engine.dart index 2662a4ac..cba79c2e 100644 --- a/lib/core/media/tlottie/tlottie_engine.dart +++ b/lib/core/media/tlottie/tlottie_engine.dart @@ -264,7 +264,7 @@ class TlottieEngine { } else if (message is LoadMiss) { unawaited(_onMiss(message)); } else if (message is CacheWritten) { - TlottieDiskCache.instance.noteWritten(); + TlottieDiskCache.instance.noteWritten(message.bytes); } else if (message is RenderError) { _onError(message); } @@ -452,11 +452,15 @@ class TlottieEngine { // #***! кэш в памяти, потом диск, потом рендер Future acquire(String url, int px, {String? inlineJson}) async { if (!available) return null; + final cached = _clips[_keyFor(url, px)]; + if (cached != null) return _retain(cached); final clip = await _start(url, px, inlineJson, keep: false); - if (clip != null) { - clip.lastUsed = _tick(); - clip.active++; - } + return clip == null ? null : _retain(clip); + } + + TlottieClip _retain(TlottieClip clip) { + clip.lastUsed = _tick(); + clip.active++; return clip; } diff --git a/lib/core/media/tlottie/tlottie_worker.dart b/lib/core/media/tlottie/tlottie_worker.dart index a36e6ff7..7f00ef49 100644 --- a/lib/core/media/tlottie/tlottie_worker.dart +++ b/lib/core/media/tlottie/tlottie_worker.dart @@ -77,7 +77,9 @@ class LoadMiss { } class CacheWritten { - const CacheWritten(); + const CacheWritten(this.bytes); + + final int bytes; } class WorkerIdle { @@ -227,8 +229,9 @@ void tlottieWorkerMain(WorkerConfig config) { final path = job.cachePath; if (path == null) return; try { - File(path).writeAsBytesSync(TlottieCodec.encode(header, frames)); - toMain.send(const CacheWritten()); + final encoded = TlottieCodec.encode(header, frames); + File(path).writeAsBytesSync(encoded); + toMain.send(CacheWritten(encoded.length)); } catch (_) {} } diff --git a/lib/core/media/video_preloader.dart b/lib/core/media/video_preloader.dart index 90892323..e1dad6d5 100644 --- a/lib/core/media/video_preloader.dart +++ b/lib/core/media/video_preloader.dart @@ -25,6 +25,7 @@ class VideoPreloader { void Function(double progress)? onProgress, bool Function()? cancelled, int? maxBytes, + Map Function(Uri url)? headers, }) async { final cached = await MediaCache.existing(cacheName); if (cached != null) return cached; @@ -35,6 +36,7 @@ class VideoPreloader { onProgress, cancelled, maxBytes, + headers, ); // #***! видимый кружок в начало очереди if (priority) { @@ -73,6 +75,7 @@ class VideoPreloader { url, onProgress: job.onProgress, maxBytes: job.maxBytes, + headers: job.headers?.call(Uri.parse(url)) ?? const {}, ); } } catch (_) { @@ -89,6 +92,7 @@ class _PreloadJob { this.onProgress, this.cancelled, this.maxBytes, + this.headers, ); final String cacheName; @@ -96,5 +100,6 @@ class _PreloadJob { final void Function(double progress)? onProgress; final bool Function()? cancelled; final int? maxBytes; + final Map Function(Uri url)? headers; final Completer result = Completer(); } diff --git a/lib/core/media/voice_audio_controller.dart b/lib/core/media/voice_audio_controller.dart index 71e69fab..8ea2afeb 100644 --- a/lib/core/media/voice_audio_controller.dart +++ b/lib/core/media/voice_audio_controller.dart @@ -12,6 +12,7 @@ import '../utils/logger.dart'; import '../utils/media_cache.dart'; import 'opus_ogg_index.dart'; import 'voice_playback_session.dart'; +import '../utils/media_cache_names.dart'; // #***! почему не играет, не скачалось или плеер не открыл enum VoiceAudioFailure { none, download, playback } @@ -59,7 +60,7 @@ class VoiceAudioController { // #***! один ключ кэша у пузыря, сохранения и вкладки голосовых static String cacheNameFor({int? audioId, required String messageId}) => - '${audioId ?? messageId}.ogg'; + voiceCacheName(audioId: audioId, messageId: messageId); // #***! у конца считаем что дослушали иначе последний тик не совпадёт static const double _endEpsilon = 0.05; diff --git a/lib/core/protocol/opcode_map.dart b/lib/core/protocol/opcode_map.dart index 05b428ef..8e0d0fa7 100644 --- a/lib/core/protocol/opcode_map.dart +++ b/lib/core/protocol/opcode_map.dart @@ -235,7 +235,8 @@ abstract class Opcode { static const int orgInfo = 256; // Инфо об организации / бизнес-профиле static const int getQr = 288; // Получение QR для входа static const int getQrStatus = 289; // Статус QR-входа - static const int loginByQr = 291; // Вход по QR + static const int authByTrack = 291; + static const int authCheckCall = 294; static const int msgDelivery = 303; // Подтверждение доставки сообщения // ── Human-readable names ─────────────────────────────────────────── @@ -425,7 +426,8 @@ abstract class Opcode { orgInfo: 'ORG_INFO', getQr: 'GET_QR', getQrStatus: 'GET_QR_STATUS', - loginByQr: 'LOGIN_BY_QR', + authByTrack: 'AUTH_BY_TRACK', + authCheckCall: 'AUTH_CHECK_CALL', msgDelivery: 'MSG_DELIVERY', }; } diff --git a/lib/core/push/fkm_bridge.dart b/lib/core/push/fkm_bridge.dart index 829487ea..57f5218e 100644 --- a/lib/core/push/fkm_bridge.dart +++ b/lib/core/push/fkm_bridge.dart @@ -48,6 +48,9 @@ class FkmBridge { Future setConnected(bool connected) => _invoke('setConnected', {'connected': connected}); + Future setUnread(int count) => + _invoke('setUnread', {'count': count}); + Future showMessage(Map data) => _invoke('showMessage', {'data': data}); diff --git a/lib/core/push/fkm_controller.dart b/lib/core/push/fkm_controller.dart index 69b37a20..eaaa0c36 100644 --- a/lib/core/push/fkm_controller.dart +++ b/lib/core/push/fkm_controller.dart @@ -15,10 +15,12 @@ import '../../core/storage/token_storage.dart'; import '../config/komet_settings.dart'; import '../utils/logger.dart'; import 'fkm_bridge.dart'; +import 'launcher_badge.dart'; import 'push_service.dart'; const _fallbackSender = 'MAX'; const _hiddenPreview = 'Новое сообщение'; +const _unreadThrottle = Duration(milliseconds: 300); // #***! FKM, своё фоновое уведомление для флейвора без гугла /// FKM — уведомления через собственное фоновое соединение, без FCM. @@ -35,6 +37,8 @@ class FkmController { Api? _api; StreamSubscription? _pushSub; StreamSubscription? _stateSub; + Timer? _unreadTimer; + int? _sentUnread; bool _started = false; bool get isSupported => FkmBridge.instance.isSupported; @@ -56,11 +60,15 @@ class FkmController { ) .listen(_onPush); _stateSub = api.stateStream.listen(_onSessionState); + for (final source in BadgeCount.chatSources) { + source.addListener(_scheduleUnread); + } if (enabled.value) { await initLocalNotificationActions(); await FkmBridge.instance.setEnabled(true); await _pushConnectionState(); + _scheduleUnread(); } } @@ -74,12 +82,19 @@ class FkmController { if (value) await initLocalNotificationActions(); await FkmBridge.instance.setEnabled(value); enabled.value = value; - if (value) await _pushConnectionState(); + _sentUnread = null; + if (value) { + await _pushConnectionState(); + _scheduleUnread(); + } return true; } // #***! выключили FKM кнопкой в уведомлении - void _onDisabledFromNotification() => enabled.value = false; + void _onDisabledFromNotification() { + enabled.value = false; + _sentUnread = null; + } void _onSessionState(SessionState state) { if (!enabled.value) return; @@ -87,9 +102,28 @@ class FkmController { } // #***! говорим нативу есть ли связь, от этого текст постоянного уведомления - Future _pushConnectionState() => FkmBridge.instance.setConnected( - _api?.state == SessionState.online, - ); + Future _pushConnectionState() => + FkmBridge.instance.setConnected(_api?.state == SessionState.online); + + // #***! в постоянном уведомлении непрочитанные в чатах со звуком, не всё принятое + void _scheduleUnread() { + if (!enabled.value || _unreadTimer != null) return; + _unreadTimer = Timer(_unreadThrottle, _syncUnread); + } + + void _syncUnread() { + _unreadTimer = null; + if (!enabled.value) return; + if (_sentUnread == null && !chats.chatsLoaded) return; + final count = BadgeCount.live( + enabled: true, + includeMuted: false, + countMessages: true, + ).count; + if (count == _sentUnread) return; + _sentUnread = count; + unawaited(FkmBridge.instance.setUnread(count)); + } // #***! входящий звонок, натив рисует полноэкранное /// Входящий звонок, когда приложение не на переднем плане. @@ -250,9 +284,7 @@ class FkmController { if (chat != null && chat.isMuted) return null; final rawConfig = await AppDatabase.getPrivacyConfig(accountId); - final config = rawConfig == null - ? null - : PrivacyConfig.fromJson(rawConfig); + final config = rawConfig == null ? null : PrivacyConfig.fromJson(rawConfig); if (config != null && !_pushAllowed(config, chat, msg, accountId)) { return null; } @@ -317,8 +349,14 @@ class FkmController { void dispose() { _pushSub?.cancel(); _stateSub?.cancel(); + _unreadTimer?.cancel(); + for (final source in BadgeCount.chatSources) { + source.removeListener(_scheduleUnread); + } _pushSub = null; _stateSub = null; + _unreadTimer = null; + _sentUnread = null; _started = false; } } diff --git a/lib/core/push/launcher_badge.dart b/lib/core/push/launcher_badge.dart index 6d76a250..e733356e 100644 --- a/lib/core/push/launcher_badge.dart +++ b/lib/core/push/launcher_badge.dart @@ -47,6 +47,29 @@ class BadgeCount { ); } + factory BadgeCount.live({ + required bool enabled, + required bool includeMuted, + required bool countMessages, + }) => BadgeCount.of( + chats.chatsLoaded + ? chats.chatsSnapshot( + includeHidden: KometSettings.showHiddenChats.value, + ) + : const [], + enabled: enabled, + includeMuted: includeMuted, + countMessages: countMessages, + isArchived: (chat) => + ArchivedChatsStore.instance.isArchived(chat.accountId, chat.id), + ); + + static List get chatSources => [ + chats.chatsChanged, + ArchivedChatsStore.instance.revision, + KometSettings.showHiddenChats, + ]; + final bool enabled; final bool byChats; final int count; @@ -86,9 +109,7 @@ class LauncherBadge { bool _sawChats = false; List get _sources => [ - chats.chatsChanged, - ArchivedChatsStore.instance.revision, - KometSettings.showHiddenChats, + ...BadgeCount.chatSources, AppBadge.enabled.current, AppBadge.includeMuted.current, AppBadge.countMessages.current, @@ -129,17 +150,10 @@ class LauncherBadge { final loaded = chats.chatsLoaded; if (enabled && !loaded && !_sawChats) return null; if (loaded) _sawChats = true; - return BadgeCount.of( - loaded - ? chats.chatsSnapshot( - includeHidden: KometSettings.showHiddenChats.value, - ) - : const [], + return BadgeCount.live( enabled: enabled, includeMuted: AppBadge.includeMuted.current.value, countMessages: AppBadge.countMessages.current.value, - isArchived: (chat) => - ArchivedChatsStore.instance.isArchived(chat.accountId, chat.id), ); } diff --git a/lib/core/push/push_service.dart b/lib/core/push/push_service.dart index 5c4336d8..9a25e7f0 100644 --- a/lib/core/push/push_service.dart +++ b/lib/core/push/push_service.dart @@ -18,7 +18,7 @@ import '../protocol/opcode_map.dart'; import '../storage/app_instance.dart'; import '../storage/app_database.dart'; import '../storage/token_storage.dart'; -import '../transport/tls_config.dart'; +import '../transport/network_core.dart'; import '../utils/logger.dart'; import 'notification_bridge.dart'; @@ -60,7 +60,7 @@ Future _initIsolate() async { SharedPreferences.setPrefix('flutter.${AppInstance.id}.'); } catch (_) {} } - await TlsConfig.applyMincifryTrust(); + await NetworkCore.configure(); } // #***! своя сессия аккаунта ради одного запроса, после него отключаемся @@ -140,7 +140,7 @@ Future _handleCallDecline(String payloadJson) async { // Фоновый изолят: инициализируем ядро перед vcp-декодом/сигналингом. await initKolibri(); - await TlsConfig.applyMincifryTrust(); + await NetworkCore.configure(); final params = ConversationParams.decode(vcp); if (params == null) return; diff --git a/lib/core/storage/app_database.dart b/lib/core/storage/app_database.dart index fd13b4e5..bb9543a6 100644 --- a/lib/core/storage/app_database.dart +++ b/lib/core/storage/app_database.dart @@ -179,6 +179,7 @@ abstract class SyncKey { static const profileInviteLink = 'profile_invite_link'; static const welcomeStickerIds = 'welcome_sticker_ids'; static const channelsFolderSuggested = 'channels_folder_suggested'; + static const viewsCountEnabled = 'views_count_enabled'; static const folderFiltersEnabled = 'folder_filters_enabled'; static const privacyOverrides = 'privacy_overrides'; } @@ -230,6 +231,20 @@ class AppDatabase { .getDatabasesPath(); } + static String get _databaseName => 'komet${AppInstance.suffix}.db'; + + static Future fileBytes() async { + final base = join(await _databasesDir(), _databaseName); + var total = 0; + for (final suffix in const ['', '-wal', '-shm']) { + try { + final file = File('$base$suffix'); + if (await file.exists()) total += await file.length(); + } catch (_) {} + } + return total; + } + static String? _legacyExposedDb; // #***! WAL живёт в отдельных файлах, копировать надо все три @@ -291,7 +306,7 @@ class AppDatabase { static Future _open() async { final dbPath = await _databasesDir(); await Directory(dbPath).create(recursive: true); - final target = join(dbPath, 'komet${AppInstance.suffix}.db'); + final target = join(dbPath, _databaseName); await _migrateLegacyDb(target); final opened = await openDatabase( target, @@ -1536,6 +1551,23 @@ class AppDatabase { return changed != 0; } + static Future requeueFailedMessage( + int accountId, + int chatId, + String messageId, + ) async { + final db = await _instance; + final changed = await db.update( + 'messages', + {'status': 'pending'}, + where: + 'account_id = ? AND chat_id = ? AND id = ? ' + "AND status = 'error' AND deleted = 0", + whereArgs: [accountId, chatId, messageId], + ); + return changed != 0; + } + // #***! дальше выборки истории, с конца до сообщения между и вокруг static Future>> loadMessages( int accountId, diff --git a/lib/core/storage/chat_wallpaper_store.dart b/lib/core/storage/chat_wallpaper_store.dart index 16ef8f31..8297420a 100644 --- a/lib/core/storage/chat_wallpaper_store.dart +++ b/lib/core/storage/chat_wallpaper_store.dart @@ -12,7 +12,7 @@ import 'per_chat_json_store.dart'; const int kGlobalWallpaperChatId = 0; // #***! обои, своя картинка, встроенная тема или свой градиент -enum ChatWallpaperKind { image, theme, gradient } +enum ChatWallpaperKind { image, theme, gradient, none } // #***! правки картинки, затемнение блюр параллакс сдвиг @immutable @@ -82,11 +82,25 @@ class ChatWallpaper { motion = false, offsetX = 0; + const ChatWallpaper.none() + : kind = ChatWallpaperKind.none, + imagePath = null, + themeId = null, + gradientColors = null, + gradientAnimated = false, + gradientRotation = 0, + dim = 0, + blur = false, + motion = false, + offsetX = 0; + bool get isImage => kind == ChatWallpaperKind.image; bool get isGradient => kind == ChatWallpaperKind.gradient; + bool get isNone => kind == ChatWallpaperKind.none; // #***! в джейсон или путь с настройками, или id темы, или свои цвета Map _toJson() { + if (isNone) return const {'none': true}; if (isImage) { return { 'path': imagePath, @@ -108,6 +122,7 @@ class ChatWallpaper { static ChatWallpaper? _fromJson(Object? raw) { if (raw is! Map) return null; + if (raw['none'] == true) return const ChatWallpaper.none(); final path = raw['path']; if (path is String && path.isNotEmpty) { return ChatWallpaper.image( @@ -147,6 +162,18 @@ class ChatWallpaperStore extends PerChatJsonStore { ChatWallpaper? get(int accountId, int chatId) => read(accountId, chatId); + Set get themeIds => { + for (final entry in allEntries) ?entry.value.themeId, + }; + + ChatWallpaper? effective(int accountId, int chatId) { + final own = get(accountId, chatId); + if (own != null) return own.isNone ? null : own; + if (chatId == kGlobalWallpaperChatId) return null; + final global = get(accountId, kGlobalWallpaperChatId); + return global == null || global.isNone ? null : global; + } + // #***! картинку копируем к себе, исходник из галереи может исчезнуть Future setImage( int accountId, @@ -199,6 +226,9 @@ class ChatWallpaperStore extends PerChatJsonStore { return wallpaper; } + Future setNone(int accountId, int chatId) => + write(accountId, chatId, const ChatWallpaper.none()); + Future clear(int accountId, int chatId) => write(accountId, chatId, null); diff --git a/lib/core/storage/ghost_read_store.dart b/lib/core/storage/ghost_read_store.dart index 69bdd1c7..b03b9f07 100644 --- a/lib/core/storage/ghost_read_store.dart +++ b/lib/core/storage/ghost_read_store.dart @@ -2,10 +2,31 @@ import 'per_chat_json_store.dart'; class GhostRead { final int mark; - final int unread; - final int ownMark; + final int serverUnread; + final int serverOwnMark; + final int baseUnread; + final int left; - const GhostRead({required this.mark, required this.unread, required this.ownMark}); + const GhostRead({ + required this.mark, + required this.serverUnread, + required this.serverOwnMark, + required this.baseUnread, + required this.left, + }); + + int unreadFor(int serverUnread, {int? lastMessageTime}) { + if (lastMessageTime != null && lastMessageTime <= mark) return 0; + return (serverUnread - baseUnread + left).clamp(0, serverUnread); + } + + GhostRead withServer({int? unread, int? ownMark}) => GhostRead( + mark: mark, + serverUnread: unread ?? serverUnread, + serverOwnMark: ownMark ?? serverOwnMark, + baseUnread: baseUnread, + left: left, + ); } class GhostReadStore extends PerChatJsonStore { @@ -15,8 +36,10 @@ class GhostReadStore extends PerChatJsonStore { fromJson: _fromJson, toJson: (value) => { 'mark': value.mark, - 'unread': value.unread, - 'ownMark': value.ownMark, + 'unread': value.serverUnread, + 'ownMark': value.serverOwnMark, + 'base': value.baseUnread, + 'left': value.left, }, ); @@ -28,28 +51,64 @@ class GhostReadStore extends PerChatJsonStore { final unread = raw['unread']; final ownMark = raw['ownMark']; if (mark is! int || unread is! int || ownMark is! int) return null; - return GhostRead(mark: mark, unread: unread, ownMark: ownMark); + final base = raw['base']; + final left = raw['left']; + return GhostRead( + mark: mark, + serverUnread: unread, + serverOwnMark: ownMark, + baseUnread: base is int ? base : unread, + left: left is int ? left : 0, + ); } - Future remember( + GhostRead? of(int accountId, int chatId) => read(accountId, chatId); + + Future noteLocalRead( int accountId, int chatId, { required int mark, - required int unread, - required int ownMark, + required int left, + required int serverUnread, + required int serverOwnMark, }) { final prev = read(accountId, chatId); + final known = prev?.serverUnread ?? serverUnread; return write( accountId, chatId, GhostRead( - mark: mark, - unread: prev?.unread ?? unread, - ownMark: prev?.ownMark ?? ownMark, + mark: prev == null || mark > prev.mark ? mark : prev.mark, + serverUnread: known, + serverOwnMark: prev?.serverOwnMark ?? serverOwnMark, + baseUnread: known, + left: left, ), ); } + Future noteServer( + int accountId, + int chatId, { + int? unread, + int? ownMark, + }) { + final prev = read(accountId, chatId); + if (prev == null) return Future.value(); + if ((unread == null || unread == prev.serverUnread) && + (ownMark == null || ownMark == prev.serverOwnMark)) { + return Future.value(); + } + return write( + accountId, + chatId, + prev.withServer(unread: unread, ownMark: ownMark), + ); + } + + Future forget(int accountId, int chatId) => + write(accountId, chatId, null); + List<({int accountId, int chatId, GhostRead read})> snapshot() { final out = <({int accountId, int chatId, GhostRead read})>[]; for (final entry in allEntries) { diff --git a/lib/core/transport/network_core.dart b/lib/core/transport/network_core.dart new file mode 100644 index 00000000..5a8b785d --- /dev/null +++ b/lib/core/transport/network_core.dart @@ -0,0 +1,27 @@ +import 'package:flutter/foundation.dart'; +import 'package:kolibri/kolibri.dart' show setDnsCachePath; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import '../storage/app_instance.dart'; +import '../utils/logger.dart'; +import 'tls_config.dart'; + +abstract final class NetworkCore { + static Future configure() async { + await TlsConfig.applyMincifryTrust(); + await _keepWorkingAddresses(); + } + + static Future _keepWorkingAddresses() async { + if (kIsWeb) return; + try { + final dir = await getApplicationSupportDirectory(); + setDnsCachePath( + path: p.join(dir.path, 'kolibri_dns${AppInstance.suffix}.cache'), + ); + } catch (e) { + logger.w('[net] адреса серверов не переживут перезапуск: $e'); + } + } +} diff --git a/lib/core/utils/debug_session_log.dart b/lib/core/utils/debug_session_log.dart index 066cec60..73514613 100644 --- a/lib/core/utils/debug_session_log.dart +++ b/lib/core/utils/debug_session_log.dart @@ -55,37 +55,6 @@ class _LogEntry { bool get pending => responseTime == null && error == null; - Map requestRecord() => { - 'k': 'q', - 'op': opcode, - 'seq': seq, - 't': requestTime.toIso8601String(), - 'p': request, - }; - - Map responseRecord() => { - 'k': 'r', - 'seq': seq, - 'cmd': cmd, - 't': responseTime?.toIso8601String(), - 'p': response, - }; - - Map errorRecord() => { - 'k': 'e', - 'seq': seq, - 't': responseTime?.toIso8601String(), - 'err': error, - }; - - List> records() => [ - requestRecord(), - if (error != null) - errorRecord() - else if (responseTime != null) - responseRecord(), - ]; - static _LogEntry fromRequestRecord(Map record) => _LogEntry( opcode: (record['op'] as num?)?.toInt() ?? 0, seq: (record['seq'] as num?)?.toInt() ?? 0, @@ -109,6 +78,16 @@ class _LogEntry { DateTime.fromMillisecondsSinceEpoch(0); } +class _LiveEntry { + _LiveEntry(this.seq, this.requestLine); + + final int seq; + final String requestLine; + String? outcomeLine; + + bool get pending => outcomeLine == null; +} + _LogEntry? _lastPending(List<_LogEntry> entries, int seq) { for (var i = entries.length - 1; i >= 0; i--) { final entry = entries[i]; @@ -232,14 +211,14 @@ class DebugSessionLog { Directory? _dir; File? _currentFile; DateTime? _currentStart; - final List<_LogEntry> _entries = []; - final List _logLines = []; - final List> _pending = []; + final List<_LiveEntry> _entries = []; + final List _logRecords = []; + final List _pending = []; bool _truncated = false; bool _logsTruncated = false; bool _initialized = false; bool _compact = false; - int _writtenChars = 0; + int _appendedSinceCompact = 0; Future _writes = Future.value(); Timer? _flushTimer; @@ -278,50 +257,72 @@ class DebugSessionLog { void recordLogLine(String line) { final clean = _redactWireLine(line.replaceAll(_ansiEscape, '')); - _logLines.add(clean); - if (_logLines.length > _maxLogLinesPerSession) { - _logLines.removeRange(0, _logLines.length - _maxLogLinesPerSession); + final record = _encodeRecord({'k': 'l', 'v': clean}); + _logRecords.add(record); + if (_logRecords.length > _maxLogLinesPerSession) { + _logRecords.removeRange(0, _logRecords.length - _maxLogLinesPerSession); _logsTruncated = true; } - _append({'k': 'l', 'v': clean}); + _append(record); } // #***! исходящий запрос, payload чистим от секретов void recordRequest(int opcode, int seq, dynamic payload) { - final entry = _LogEntry( - opcode: opcode, - seq: seq, - requestTime: DateTime.now(), - request: redactForLog(payload), + final entry = _LiveEntry( + seq, + _encodeRecord({ + 'k': 'q', + 'op': opcode, + 'seq': seq, + 't': DateTime.now().toIso8601String(), + 'p': redactForLog(payload), + }), ); _entries.add(entry); if (_entries.length > _maxEntriesPerSession) { _entries.removeRange(0, _entries.length - _maxEntriesPerSession); _truncated = true; } - _append(entry.requestRecord()); + _append(entry.requestLine); } // #***! ответ подшиваем к запросу по seq void recordResponse(int seq, int cmd, dynamic payload) { - final entry = _lastPending(_entries, seq); - if (entry == null) return; - entry.responseTime = DateTime.now(); - entry.cmd = cmd; - entry.response = redactForLog(payload); - _append(entry.responseRecord()); + _settle(seq, { + 'k': 'r', + 'seq': seq, + 'cmd': cmd, + 't': DateTime.now().toIso8601String(), + 'p': redactForLog(payload), + }); } // #***! ошибку тоже подшиваем void recordError(int seq, Object error) { - final entry = _lastPending(_entries, seq); + _settle(seq, { + 'k': 'e', + 'seq': seq, + 't': DateTime.now().toIso8601String(), + 'err': error.toString(), + }); + } + + void _settle(int seq, Map record) { + _LiveEntry? entry; + for (var i = _entries.length - 1; i >= 0; i--) { + final candidate = _entries[i]; + if (candidate.seq == seq && candidate.pending) { + entry = candidate; + break; + } + } if (entry == null) return; - entry.responseTime = DateTime.now(); - entry.error = error.toString(); - _append(entry.errorRecord()); + final line = _encodeRecord(record); + entry.outcomeLine = line; + _append(line); } - void _append(Map record) { + void _append(String record) { _pending.add(record); if (_pending.length > _maxPendingRecords) { _pending.clear(); @@ -347,31 +348,36 @@ class DebugSessionLog { Future _writePending() async { final file = _currentFile; if (file == null) return; - final compact = _compact || _writtenChars > _compactAfterChars; + final compact = _compact || _appendedSinceCompact > _compactAfterChars; if (!compact && _pending.isEmpty) return; - final records = compact ? _snapshotRecords() : List.of(_pending); + final records = compact ? _snapshotLines() : List.of(_pending); _pending.clear(); _compact = false; final buffer = StringBuffer(); - for (final record in records) { - buffer.writeln(_encodeRecord(record)); - } + records.forEach(buffer.writeln); final data = buffer.toString(); try { await file.writeAsString( data, mode: compact ? FileMode.write : FileMode.append, ); - _writtenChars = compact ? data.length : _writtenChars + data.length; + _appendedSinceCompact = compact ? 0 : _appendedSinceCompact + data.length; } catch (_) { _compact = true; } } - List> _snapshotRecords() => [ - {'k': 's', 'truncated': _truncated, 'logsTruncated': _logsTruncated}, - for (final entry in _entries) ...entry.records(), - for (final line in _logLines) {'k': 'l', 'v': line}, + List _snapshotLines() => [ + _encodeRecord({ + 'k': 's', + 'truncated': _truncated, + 'logsTruncated': _logsTruncated, + }), + for (final entry in _entries) ...[ + entry.requestLine, + ?entry.outcomeLine, + ], + ..._logRecords, ]; static String _encodeRecord(Map record) { @@ -477,12 +483,9 @@ class DebugSessionLog { } } sessions.add( - _SessionData( - startedAt: _currentStart ?? DateTime.now(), - entries: List.of(_entries), - truncated: _truncated, - logLines: List.of(_logLines), - logsTruncated: _logsTruncated, + _SessionData.fromRecords( + _currentStart ?? DateTime.now(), + _snapshotLines().join('\n'), ), ); sessions.sort((a, b) => a.startedAt.compareTo(b.startedAt)); diff --git a/lib/core/utils/download_history.dart b/lib/core/utils/download_history.dart index b6a2948a..117141ca 100644 --- a/lib/core/utils/download_history.dart +++ b/lib/core/utils/download_history.dart @@ -301,6 +301,8 @@ class DownloadHistory { for (final file in files) { final cacheName = p.basename(file.path); if (cacheName.startsWith('avatar_') || + cacheName.startsWith('audioart_') || + cacheName.startsWith('audiometa_') || cacheName.startsWith('decrypted_') || cacheName.startsWith(MediaCache.keptPrefix) || cacheName.startsWith('download_thumb_')) { diff --git a/lib/core/utils/format.dart b/lib/core/utils/format.dart index 68a8bbd5..4313b94d 100644 --- a/lib/core/utils/format.dart +++ b/lib/core/utils/format.dart @@ -87,6 +87,23 @@ String formatBytes(AppLocalizations l10n, int bytes) { return l10n.formatBytesGb((bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)); } +String formatCompactCount(int count) { + if (count < 1000) return '$count'; + const units = ['K', 'M', 'B']; + var scaled = count / 1000; + var unit = 0; + while (unit < units.length - 1 && (scaled * 10).round() >= 10000) { + scaled /= 1000; + unit++; + } + final tenths = (scaled * 10).round(); + final fraction = tenths % 10; + final whole = tenths ~/ 10; + return fraction == 0 + ? '$whole${units[unit]}' + : '$whole,$fraction${units[unit]}'; +} + // #***! дальше время и даты в разных видах String formatDurationMmSs(Duration d, {bool padMinutes = false}) { final m = d.inMinutes; @@ -133,6 +150,23 @@ String formatDateWords(AppLocalizations l10n, DateTime dt) => String formatDateNumeric(DateTime dt) => '${pad2(dt.day)}.${pad2(dt.month)}.${dt.year}'; +String formatChatListStamp( + AppLocalizations l10n, + DateTime dt, { + DateTime? now, +}) { + final today = now ?? DateTime.now(); + final daysAgo = DateTime.utc( + today.year, + today.month, + today.day, + ).difference(DateTime.utc(dt.year, dt.month, dt.day)).inDays; + if (daysAgo <= 0) return formatClock(dt); + if (daysAgo < 7) return formatWeekdayShort(l10n, dt.weekday); + if (dt.year == today.year) return formatDayMonth(l10n, dt); + return formatDateNumeric(dt); +} + String formatDateTimeNumeric(DateTime dt) => '${formatDateNumeric(dt)} ${formatClock(dt)}'; diff --git a/lib/core/utils/media_cache.dart b/lib/core/utils/media_cache.dart index a89b5a9f..8845598c 100644 --- a/lib/core/utils/media_cache.dart +++ b/lib/core/utils/media_cache.dart @@ -5,7 +5,8 @@ import 'package:flutter/foundation.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; -import '../config/app_media_cache.dart'; +import '../cache/cache_janitor.dart'; +import '../config/app_cache_limit.dart'; import 'logger.dart'; import '../storage/app_instance.dart'; @@ -15,9 +16,9 @@ import '../storage/app_instance.dart'; /// Хранит файлы в `/media_cache/` под детерминированным именем /// (обычно по id вложения), чтобы повторные открытия не качали заново. class MediaCache { - /// Максимальный размер кэша (настраивается в дев-меню); при превышении - /// вытесняются старые файлы (LRU), кроме закреплённых. - static int get maxBytes => AppMediaCacheLimit.current.value; + /// Общий лимит кэша из настроек памяти: файл крупнее него не скачиваем, + /// а вытеснение старых файлов (LRU) ведёт [CacheJanitor]. + static int get maxBytes => AppCacheLimit.current.value; static const String keptPrefix = 'keep_'; static const int maxSingleFileBytes = 128 * 1024 * 1024; @@ -31,9 +32,7 @@ class MediaCache { return next; } - // #***! размер держим в памяти, каталог не пересканируем static Directory? _dir; - static int? _cachedSize; static final Map> _inFlight = {}; static final Set _present = {}; static final Map> _presence = {}; @@ -43,7 +42,6 @@ class MediaCache { _generation++; _mutations = Future.value(); _dir = null; - _cachedSize = null; _inFlight.clear(); _present.clear(); for (final notifier in _presence.values) { @@ -95,7 +93,6 @@ class MediaCache { } final target = await part.rename((await fileFor(pinned)).path); _markPresent(pinned, true); - _cachedSize = null; return target; }); } finally { @@ -115,6 +112,27 @@ class MediaCache { return File(p.join(dir.path, _sanitize(name))); } + static Future directoryPath() async => (await _cacheDir()).path; + + static Future remove(Iterable names) => _mutate(() async { + final dir = await _cacheDir(); + var freed = 0; + for (final name in names) { + if (_isInFlight(name)) continue; + final file = File(p.join(dir.path, name)); + try { + final size = await file.length(); + await file.delete(); + freed += size; + _markAbsentByBasename(name); + } catch (_) {} + } + return freed; + }); + + static bool _isInFlight(String name) => + _inFlight.keys.any((key) => _sanitize(key) == name); + static Future> files() async { final dir = await _cacheDir(); final files = []; @@ -150,7 +168,6 @@ class MediaCache { logger.w('[cache] не удалил $name: $e'); } _markPresent(name, false); - _cachedSize = null; }); // #***! скачивание с защитой от параллельных запросов @@ -164,6 +181,7 @@ class MediaCache { String url, { void Function(double progress)? onProgress, int? maxBytes, + Map headers = const {}, }) async { name = _sanitize(name); final existingFile = await existing(name); @@ -172,7 +190,7 @@ class MediaCache { final running = _inFlight[name]; if (running != null) return running; - final future = _download(name, url, onProgress, maxBytes); + final future = _download(name, url, onProgress, maxBytes, headers); _inFlight[name] = future; try { return await future; @@ -187,6 +205,7 @@ class MediaCache { String url, void Function(double progress)? onProgress, int? maxBytes, + Map headers, ) async { final generation = _generation; final file = await fileFor(name); @@ -205,6 +224,7 @@ class MediaCache { final request = await client .getUrl(Uri.parse(url)) .timeout(const Duration(seconds: 15)); + headers.forEach(request.headers.set); final response = await request.close().timeout( const Duration(seconds: 30), ); @@ -250,8 +270,9 @@ class MediaCache { } await part.rename(file.path); _markPresent(name, true); - _cachedSize = null; - await _enforceLimit(protectedName: _sanitize(name)); + if (!pinned) { + CacheJanitor.instance.noteWrite(CacheStore.media, received); + } return await file.exists() ? file : null; }); } catch (_) { @@ -276,32 +297,6 @@ class MediaCache { } } - // #***! размер считаем инкрементально - /// Суммарный размер кэша в байтах. - /// - /// Результат держится в памяти и поддерживается инкрементально при - /// загрузке/очистке/вытеснении — повторные вызовы не пересканируют каталог. - static Future currentSize() => _mutate(() async { - final cached = _cachedSize; - if (cached != null) return cached; - final total = await _scanSize(); - _cachedSize = total; - return total; - }); - - static Future _scanSize() async { - final dir = await _cacheDir(); - var total = 0; - await for (final entity in dir.list()) { - if (entity is File && !entity.path.endsWith('.part')) { - try { - total += await entity.length(); - } catch (_) {} - } - } - return total; - } - /// Полностью очищает кэш. Возвращает число удалённых байт. static Future clear() { _generation++; @@ -316,7 +311,6 @@ class MediaCache { } catch (_) {} } } - _cachedSize = 0; _present.clear(); for (final notifier in _presence.values) { notifier.value = false; @@ -325,11 +319,6 @@ class MediaCache { }); } - // #***! под лимитом выходим сразу, каталог обходим только при превышении - /// Вытесняет старые файлы (по mtime), пока размер превышает [maxBytes]. - /// - /// Под лимитом — ранний выход без сканирования каталога (частый случай). - /// Каталог обходится только когда лимит реально превышен. static Future _pinnedFits(String name, int incoming) async { var total = incoming; for (final file in await files()) { @@ -341,49 +330,6 @@ class MediaCache { return total <= maxPinnedBytes; } - static Future _enforceLimit({String? protectedName}) async { - final limit = maxBytes; - if (limit <= 0) return; - - var total = _cachedSize ?? await _scanSize(); - if (total <= limit) { - _cachedSize = total; - return; - } - - final dir = await _cacheDir(); - // #***! stat снимаем по разу на файл: в компараторе он звался бы - // синхронно и по два раза на сравнение, то есть тысячи блокирующих - // сисколлов на изоляте интерфейса - final entries = <({File file, DateTime modified, int size})>[]; - await for (final entity in dir.list()) { - if (entity is! File || entity.path.endsWith('.part')) continue; - final name = p.basename(entity.path); - if (name == protectedName || - name.startsWith(keptPrefix) || - _inFlight.keys.any((key) => _sanitize(key) == name)) { - continue; - } - try { - final stat = await entity.stat(); - entries.add((file: entity, modified: stat.modified, size: stat.size)); - } catch (_) {} - } - - // #***! сортируем по времени доступа и удаляем старое - entries.sort((a, b) => a.modified.compareTo(b.modified)); - - for (final entry in entries) { - if (total <= limit) break; - try { - await entry.file.delete(); - total -= entry.size; - _markAbsentByBasename(p.basename(entry.file.path)); - } catch (_) {} - } - _cachedSize = total; - } - // #***! флаг файл скачан для иконки в пузыре /// Реактивный флаг наличия файла [name] в кэше (для UI-иконки «скачано»). static ValueListenable presence(String name) { diff --git a/lib/core/utils/media_cache_names.dart b/lib/core/utils/media_cache_names.dart index 6e8923e2..34cf6858 100644 --- a/lib/core/utils/media_cache_names.dart +++ b/lib/core/utils/media_cache_names.dart @@ -1,7 +1,39 @@ import '../../models/attachment.dart'; +import 'media_cache.dart'; + +enum MediaCacheKind { photo, video, voice, file, kept } + +const List _photoPrefixes = ['photo_', 'avatar_', 'audioart_']; +const List _videoPrefixes = [ + 'video_', + 'videopreview_', + 'gif_', + 'story_', +]; +final RegExp _voiceName = RegExp(r'^-?\d+\.ogg$'); String photoCacheName(PhotoAttachment photo, String url) => 'photo_${photo.photoId ?? (url.hashCode & 0x7fffffff)}.jpg'; +String avatarCacheName(String url) => 'avatar_${url.hashCode & 0x7fffffff}.jpg'; + String videoCacheName(VideoAttachment video, String messageId) => 'video_${video.videoId ?? messageId}.mp4'; + +String videoPreviewCacheName(int? videoId) => 'videopreview_$videoId.mp4'; + +String gifCacheName(int photoId) => 'gif_$photoId.mp4'; + +String storyVideoCacheName(int ownerId, int storyId) => + 'story_${ownerId}_$storyId.mp4'; + +String voiceCacheName({int? audioId, required String messageId}) => + '${audioId ?? messageId}.ogg'; + +MediaCacheKind mediaCacheKindOf(String name) { + if (name.startsWith(MediaCache.keptPrefix)) return MediaCacheKind.kept; + if (_photoPrefixes.any(name.startsWith)) return MediaCacheKind.photo; + if (_videoPrefixes.any(name.startsWith)) return MediaCacheKind.video; + if (_voiceName.hasMatch(name)) return MediaCacheKind.voice; + return MediaCacheKind.file; +} diff --git a/lib/core/utils/media_saver.dart b/lib/core/utils/media_saver.dart index 731bd500..7d77f5c9 100644 --- a/lib/core/utils/media_saver.dart +++ b/lib/core/utils/media_saver.dart @@ -15,6 +15,7 @@ import 'format.dart'; import 'image_format.dart'; import 'media_cache.dart'; import 'save_file_as.dart'; +import 'media_cache_names.dart'; enum MediaSaveFailure { noLink, @@ -56,7 +57,7 @@ Future saveImageFromUrl(String url) async { return const MediaSaveResult(ok: false, failure: MediaSaveFailure.noLink); } try { - final cacheName = 'avatar_${url.hashCode & 0x7fffffff}.jpg'; + final cacheName = avatarCacheName(url); final file = await MediaCache.getOrDownload(cacheName, url); if (file == null) { return const MediaSaveResult( diff --git a/lib/core/utils/tiled_svg.dart b/lib/core/utils/tiled_svg.dart deleted file mode 100644 index 21cf1043..00000000 --- a/lib/core/utils/tiled_svg.dart +++ /dev/null @@ -1,140 +0,0 @@ -import 'dart:ui' as ui; - -import 'package:flutter/material.dart'; -import 'package:flutter_svg/flutter_svg.dart'; - -// #***! плиточный SVG узор для обоев -class TiledSvgPattern extends StatefulWidget { - final String asset; - final Color color; - final double opacity; - final double tileSize; - - const TiledSvgPattern({ - super.key, - required this.asset, - required this.color, - this.opacity = 0.12, - this.tileSize = 120, - }); - - @override - State createState() => _TiledSvgPatternState(); -} - -class _TiledSvgPatternState extends State { - // #***! растр кэшируем по путь@размер, рисовать SVG на каждый кадр дорого - static final Map _cache = {}; - static final Map> _pending = {}; - - ui.Image? _image; - double _dpr = 1; - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - final dpr = MediaQuery.maybeOf(context)?.devicePixelRatio ?? 1; - if (dpr != _dpr || _image == null) { - _dpr = dpr; - _resolve(); - } - } - - @override - void didUpdateWidget(TiledSvgPattern old) { - super.didUpdateWidget(old); - if (old.asset != widget.asset || old.tileSize != widget.tileSize) { - _resolve(); - } - } - - // #***! сменилась плотность экрана, растеризуем заново - Future _resolve() async { - final px = (widget.tileSize * _dpr).clamp(1, 4096).round(); - final key = '${widget.asset}@$px'; - final cached = _cache[key]; - if (cached != null) { - if (_image != cached) setState(() => _image = cached); - return; - } - // #***! _pending схлопывает параллельные растеризации одной плитки - final future = _pending.putIfAbsent(key, () => _rasterize(widget.asset, px)); - try { - final image = await future; - _cache[key] = image; - _pending.remove(key); - if (mounted) setState(() => _image = image); - } catch (_) { - _pending.remove(key); - } - } - - // #***! SVG в картинку нужного размера - static Future _rasterize(String asset, int px) async { - final info = await vg.loadPicture(SvgAssetLoader(asset), null); - final recorder = ui.PictureRecorder(); - final canvas = Canvas(recorder); - final size = info.size; - if (size.width > 0 && size.height > 0) { - canvas.scale(px / size.width, px / size.height); - } - canvas.drawPicture(info.picture); - final picture = recorder.endRecording(); - final image = await picture.toImage(px, px); - info.picture.dispose(); - picture.dispose(); - return image; - } - - @override - Widget build(BuildContext context) { - final image = _image; - if (image == null) return const SizedBox.expand(); - return CustomPaint( - size: Size.infinite, - painter: _PatternPainter( - image: image, - color: widget.color.withValues(alpha: widget.opacity), - tileSize: widget.tileSize, - dpr: _dpr, - ), - ); - } -} - -// #***! плитка размножается шейдером и красится темой -class _PatternPainter extends CustomPainter { - final ui.Image image; - final Color color; - final double tileSize; - final double dpr; - - const _PatternPainter({ - required this.image, - required this.color, - required this.tileSize, - required this.dpr, - }); - - @override - void paint(Canvas canvas, Size size) { - final s = 1 / dpr; - final matrix = Matrix4.identity()..scaleByDouble(s, s, 1, 1); - final paint = Paint() - ..shader = ImageShader( - image, - TileMode.repeated, - TileMode.repeated, - matrix.storage, - ) - ..colorFilter = ColorFilter.mode(color, BlendMode.srcIn); - canvas.drawRect(Offset.zero & size, paint); - } - - @override - bool shouldRepaint(_PatternPainter old) => - old.image != image || - old.color != color || - old.tileSize != tileSize || - old.dpr != dpr; -} diff --git a/lib/core/utils/wallpaper_seed.dart b/lib/core/utils/wallpaper_seed.dart index c5ed8174..194a759d 100644 --- a/lib/core/utils/wallpaper_seed.dart +++ b/lib/core/utils/wallpaper_seed.dart @@ -16,9 +16,7 @@ Future computeWallpaperSeed(ChatWallpaper? wallpaper) async { return _mostVivid(colors); } if (!wallpaper.isImage) { - final theme = chatWallpaperThemeById(wallpaper.themeId); - if (theme == null) return null; - return _mostVivid(theme.colors); + return chatWallpaperThemeById(wallpaper.themeId)?.accent; } final path = wallpaper.imagePath; if (path == null) return null; diff --git a/lib/core/whats_new/spotlight_ids.dart b/lib/core/whats_new/spotlight_ids.dart new file mode 100644 index 00000000..ec258f9a --- /dev/null +++ b/lib/core/whats_new/spotlight_ids.dart @@ -0,0 +1,60 @@ +abstract final class SpotlightIds { + static const String navChats = 'nav.chats'; + static const String navCalls = 'nav.calls'; + static const String navContacts = 'nav.contacts'; + static const String navSettings = 'nav.settings'; + + static const String settingsCustomization = 'settings.customization'; + static const String settingsTheme = 'settings.theme'; + static const String settingsAppearance = 'settings.appearance'; + static const String settingsChatBackground = 'settings.chat-background'; + static const String settingsFont = 'settings.font'; + static const String settingsAppIcon = 'settings.app-icon'; + static const String settingsChats = 'settings.chats'; + static const String settingsNotifications = 'settings.notifications'; + static const String settingsLanguage = 'settings.language'; + static const String settingsMediaDevices = 'settings.media-devices'; + static const String settingsStorage = 'settings.storage'; + static const String settingsCloud = 'settings.cloud'; + static const String settingsProxy = 'settings.proxy'; + static const String settingsSpoof = 'settings.spoof'; + static const String settingsSecurity = 'settings.security'; + static const String settingsDevices = 'settings.devices'; + static const String settingsKomet = 'settings.komet'; + + static const String appearanceAnimations = 'appearance.animations'; + + static const String storageUsage = 'storage.usage'; + static const String storageLimit = 'storage.limit'; + + static const Set tappable = { + navChats, + navCalls, + navContacts, + navSettings, + settingsCustomization, + settingsTheme, + settingsAppearance, + settingsChatBackground, + settingsFont, + settingsAppIcon, + settingsChats, + settingsNotifications, + settingsLanguage, + settingsMediaDevices, + settingsStorage, + settingsCloud, + settingsProxy, + settingsSpoof, + settingsSecurity, + settingsDevices, + settingsKomet, + }; + + static const Set all = { + ...tappable, + appearanceAnimations, + storageUsage, + storageLimit, + }; +} diff --git a/lib/core/whats_new/whats_new_document.dart b/lib/core/whats_new/whats_new_document.dart new file mode 100644 index 00000000..bcb21d02 --- /dev/null +++ b/lib/core/whats_new/whats_new_document.dart @@ -0,0 +1,344 @@ +import '../links/max_link.dart'; +import 'spotlight_ids.dart'; + +enum WhatsNewTab { chats, calls, contacts, settings } + +enum WhatsNewCommand { + close, + tab, + open, + check, + back, + scroll, + highlight, + tap, + hint, + notify, + wait, + run, +} + +class WhatsNewTarget { + const WhatsNewTarget.scenario(String this.scenario) : link = null; + const WhatsNewTarget.link(String this.link) : scenario = null; + + final String? scenario; + final String? link; + + static final RegExp _name = RegExp(r'^[\w.-]+$'); + + static WhatsNewTarget? parse(String raw) { + final value = raw.trim(); + if (value.startsWith('#')) { + final name = value.substring(1); + return _name.hasMatch(name) ? WhatsNewTarget.scenario(name) : null; + } + final link = value.startsWith(':') ? 'https://max.ru/$value' : value; + if (MaxLink.parse(link) != null) return WhatsNewTarget.link(link); + final uri = Uri.tryParse(link); + if (uri != null && uri.scheme == 'https' && uri.host.isNotEmpty) { + return WhatsNewTarget.link(link); + } + return null; + } +} + +sealed class WhatsNewSpan { + const WhatsNewSpan(this.text); + + final String text; +} + +final class WhatsNewPlainSpan extends WhatsNewSpan { + const WhatsNewPlainSpan(super.text); +} + +final class WhatsNewLinkSpan extends WhatsNewSpan { + const WhatsNewLinkSpan(super.text, this.target); + + final WhatsNewTarget target; +} + +class WhatsNewNote { + const WhatsNewNote(this.spans, {this.target}); + + final List spans; + final WhatsNewTarget? target; + + String get text => spans.map((span) => span.text).join(); +} + +class WhatsNewStep { + const WhatsNewStep(this.command, this.args); + + final WhatsNewCommand command; + final List args; +} + +class WhatsNewDocument { + const WhatsNewDocument._(this.notes, this.scenarios, this.problems); + + static const WhatsNewDocument empty = WhatsNewDocument._([], {}, []); + + final List notes; + final Map> scenarios; + final List problems; + + String get plainText => notes.map((note) => note.text).join('\n'); + + factory WhatsNewDocument.parse(String source) => _Parser(source).parse(); +} + +class _Parser { + _Parser(this.source); + + static final RegExp _header = RegExp(r'^#([\w.-]+)\s*$'); + static final RegExp _wholeLine = RegExp(r'^(.*\S)\s+→\s+(\S+)$'); + static final RegExp _inline = RegExp(r'\[([^\]]+)\]\(([^)\s]+)\)'); + + final String source; + final List _notes = []; + final Map> _scenarios = {}; + final List _problems = []; + final List<(String, int)> _scenarioRefs = []; + final Map> _runs = {}; + + WhatsNewDocument parse() { + String? scenario; + final lines = source.split('\n'); + for (var i = 0; i < lines.length; i++) { + final number = i + 1; + final line = lines[i].replaceAll('\r', '').trimRight(); + final trimmed = line.trimLeft(); + if (trimmed.isEmpty || trimmed.startsWith('//')) continue; + + final header = _header.firstMatch(line); + if (header != null) { + final name = header.group(1)!; + if (_scenarios.containsKey(name)) { + _problem(number, 'сценарий #$name объявлен второй раз'); + } + _scenarios[name] = []; + scenario = name; + continue; + } + + if (line.length != trimmed.length) { + if (scenario == null) { + _problem(number, 'шаг с отступом стоит вне сценария'); + continue; + } + final step = _step(trimmed, number, scenario); + if (step != null) _scenarios[scenario]!.add(step); + continue; + } + + scenario = null; + _notes.add(_note(line, number)); + } + + for (final (name, number) in _scenarioRefs) { + if (!_scenarios.containsKey(name)) { + _problem(number, 'нет сценария #$name'); + } + } + _checkCycles(); + return WhatsNewDocument._(_notes, _scenarios, _problems); + } + + WhatsNewNote _note(String line, int number) { + var body = line; + WhatsNewTarget? whole; + final arrow = _wholeLine.firstMatch(line); + if (arrow != null) { + whole = _target(arrow.group(2)!, number); + if (whole != null) body = arrow.group(1)!; + } + + final spans = []; + var cursor = 0; + for (final match in _inline.allMatches(body)) { + if (match.start > cursor) { + spans.add(WhatsNewPlainSpan(body.substring(cursor, match.start))); + } + final words = match.group(1)!; + final target = _target(match.group(2)!, number); + spans.add( + target == null + ? WhatsNewPlainSpan(words) + : WhatsNewLinkSpan(words, target), + ); + cursor = match.end; + } + if (cursor < body.length) { + spans.add(WhatsNewPlainSpan(body.substring(cursor))); + } + return WhatsNewNote(spans, target: whole); + } + + WhatsNewTarget? _target(String raw, int number) { + final target = WhatsNewTarget.parse(raw); + if (target == null) { + _problem(number, 'не понимаю ссылку «$raw»'); + return null; + } + _refer(target, number); + return target; + } + + void _refer(WhatsNewTarget target, int number) { + final scenario = target.scenario; + if (scenario != null) _scenarioRefs.add((scenario, number)); + } + + WhatsNewStep? _step(String text, int number, String scenario) { + final tokens = _tokens(text); + if (tokens == null) { + _problem(number, 'не закрыта кавычка'); + return null; + } + final command = WhatsNewCommand.values.asNameMap()[tokens.first]; + if (command == null) { + _problem(number, 'неизвестная команда «${tokens.first}»'); + return null; + } + final args = tokens.sublist(1); + final error = _check(command, args, number, scenario); + if (error != null) { + _problem(number, error); + return null; + } + return WhatsNewStep(command, args); + } + + String? _check( + WhatsNewCommand command, + List args, + int number, + String scenario, + ) { + switch (command) { + case WhatsNewCommand.close: + case WhatsNewCommand.back: + return args.isEmpty ? null : '«${command.name}» без аргументов'; + case WhatsNewCommand.tab: + final known = WhatsNewTab.values.asNameMap(); + return args.length == 1 && known.containsKey(args.first) + ? null + : 'tab chats | calls | contacts | settings'; + case WhatsNewCommand.open: + if (args.length != 1) return 'open <ссылка>'; + final target = WhatsNewTarget.parse(args.first); + return target?.link == null + ? 'open ждёт ссылку, а не «${args.first}»' + : null; + case WhatsNewCommand.check: + if (args.length != 1) return 'check <ссылка>'; + return WhatsNewTarget.parse(args.first)?.link == null + ? 'check ждёт ссылку, а не «${args.first}»' + : null; + case WhatsNewCommand.scroll: + if (args.length != 1) return 'scroll top | bottom | <элемент>'; + final where = args.first; + if (where == 'top' || where == 'bottom') return null; + return _spotlight(where); + case WhatsNewCommand.tap: + if (args.length != 1) return 'tap <элемент>'; + return SpotlightIds.tappable.contains(args.first) + ? null + : '«${args.first}» нельзя нажать (см. SpotlightIds.tappable)'; + case WhatsNewCommand.highlight: + return args.length == 1 + ? _spotlight(args.first) + : 'highlight <элемент>'; + case WhatsNewCommand.hint: + return args.length == 2 + ? _spotlight(args.first) + : 'hint <элемент> "текст"'; + case WhatsNewCommand.notify: + if (args.length == 1) return null; + if (args.length != 3) return 'notify "текст" ["кнопка" #сценарий]'; + final target = WhatsNewTarget.parse(args[2]); + if (target == null) return 'не понимаю ссылку «${args[2]}»'; + _refer(target, number); + return null; + case WhatsNewCommand.wait: + final ms = args.length == 1 ? int.tryParse(args.first) : null; + return ms != null && ms >= 0 && ms <= 10000 + ? null + : 'wait <мс от 0 до 10000>'; + case WhatsNewCommand.run: + final target = args.length == 1 + ? WhatsNewTarget.parse(args.first) + : null; + final name = target?.scenario; + if (target == null || name == null) return 'run #сценарий'; + _refer(target, number); + _runs.putIfAbsent(scenario, () => []).add(name); + return null; + } + } + + String? _spotlight(String id) => SpotlightIds.all.contains(id) + ? null + : 'нет элемента «$id» (см. SpotlightIds)'; + + void _checkCycles() { + final done = {}; + final path = []; + void visit(String name) { + if (done.contains(name)) return; + if (path.contains(name)) { + _problems.add('сценарии зациклены: ${[...path, name].join(' → ')}'); + return; + } + path.add(name); + for (final next in _runs[name] ?? const []) { + visit(next); + } + path.removeLast(); + done.add(name); + } + + _runs.keys.forEach(visit); + } + + void _problem(int number, String message) => + _problems.add('строка $number: $message'); + + static List? _tokens(String text) { + final tokens = []; + final buffer = StringBuffer(); + var quoted = false; + var inToken = false; + for (var i = 0; i < text.length; i++) { + final char = text[i]; + if (quoted) { + if (char == r'\' && i + 1 < text.length) { + buffer.write(text[++i]); + } else if (char == '"') { + quoted = false; + } else { + buffer.write(char); + } + continue; + } + if (char == '"') { + quoted = true; + inToken = true; + } else if (char == ' ' || char == '\t') { + if (inToken) { + tokens.add(buffer.toString()); + buffer.clear(); + inToken = false; + } + } else { + buffer.write(char); + inToken = true; + } + } + if (quoted) return null; + if (inToken) tokens.add(buffer.toString()); + return tokens; + } +} diff --git a/lib/frontend/debug/cache_section.dart b/lib/frontend/debug/cache_section.dart deleted file mode 100644 index 49fb14d4..00000000 --- a/lib/frontend/debug/cache_section.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:material_symbols_icons/symbols.dart'; - -import '../../core/utils/format.dart'; -import '../../l10n/app_localizations.dart'; -import '../widgets/small_spinner.dart'; -import 'dev_menu_widgets.dart'; - -class DebugCacheSection extends StatelessWidget { - final int cacheSize; - final bool clearingCache; - final String cacheLimitLabel; - final VoidCallback onPickCacheLimit; - final VoidCallback onClearCache; - - const DebugCacheSection({ - super.key, - required this.cacheSize, - required this.clearingCache, - required this.cacheLimitLabel, - required this.onPickCacheLimit, - required this.onClearCache, - }); - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - final l10n = AppLocalizations.of(context)!; - return DevGroup( - children: [ - DevRow( - caption: 'Лимит кэша медиа', - title: cacheLimitLabel, - onTap: onPickCacheLimit, - trailing: Icon(Symbols.chevron_right, color: cs.outline, size: 20), - ), - DevRow( - caption: clearingCache - ? 'Очистка…' - : 'Занято: ${formatBytes(l10n, cacheSize)}', - title: 'Очистить кэш медиа', - onTap: clearingCache ? null : onClearCache, - trailing: clearingCache - ? SmallSpinner(size: 20, color: cs.onSurfaceVariant) - : null, - ), - ], - ); - } -} diff --git a/lib/frontend/debug/feature_toggles_section.dart b/lib/frontend/debug/feature_toggles_section.dart index e881c4bf..bf2649c8 100644 --- a/lib/frontend/debug/feature_toggles_section.dart +++ b/lib/frontend/debug/feature_toggles_section.dart @@ -11,6 +11,7 @@ import '../../core/config/app_stories.dart'; import '../../core/config/app_swipe_back_desktop.dart'; import '../../core/config/app_unchecked_links.dart'; import '../../core/config/app_video_note_quality.dart'; +import '../../core/config/komet_settings.dart'; import '../../core/contacts/device_contacts_service.dart'; import '../screens/digital_id/digital_id_web_screen.dart'; import '../widgets/custom_notification.dart'; @@ -62,6 +63,14 @@ class DebugFeatureTogglesSection extends StatelessWidget { valueListenable: AppStories.current, onChanged: AppStories.save, ), + DevToggleRow( + title: 'Снег', + description: (_) => + 'Принудительно показывает снег вне периода ' + 'с 1 декабря по 3 января', + valueListenable: KometSettings.debugSnow, + onChanged: KometSettings.setDebugSnow, + ), DevToggleRow( title: 'Команды', description: (_) => 'Панель команд по вводу «/»', diff --git a/lib/frontend/debug/id_search_section.dart b/lib/frontend/debug/id_search_section.dart index 672b12e9..38d169f8 100644 --- a/lib/frontend/debug/id_search_section.dart +++ b/lib/frontend/debug/id_search_section.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:material_symbols_icons/symbols.dart'; +import '../widgets/alert_note.dart'; import '../widgets/hint_bubble.dart'; import '../widgets/glossy_pill.dart'; import '../widgets/small_spinner.dart'; @@ -401,28 +402,6 @@ class _ErrorChip extends StatelessWidget { @override Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - return Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: cs.errorContainer.withValues(alpha: 0.5), - borderRadius: BorderRadius.circular(10), - ), - child: Row( - children: [ - Icon(Symbols.error_outline, size: 16, color: cs.onErrorContainer), - const SizedBox(width: 8), - Expanded( - child: Text( - '$label: $message', - style: TextStyle(color: cs.onErrorContainer, fontSize: 12), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ), - ), - ], - ), - ); + return AlertNote('$label: $message'); } } diff --git a/lib/frontend/debug/previews_section.dart b/lib/frontend/debug/previews_section.dart index c223a99f..19b76d0c 100644 --- a/lib/frontend/debug/previews_section.dart +++ b/lib/frontend/debug/previews_section.dart @@ -1,12 +1,22 @@ import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; +import '../../core/config/whats_new.dart'; import '../../core/storage/app_database.dart'; +import '../../main.dart' show bannersModule; +import '../../models/informer_banner.dart'; +import '../screens/auth/login_needs_2fa_screen.dart'; import '../screens/calls/call_screen.dart'; import '../widgets/auth_limits_sheet.dart'; import '../widgets/login_success_screen.dart'; import 'dev_menu_widgets.dart'; +const InformerBanner _serverBannerPreview = InformerBanner( + id: 'dev-preview-server-banner', + title: 'Истории, опросы и не только', + description: 'В новой версии MAX', +); + class DebugPreviewsSection extends StatelessWidget { final bool micSignalOn; final ValueChanged onMicSignalChanged; @@ -65,6 +75,42 @@ class DebugPreviewsSection extends StatelessWidget { title: 'После регистрации', onTap: () => showAuthLimitsSheet(context, AuthEntry.registration), ), + DevRow( + icon: Symbols.shield_person, + caption: 'Вход', + title: 'MAX требует 2FA', + onTap: () => Navigator.push( + context, + MaterialPageRoute(builder: (_) => const LoginNeeds2faScreen()), + ), + ), + ], + ), + DevGroup( + children: [ + ValueListenableBuilder( + valueListenable: bannersModule.activeBanner, + builder: (context, banner, _) => DevSwitchRow( + title: 'Баннер от сервера MAX', + description: + 'Тестовое объявление над списком чатов, как приходит ' + 'от сервера, с подписью «К Komet не относятся»', + value: banner?.id == _serverBannerPreview.id, + onChanged: (on) => + bannersModule.preview(on ? _serverBannerPreview : null), + ), + ), + ValueListenableBuilder( + valueListenable: WhatsNew.pendingVersion, + builder: (context, version, _) => DevSwitchRow( + title: 'Плашка обновления Google Play', + description: + 'Над списком чатов «Комета обновилась», по нажатию ' + 'шторка «Что нового». Как после обновления из магазина', + value: version != null, + onChanged: (on) => WhatsNew.preview(on), + ), + ), ], ), DevGroup( diff --git a/lib/frontend/screens/auth/call_out_confirmation_screen.dart b/lib/frontend/screens/auth/call_out_confirmation_screen.dart new file mode 100644 index 00000000..97f7d5b2 --- /dev/null +++ b/lib/frontend/screens/auth/call_out_confirmation_screen.dart @@ -0,0 +1,548 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:material_symbols_icons/symbols.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../../backend/modules/account.dart'; +import '../../../core/protocol/packet.dart'; +import '../../../core/utils/logger.dart'; +import '../../../main.dart'; +import '../../widgets/custom_notification.dart'; +import '../../widgets/hint_bubble.dart'; +import '../../widgets/small_spinner.dart'; +import 'call_out_controller.dart'; +import 'code_confirmation_screen.dart'; +import 'login_needs_2fa_screen.dart'; +import 'session_stale_recovery.dart'; +import 'verified_login_flow.dart'; + +class CallOutConfirmationScreen extends StatefulWidget { + final String phoneNumber; + final String rawPhone; + final String countryCode; + final CallOutParams callOut; + + const CallOutConfirmationScreen({ + super.key, + required this.phoneNumber, + required this.rawPhone, + required this.countryCode, + required this.callOut, + }); + + @override + State createState() => + _CallOutConfirmationScreenState(); +} + +class _CallOutConfirmationScreenState extends State + with SessionStaleRecovery, VerifiedLoginFlow { + late final CallOutController _controller; + late final AppLifecycleListener _lifecycle; + CallOutPhase? _handledPhase; + bool _signingIn = false; + bool _refreshing = false; + String? _errorMessage; + + @override + String get connectionDroppedMessage => + AppLocalizations.of(context)!.codeConfirmationConnectionDropped; + + @override + String get verifiedRawPhone => widget.rawPhone; + + @override + String get verifiedPhoneNumber => widget.phoneNumber; + + @override + void showVerificationError(String message) => + setState(() => _errorMessage = message); + + bool get _busy => _signingIn || _refreshing || recovering; + + @override + void initState() { + super.initState(); + _controller = CallOutController( + params: widget.callOut, + check: accountModule.checkCallOut, + )..addListener(_onControllerChanged); + _lifecycle = AppLifecycleListener(onResume: _controller.pollNow); + startSessionRecovery(); + _controller.start(); + } + + @override + void dispose() { + stopSessionRecovery(); + _lifecycle.dispose(); + _controller + ..removeListener(_onControllerChanged) + ..dispose(); + super.dispose(); + } + + void _onControllerChanged() { + final phase = _controller.phase; + if (phase == _handledPhase) return; + _handledPhase = phase; + switch (phase) { + case CallOutPhase.verified: + unawaited(_signIn()); + case CallOutPhase.failed: + final error = _controller.error; + if (error != null && isAuthSessionLostError(error)) { + unawaited( + _refresh(notice: AppLocalizations.of(context)!.callOutNewNumber), + ); + } + case CallOutPhase.waitingForNumber || + CallOutPhase.awaitingCall || + CallOutPhase.expired: + break; + } + } + + @override + Future recoverStaleSession() async { + if (recovering) return; + setState(() => recovering = true); + try { + if (!await waitForOnline()) { + if (mounted) { + showCustomNotification( + context, + AppLocalizations.of(context)!.codeConfirmationNoConnection, + ); + } + return; + } + if (!mounted) return; + setState(() { + sessionEpoch = api.sessionEpoch; + dropNotified = false; + }); + showCustomNotification( + context, + AppLocalizations.of(context)!.codeConfirmationConnectionRestored, + ); + _controller.pollNow(); + } catch (e) { + if (mounted) { + showCustomNotification( + context, + AppLocalizations.of(context)!.codeConfirmationReconnectFailed('$e'), + ); + } + } finally { + if (mounted) setState(() => recovering = false); + } + } + + Future _refresh({String? notice}) async { + if (_signingIn || _refreshing) return; + setState(() { + _refreshing = true; + _errorMessage = null; + }); + try { + if (!await waitForOnline()) { + if (mounted) { + setState( + () => _errorMessage = AppLocalizations.of( + context, + )!.codeConfirmationNoConnection, + ); + } + return; + } + final fresh = await accountModule.requestCode(widget.rawPhone); + if (!mounted) return; + sessionEpoch = api.sessionEpoch; + dropNotified = false; + final callOut = fresh.callOut; + if (callOut == null) { + _openCodeScreen(fresh.token); + return; + } + _handledPhase = null; + _controller.restart(callOut); + if (notice != null) showCustomNotification(context, notice); + } catch (e) { + if (mounted) { + setState( + () => _errorMessage = AppLocalizations.of( + context, + )!.callOutRefreshFailed('$e'), + ); + } + } finally { + if (mounted) setState(() => _refreshing = false); + } + } + + void _openCodeScreen(String token) { + stopSessionRecovery(); + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => CodeConfirmationScreen( + phoneNumber: widget.phoneNumber, + rawPhone: widget.rawPhone, + countryCode: widget.countryCode, + token: token, + ), + ), + ); + } + + Future _signIn() async { + if (_signingIn) return; + setState(() { + _signingIn = true; + _errorMessage = null; + }); + final VerifyCodeResult result; + try { + result = await accountModule.loginByTrack(_controller.trackId); + } catch (e, st) { + logger.d('[${api.debugTag}] вход после звонка не принят: $e\n$st'); + if (!mounted) return; + setState(() => _signingIn = false); + await _onTrackRejected(e); + return; + } + stopSessionRecovery(); + try { + await finishVerifiedLogin(result); + } finally { + if (mounted && (ModalRoute.isCurrentOf(context) ?? true)) { + setState(() => _signingIn = false); + } + } + } + + Future _onTrackRejected(Object error) async { + if (error is PacketError && error.errorKey == loginNeeds2faErrorKey) { + final retry = await Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const LoginNeeds2faScreen()), + ); + if (retry == true && mounted) await _refresh(); + return; + } + if (!mounted) return; + setState( + () => _errorMessage = isSessionStateError(error) + ? AppLocalizations.of(context)!.callOutCommonError + : error.toString(), + ); + } + + Future _dial(BuildContext anchor, String number) async { + var launched = false; + try { + launched = await launchUrl( + Uri(scheme: 'tel', path: number), + mode: LaunchMode.externalApplication, + ); + } catch (_) { + launched = false; + } + if (launched || !anchor.mounted) return; + showHintBubble(anchor, AppLocalizations.of(anchor)!.textEntityDialFailed); + } + + Future _copyNumber(BuildContext anchor, String number) async { + await Clipboard.setData(ClipboardData(text: number)); + if (!anchor.mounted) return; + showHintBubble(anchor, AppLocalizations.of(anchor)!.msgActionsCopied); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + + return PopScope( + canPop: !_signingIn, + child: Scaffold( + backgroundColor: cs.surface, + appBar: AppBar( + backgroundColor: Colors.transparent, + elevation: 0, + leading: IconButton( + icon: Icon(Symbols.arrow_back, color: cs.onSurfaceVariant), + onPressed: _signingIn ? null : () => Navigator.pop(context), + ), + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: ListenableBuilder( + listenable: _controller, + builder: (context, _) { + final phase = _controller.phase; + final number = _controller.callNumber; + final error = + _errorMessage ?? + (phase == CallOutPhase.failed + ? _controller.error?.toString() ?? + l10n.callOutCommonError + : null); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + Text( + widget.phoneNumber, + style: TextStyle( + color: cs.onSurface, + fontSize: 22, + fontWeight: FontWeight.w500, + ), + ), + const SizedBox(height: 12), + Text( + l10n.callOutDescription, + style: TextStyle( + color: cs.outline, + fontSize: 15, + fontWeight: FontWeight.w400, + height: 1.4, + ), + ), + const SizedBox(height: 24), + _CallNumberCard( + number: number, + onCopy: number == null + ? null + : (anchor) => _copyNumber(anchor, number), + ), + const SizedBox(height: 16), + _CallOutStatusLine( + phase: phase, + remaining: _controller.remaining, + signingIn: _signingIn, + ), + AnimatedSize( + duration: const Duration(milliseconds: 250), + curve: Curves.easeOutCubic, + alignment: Alignment.topLeft, + child: error == null + ? const SizedBox(width: double.infinity) + : Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + error, + style: TextStyle( + color: cs.error, + fontSize: 14, + fontWeight: FontWeight.w500, + height: 1.35, + ), + ), + ), + ), + const Spacer(), + _CallOutAction( + phase: phase, + number: number, + busy: _busy, + onDial: _dial, + onRefresh: () => unawaited(_refresh()), + ), + const SizedBox(height: 24), + ], + ); + }, + ), + ), + ), + ), + ); + } +} + +class _CallNumberCard extends StatelessWidget { + final String? number; + final void Function(BuildContext anchor)? onCopy; + + const _CallNumberCard({required this.number, required this.onCopy}); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final value = number; + + return Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(16), + child: Builder( + builder: (anchor) => InkWell( + borderRadius: BorderRadius.circular(16), + onTap: onCopy == null ? null : () => onCopy!(anchor), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18), + child: SizedBox( + width: double.infinity, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 200), + child: value == null + ? Row( + key: const ValueKey('waiting'), + children: [ + SmallSpinner(size: 20, color: cs.primary), + const SizedBox(width: 14), + Expanded( + child: Text( + l10n.callOutWaitingNumber, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 15, + ), + ), + ), + ], + ) + : Column( + key: ValueKey(value), + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + style: TextStyle( + color: cs.onSurface, + fontSize: 26, + fontWeight: FontWeight.w600, + letterSpacing: 0.5, + ), + ), + const SizedBox(height: 4), + Text( + l10n.callOutTapToCopy, + style: TextStyle(color: cs.outline, fontSize: 13), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } +} + +class _CallOutStatusLine extends StatelessWidget { + final CallOutPhase phase; + final ValueListenable remaining; + final bool signingIn; + + const _CallOutStatusLine({ + required this.phase, + required this.remaining, + required this.signingIn, + }); + + static String _format(Duration left) { + final seconds = (left.inMilliseconds / 1000).ceil(); + return '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final style = TextStyle(color: cs.outline, fontSize: 14, height: 1.35); + + if (signingIn) return Text(l10n.callOutVerified, style: style); + if (phase == CallOutPhase.expired) { + return Text(l10n.callOutExpired, style: style); + } + if (phase == CallOutPhase.failed || phase == CallOutPhase.verified) { + return const SizedBox.shrink(); + } + return ValueListenableBuilder( + valueListenable: remaining, + builder: (context, left, _) => + Text(l10n.callOutTimer(_format(left)), style: style), + ); + } +} + +class _CallOutAction extends StatelessWidget { + final CallOutPhase phase; + final String? number; + final bool busy; + final Future Function(BuildContext anchor, String number) onDial; + final VoidCallback onRefresh; + + const _CallOutAction({ + required this.phase, + required this.number, + required this.busy, + required this.onDial, + required this.onRefresh, + }); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final value = number; + final canRefresh = + phase == CallOutPhase.expired || + phase == CallOutPhase.failed || + phase == CallOutPhase.verified; + + final Widget label; + final VoidCallback? onPressed; + if (busy) { + label = SmallSpinner(size: 22, color: cs.onPrimary); + onPressed = null; + } else if (canRefresh) { + label = _label(Symbols.refresh, l10n.callOutRefresh); + onPressed = onRefresh; + } else if (value != null) { + label = _label(Symbols.call, l10n.callOutDial(value)); + onPressed = () => unawaited(onDial(context, value)); + } else { + label = _label(Symbols.call, l10n.callOutDialPending); + onPressed = null; + } + + return SizedBox( + width: double.infinity, + height: 56, + child: FilledButton( + onPressed: onPressed, + style: FilledButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + child: label, + ), + ); + } + + static Widget _label(IconData icon, String text) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 22), + const SizedBox(width: 10), + Flexible( + child: Text( + text, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600), + ), + ), + ], + ); +} diff --git a/lib/frontend/screens/auth/call_out_controller.dart b/lib/frontend/screens/auth/call_out_controller.dart new file mode 100644 index 00000000..f47ab16d --- /dev/null +++ b/lib/frontend/screens/auth/call_out_controller.dart @@ -0,0 +1,150 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import '../../../backend/modules/account.dart'; +import '../../../core/protocol/packet.dart'; +import '../../../core/utils/logger.dart'; + +enum CallOutPhase { waitingForNumber, awaitingCall, verified, expired, failed } + +class CallOutController extends ChangeNotifier { + CallOutController({required CallOutParams params, required this.check}) + : _params = params; + + final Future Function(String trackId) check; + + final ValueNotifier remaining = ValueNotifier(Duration.zero); + final Stopwatch _clock = Stopwatch(); + CallOutParams _params; + Timer? _pollTimer; + Timer? _countdown; + int _generation = 0; + bool _disposed = false; + + CallOutPhase _phase = CallOutPhase.waitingForNumber; + String? _callNumber; + Object? _error; + + CallOutPhase get phase => _phase; + + String? get callNumber => _callNumber; + + Object? get error => _error; + + String get trackId => _params.trackId; + + bool get active => + _phase == CallOutPhase.waitingForNumber || + _phase == CallOutPhase.awaitingCall; + + void start() => restart(_params); + + void restart(CallOutParams params) { + if (_disposed) return; + _params = params; + final generation = ++_generation; + _pollTimer?.cancel(); + _countdown?.cancel(); + _phase = CallOutPhase.waitingForNumber; + _callNumber = null; + _error = null; + _clock + ..reset() + ..start(); + remaining.value = params.ttl; + _countdown = Timer.periodic(const Duration(seconds: 1), (_) => _tick()); + notifyListeners(); + unawaited(_poll(generation)); + } + + void pollNow() { + if (_disposed || !active) return; + _pollTimer?.cancel(); + unawaited(_poll(_generation)); + } + + Duration get _left { + final left = _params.ttl - _clock.elapsed; + return left.isNegative ? Duration.zero : left; + } + + void _tick() { + remaining.value = _left; + if (remaining.value == Duration.zero) _finish(CallOutPhase.expired); + } + + Future _poll(int generation) async { + if (!_isCurrent(generation)) return; + if (_left == Duration.zero) { + _finish(CallOutPhase.expired); + return; + } + + final CallOutCheck result; + try { + result = await check(trackId); + } catch (e) { + if (!_isCurrent(generation)) return; + if (e is PacketError) { + _error = e; + _finish(CallOutPhase.failed); + return; + } + logger.d('проверка звонка не дошла, повторим: $e'); + _schedule(generation); + return; + } + if (!_isCurrent(generation)) return; + + switch (result.status) { + case CallOutStatus.verificationPassed: + _finish(CallOutPhase.verified); + return; + case CallOutStatus.verificationTimeout: + _finish(CallOutPhase.expired); + return; + case CallOutStatus.numberAssigned: + final number = result.callNumber; + if (number != null && number != _callNumber) { + _callNumber = number; + _phase = CallOutPhase.awaitingCall; + notifyListeners(); + } + case CallOutStatus.numberNotAssigned: + case null: + break; + } + _schedule(generation); + } + + bool _isCurrent(int generation) => + !_disposed && generation == _generation && active; + + void _schedule(int generation) { + _pollTimer?.cancel(); + _pollTimer = Timer(_params.pollingInterval, () { + unawaited(_poll(generation)); + }); + } + + void _finish(CallOutPhase phase) { + if (_disposed) return; + _pollTimer?.cancel(); + _countdown?.cancel(); + _clock.stop(); + if (phase == CallOutPhase.expired) remaining.value = Duration.zero; + _phase = phase; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _generation++; + _pollTimer?.cancel(); + _countdown?.cancel(); + remaining.dispose(); + super.dispose(); + } +} diff --git a/lib/frontend/screens/auth/code_confirmation_screen.dart b/lib/frontend/screens/auth/code_confirmation_screen.dart index aa5fb0f4..c64a2fc3 100644 --- a/lib/frontend/screens/auth/code_confirmation_screen.dart +++ b/lib/frontend/screens/auth/code_confirmation_screen.dart @@ -3,26 +3,25 @@ import 'package:flutter/material.dart'; import 'package:komet/l10n/app_localizations.dart'; import 'package:flutter/services.dart'; import 'package:material_symbols_icons/symbols.dart'; -import 'password_2fa_screen.dart'; -import 'registration_screen.dart'; +import 'call_out_confirmation_screen.dart'; +import 'login_needs_2fa_screen.dart'; import 'session_stale_recovery.dart'; import 'slow_login_hint.dart'; -import '../../../backend/api.dart'; +import 'verified_login_flow.dart'; +import '../../../backend/modules/account.dart'; import '../../../core/config/review_access.dart'; import '../../../core/protocol/packet.dart'; import '../../../core/storage/spoofing_service.dart'; import '../../../core/utils/logger.dart'; import '../../../core/utils/sms_code_listener.dart'; import '../../../main.dart'; -import '../../widgets/auth_limits_sheet.dart'; import '../../widgets/custom_notification.dart'; -import '../../widgets/login_success_screen.dart'; import '../../widgets/small_spinner.dart'; -import '../../widgets/temporary_password_recovery_dialog.dart'; class CodeConfirmationScreen extends StatefulWidget { final String phoneNumber; final String rawPhone; + final String countryCode; final String token; final bool reviewAccess; @@ -30,6 +29,7 @@ class CodeConfirmationScreen extends StatefulWidget { super.key, required this.phoneNumber, required this.rawPhone, + required this.countryCode, required this.token, }) : reviewAccess = false; @@ -37,6 +37,7 @@ class CodeConfirmationScreen extends StatefulWidget { super.key, required this.phoneNumber, required this.rawPhone, + required this.countryCode, }) : token = '', reviewAccess = true; @@ -45,7 +46,7 @@ class CodeConfirmationScreen extends StatefulWidget { } class _CodeConfirmationScreenState extends State - with TickerProviderStateMixin, SessionStaleRecovery { + with TickerProviderStateMixin, SessionStaleRecovery, VerifiedLoginFlow { final TextEditingController _codeController = TextEditingController(); final FocusNode _focusNode = FocusNode(); final SmsCodeListener _smsListener = SmsCodeListener(); @@ -68,6 +69,18 @@ class _CodeConfirmationScreenState extends State String get connectionDroppedMessage => AppLocalizations.of(context)!.codeConfirmationConnectionDropped; + @override + String get verifiedRawPhone => widget.rawPhone; + + @override + String get verifiedPhoneNumber => widget.phoneNumber; + + @override + void showVerificationError(String message) => _showError(message); + + bool get _codeArrivesByCall => + !widget.reviewAccess && widget.countryCode != 'RU'; + @override void initState() { super.initState(); @@ -119,7 +132,7 @@ class _CodeConfirmationScreenState extends State if (recovering) return; setState(() => recovering = true); try { - if (!await _waitForOnline()) { + if (!await waitForOnline()) { if (mounted) { showCustomNotification( context, @@ -149,22 +162,11 @@ class _CodeConfirmationScreenState extends State } } - Future _waitForOnline() async { - if (api.state == SessionState.online) return true; - final back = await api.stateStream - .firstWhere((s) => s == SessionState.online) - .timeout( - const Duration(seconds: 12), - onTimeout: () => SessionState.disconnected, - ); - return back == SessionState.online; - } - Future _requestFreshCode(String notice, {bool resend = false}) async { if (recovering) return; setState(() => recovering = true); try { - if (!await _waitForOnline()) { + if (!await waitForOnline()) { if (mounted) { showCustomNotification( context, @@ -177,6 +179,22 @@ class _CodeConfirmationScreenState extends State ? await accountModule.resendCode(widget.rawPhone) : await accountModule.requestCode(widget.rawPhone); if (!mounted) return; + final callOut = fresh.callOut; + if (callOut != null) { + stopSessionRecovery(); + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => CallOutConfirmationScreen( + phoneNumber: widget.phoneNumber, + rawPhone: widget.rawPhone, + countryCode: widget.countryCode, + callOut: callOut, + ), + ), + ); + return; + } setState(() { _token = fresh.token; sessionEpoch = api.sessionEpoch; @@ -269,6 +287,16 @@ class _CodeConfirmationScreenState extends State }); } + Future _showLoginNeeds2fa() async { + final retry = await Navigator.of(context).push( + MaterialPageRoute(builder: (_) => const LoginNeeds2faScreen()), + ); + if (retry != true || !mounted) return; + await _requestFreshCode( + AppLocalizations.of(context)!.codeConfirmationNewCodeSent, + ); + } + void _resendCode() { if (_timerSeconds > 0 || recovering || _verifying) return; unawaited( @@ -279,29 +307,6 @@ class _CodeConfirmationScreenState extends State ); } - Future _completeLogin(String? avatarUrl) async { - if (!mounted) return; - - final avatar = await precacheLoginAvatar(context, avatarUrl); - - if (!mounted) return; - - await markAuthLimitsPending(AuthEntry.login); - - if (!mounted) return; - - Navigator.pushAndRemoveUntil( - context, - PageRouteBuilder( - transitionDuration: const Duration(milliseconds: 240), - pageBuilder: (_, _, _) => LoginSuccessScreen(avatar: avatar), - transitionsBuilder: (_, animation, _, child) => - FadeTransition(opacity: animation, child: child), - ), - (route) => false, - ); - } - Future _verifyReviewCode() async { setState(() => _verifying = true); try { @@ -318,9 +323,12 @@ class _CodeConfirmationScreenState extends State await SpoofingService.saveProfile(SpoofingService.pendingScope, spoof); } - final loginResult = await accountModule.loginWithToken(credentials.token); + final loginResult = await accountModule.loginWithToken( + credentials.token, + accountPhone: widget.rawPhone, + ); - await _completeLogin(loginResult.profile.baseUrl); + await completeLogin(loginResult.profile.baseUrl); } catch (e) { if (!mounted) return; _showError(e.toString()); @@ -343,119 +351,36 @@ class _CodeConfirmationScreenState extends State } setState(() => _verifying = true); - var verified = false; - int? verifiedAccountId; try { - final result = await accountModule.verifyCode( - _codeController.text, - _token, - ); - verified = true; - verifiedAccountId = result.accountId; - stopSessionRecovery(); - - if (!mounted) return; - - if (result.requiresPassword) { - final trackId = result.challengeTrackId; - - if (trackId == null) { - showCustomNotification( - context, - AppLocalizations.of(context)!.codeError2faMissing, - ); - return; - } - - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (context) => Password2FAScreen( - trackId: trackId, - hint: result.challengeHint, - rawPhone: widget.rawPhone, - ), - ), - ); - return; - } - - if (result.isRegistration) { - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (context) => RegistrationScreen( - phoneNumber: widget.phoneNumber, - registerToken: result.registerToken!, - presetAvatars: result.presetAvatars, - ), - ), - ); - return; - } - - logger.d( - '[${api.debugTag}] код подтверждён: ' - '${api.webHandshake ? 'SMS-вход через веб' : 'обычный вход'}', - ); - // #***! эксперим. SMS-вход через веб: получаем сокетовый токен хитрой схемой - if (api.webHandshake) { - final token = result.loginToken; - final accId = result.accountId; - if (token == null || accId == null) { - _showError(AppLocalizations.of(context)!.codeConfirmationSmsNoToken); - return; - } - await accountModule.completeWebSmsSocketLogin( - phone: widget.rawPhone, - accountId: accId, - webToken: token, - existingPassword: null, - ); - if (!mounted) return; - await showTemporaryPasswordRecovery( - context, - accId, - verifiedAccountId: verifiedAccountId, - ); - if (!mounted) return; - await _completeLogin(null); + final VerifyCodeResult result; + try { + result = await accountModule.verifyCode(_codeController.text, _token); + } catch (e, st) { + logger.d('[${api.debugTag}] код не принят: $e\n$st'); + if (mounted) await _onCodeRejected(e); return; } - - final loginResult = await accountModule.login(); - - await _completeLogin(loginResult.profile.baseUrl); - } catch (e, st) { - logger.d( - '[${api.debugTag}] подтверждение кода упало ' - '(код принят=$verified): $e\n$st', - ); - if (!mounted) return; - if (verified && verifiedAccountId != null) { - await showTemporaryPasswordRecovery( - context, - verifiedAccountId, - verifiedAccountId: verifiedAccountId, - ); - if (!mounted) return; - } - if (verified) { - _showError(e.toString()); - } else if (isAuthSessionLostError(e)) { - await _requestFreshCode( - AppLocalizations.of(context)!.codeConfirmationCodeExpired, - ); - } else if (isSessionStateError(e) || sessionStale) { - await recoverStaleSession(); - } else { - _showError(e.toString()); - } + stopSessionRecovery(); + await finishVerifiedLogin(result); } finally { if (mounted) setState(() => _verifying = false); } } + Future _onCodeRejected(Object error) async { + if (error is PacketError && error.errorKey == loginNeeds2faErrorKey) { + await _showLoginNeeds2fa(); + } else if (isAuthSessionLostError(error)) { + await _requestFreshCode( + AppLocalizations.of(context)!.codeConfirmationCodeExpired, + ); + } else if (isSessionStateError(error) || sessionStale) { + await recoverStaleSession(); + } else { + _showError(error.toString()); + } + } + @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; @@ -493,6 +418,8 @@ class _CodeConfirmationScreenState extends State Text( api.webHandshake ? l10n.codeConfirmationSmsSent + : _codeArrivesByCall + ? l10n.codeConfirmationIncomingCall : l10n.codeConfirmationCheckMaxChat, style: TextStyle( color: cs.outline, diff --git a/lib/frontend/screens/auth/login_needs_2fa_screen.dart b/lib/frontend/screens/auth/login_needs_2fa_screen.dart new file mode 100644 index 00000000..81a7df41 --- /dev/null +++ b/lib/frontend/screens/auth/login_needs_2fa_screen.dart @@ -0,0 +1,163 @@ +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../../l10n/app_localizations.dart'; +import '../../widgets/custom_notification.dart'; + +const String loginNeeds2faErrorKey = 'error.profile.active.session.no2fa'; + +final Uri _resetSessionUrl = Uri.parse('https://go.max.ru/reset-session'); + +class LoginNeeds2faScreen extends StatelessWidget { + const LoginNeeds2faScreen({super.key}); + + Future _openResetSession(BuildContext context) async { + final opened = await launchUrl( + _resetSessionUrl, + mode: LaunchMode.externalApplication, + ); + if (!opened && context.mounted) { + showCustomNotification( + context, + AppLocalizations.of(context)!.login2faRequiredLinkFailed, + ); + } + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + return Scaffold( + backgroundColor: cs.surface, + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 400), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + children: [ + const Spacer(), + Container( + width: 80, + height: 80, + decoration: BoxDecoration( + color: cs.primary.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(24), + ), + child: Icon( + Symbols.shield_person, + fill: 1, + size: 40, + color: cs.primary, + ), + ), + const SizedBox(height: 20), + Text( + l10n.login2faRequiredTitle, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 20, + fontWeight: FontWeight.w600, + height: 1.25, + ), + ), + const SizedBox(height: 8), + Text( + l10n.login2faRequiredSteps, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 14, + height: 1.35, + ), + ), + const SizedBox(height: 24), + Text( + l10n.login2faRequiredThen, + textAlign: TextAlign.center, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), + ), + const SizedBox(height: 16), + _NotKometBadge(text: l10n.login2faRequiredNotKomet), + const SizedBox(height: 20), + SizedBox( + width: double.infinity, + height: 56, + child: FilledButton( + onPressed: () => Navigator.of(context).pop(true), + style: FilledButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + child: Text( + l10n.login2faRequiredRetry, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + const Spacer(), + TextButton( + onPressed: () => _openResetSession(context), + child: Text( + l10n.login2faRequiredNoAccess, + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + ), + const SizedBox(height: 16), + ], + ), + ), + ), + ), + ), + ); + } +} + +class _NotKometBadge extends StatelessWidget { + const _NotKometBadge({required this.text}); + + final String text; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: cs.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Symbols.info, size: 18, color: cs.error), + const SizedBox(width: 8), + Flexible( + child: Text( + text, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 13, + fontWeight: FontWeight.w700, + height: 1.3, + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/frontend/screens/auth/login_screen.dart b/lib/frontend/screens/auth/login_screen.dart index 95d60f1c..00133aa2 100644 --- a/lib/frontend/screens/auth/login_screen.dart +++ b/lib/frontend/screens/auth/login_screen.dart @@ -10,6 +10,7 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'code_confirmation_screen.dart'; import 'token_login_screen.dart'; import 'select_country_screen.dart'; +import 'call_out_confirmation_screen.dart'; import 'phone_input_formatter.dart'; import 'proxy_settings_sheet.dart'; import 'server_settings_sheet.dart'; @@ -643,6 +644,7 @@ class _LoginScreenState extends State { phoneNumber: '${_selectedCountry.phoneCode} $formattedPhone', rawPhone: fullPhone, + countryCode: _selectedCountry.code, ), ), ); @@ -669,15 +671,25 @@ class _LoginScreenState extends State { ); if (!screenContext.mounted) return; + final phoneNumber = + '${_selectedCountry.phoneCode} $formattedPhone'; + final callOut = result.callOut; Navigator.push( screenContext, MaterialPageRoute( - builder: (context) => CodeConfirmationScreen( - phoneNumber: - '${_selectedCountry.phoneCode} $formattedPhone', - rawPhone: fullPhone, - token: result.token, - ), + builder: (context) => callOut == null + ? CodeConfirmationScreen( + phoneNumber: phoneNumber, + rawPhone: fullPhone, + countryCode: _selectedCountry.code, + token: result.token, + ) + : CallOutConfirmationScreen( + phoneNumber: phoneNumber, + rawPhone: fullPhone, + countryCode: _selectedCountry.code, + callOut: callOut, + ), ), ); } catch (e, st) { diff --git a/lib/frontend/screens/auth/session_stale_recovery.dart b/lib/frontend/screens/auth/session_stale_recovery.dart index b658344d..d1e57770 100644 --- a/lib/frontend/screens/auth/session_stale_recovery.dart +++ b/lib/frontend/screens/auth/session_stale_recovery.dart @@ -27,6 +27,17 @@ mixin SessionStaleRecovery on State { _stateSub = null; } + Future waitForOnline() async { + if (api.state == SessionState.online) return true; + final back = await api.stateStream + .firstWhere((s) => s == SessionState.online) + .timeout( + const Duration(seconds: 12), + onTimeout: () => SessionState.disconnected, + ); + return back == SessionState.online; + } + void _onSessionState(SessionState state) { if (!mounted) return; if (state != SessionState.online) { diff --git a/lib/frontend/screens/auth/verified_login_flow.dart b/lib/frontend/screens/auth/verified_login_flow.dart new file mode 100644 index 00000000..6484e795 --- /dev/null +++ b/lib/frontend/screens/auth/verified_login_flow.dart @@ -0,0 +1,133 @@ +import 'package:flutter/material.dart'; +import 'package:komet/l10n/app_localizations.dart'; + +import '../../../backend/modules/account.dart'; +import '../../../core/utils/logger.dart'; +import '../../../main.dart'; +import '../../widgets/auth_limits_sheet.dart'; +import '../../widgets/custom_notification.dart'; +import '../../widgets/login_success_screen.dart'; +import '../../widgets/temporary_password_recovery_dialog.dart'; +import 'password_2fa_screen.dart'; +import 'registration_screen.dart'; + +mixin VerifiedLoginFlow on State { + String get verifiedRawPhone; + + String get verifiedPhoneNumber; + + void showVerificationError(String message); + + Future finishVerifiedLogin(VerifyCodeResult result) async { + try { + await _continueAfterVerification(result); + } catch (e, st) { + logger.d('[${api.debugTag}] вход после подтверждения упал: $e\n$st'); + if (!mounted) return; + final accountId = result.accountId; + if (accountId != null) { + await showTemporaryPasswordRecovery( + context, + accountId, + verifiedAccountId: accountId, + ); + if (!mounted) return; + } + showVerificationError(e.toString()); + } + } + + Future completeLogin(String? avatarUrl) async { + if (!mounted) return; + + final avatar = await precacheLoginAvatar(context, avatarUrl); + + if (!mounted) return; + + await markAuthLimitsPending(AuthEntry.login); + + if (!mounted) return; + + Navigator.pushAndRemoveUntil( + context, + PageRouteBuilder( + transitionDuration: const Duration(milliseconds: 240), + pageBuilder: (_, _, _) => LoginSuccessScreen(avatar: avatar), + transitionsBuilder: (_, animation, _, child) => + FadeTransition(opacity: animation, child: child), + ), + (route) => false, + ); + } + + Future _continueAfterVerification(VerifyCodeResult result) async { + if (!mounted) return; + final l10n = AppLocalizations.of(context)!; + + if (result.requiresPassword) { + final trackId = result.challengeTrackId; + if (trackId == null) { + showCustomNotification(context, l10n.codeError2faMissing); + return; + } + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => Password2FAScreen( + trackId: trackId, + hint: result.challengeHint, + rawPhone: verifiedRawPhone, + ), + ), + ); + return; + } + + if (result.isRegistration) { + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => RegistrationScreen( + phoneNumber: verifiedPhoneNumber, + registerToken: result.registerToken!, + presetAvatars: result.presetAvatars, + ), + ), + ); + return; + } + + logger.d( + '[${api.debugTag}] вход подтверждён: ' + '${api.webHandshake ? 'SMS-вход через веб' : 'обычный вход'}', + ); + // #***! эксперим. SMS-вход через веб: получаем сокетовый токен хитрой схемой + if (api.webHandshake) { + final token = result.loginToken; + final accountId = result.accountId; + if (token == null || accountId == null) { + showVerificationError(l10n.codeConfirmationSmsNoToken); + return; + } + await accountModule.completeWebSmsSocketLogin( + phone: verifiedRawPhone, + accountId: accountId, + webToken: token, + existingPassword: null, + ); + if (!mounted) return; + await showTemporaryPasswordRecovery( + context, + accountId, + verifiedAccountId: accountId, + ); + if (!mounted) return; + await completeLogin(null); + return; + } + + final loginResult = await accountModule.login(); + + await completeLogin(loginResult.profile.baseUrl); + } +} diff --git a/lib/frontend/screens/calls/call_screen.dart b/lib/frontend/screens/calls/call_screen.dart index 9eecf2c0..6ce57d53 100644 --- a/lib/frontend/screens/calls/call_screen.dart +++ b/lib/frontend/screens/calls/call_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io' show Platform; import 'dart:math' show cos, pi; import 'package:cached_network_image/cached_network_image.dart'; @@ -7,11 +8,13 @@ import 'package:flutter/services.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart' show MediaStream, RTCVideoRenderer, RTCVideoValue, RTCVideoViewObjectFit; import 'package:material_symbols_icons/symbols.dart'; +import 'package:permission_handler/permission_handler.dart'; import '../../../backend/modules/messages.dart' show ContactCache; import '../../../core/cache/info_cache.dart'; import '../../../core/calls/active_call.dart'; import '../../../core/calls/call_controller.dart'; +import '../../../core/calls/call_permissions.dart'; import '../../../core/calls/call_info.dart'; import '../../../core/calls/call_session.dart'; import '../../../core/config/app_colors.dart'; @@ -68,6 +71,7 @@ class _CallScreenState extends State with TickerProviderStateMixin { StreamSubscription? _infoSub; StreamSubscription? _kometSub; StreamSubscription? _chatSub; + StreamSubscription? _noticeSub; StreamSubscription? _remoteStreamSub; bool _chatOpen = false; bool _stageOpen = false; @@ -273,9 +277,15 @@ class _CallScreenState extends State with TickerProviderStateMixin { _tileStreamSub = session.participantStreamUpdates.listen(_onTileStream); _kometSub = session.peerKometDetected.listen((_) => _showKometBadge()); _chatSub = session.chatMessages.listen(_onChatMessage); + _noticeSub = session.notices.listen(_onNotice); if (session.peerIsKomet) { WidgetsBinding.instance.addPostFrameCallback((_) => _showKometBadge()); } + if (session.micUnavailable) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => _showMicUnavailable(), + ); + } final existing = session.remoteStream; if (existing != null) _attachStream(existing); _resolveParticipants(); @@ -301,6 +311,22 @@ class _CallScreenState extends State with TickerProviderStateMixin { showCustomNotification(context, l10n.callKometDetectedNotification); } + void _onNotice(CallNotice notice) { + if (notice == CallNotice.micUnavailable) _showMicUnavailable(); + } + + void _showMicUnavailable() { + if (!mounted) return; + final l10n = AppLocalizations.of(context)!; + showCustomNotification( + context, + l10n.callMicUnavailable, + action: Platform.isAndroid || Platform.isIOS + ? (label: l10n.callMicSettings, onTap: () => openAppSettings()) + : null, + ); + } + void _onChatMessage(CallChatMessage message) { if (!mounted || message.mine || _chatOpen) return; showCustomNotification(context, message.text); @@ -358,6 +384,13 @@ class _CallScreenState extends State with TickerProviderStateMixin { final session = await CallController.instance.acceptIncoming(incoming); if (!mounted) return; _bind(session); + } on CallMicrophonePermissionException { + if (!mounted) return; + setState(() => _incomingPending = true); + showCustomNotification( + context, + AppLocalizations.of(context)!.callMicrophonePermissionDenied, + ); } catch (_) { _close(); } @@ -469,6 +502,7 @@ class _CallScreenState extends State with TickerProviderStateMixin { _infoSub?.cancel(); _kometSub?.cancel(); _chatSub?.cancel(); + _noticeSub?.cancel(); _remoteStreamSub?.cancel(); _tileStreamSub?.cancel(); for (final renderer in _tileRenderers.values) { diff --git a/lib/frontend/screens/calls/calls_tab.dart b/lib/frontend/screens/calls/calls_tab.dart index faa1c384..509415d0 100644 --- a/lib/frontend/screens/calls/calls_tab.dart +++ b/lib/frontend/screens/calls/calls_tab.dart @@ -7,6 +7,7 @@ import '../../../backend/modules/account.dart'; import '../../../core/storage/app_database.dart'; import '../../../core/utils/format.dart'; import '../../../core/calls/call_controller.dart'; +import '../../../core/calls/call_permissions.dart'; import '../../../backend/modules/calls.dart'; import '../../widgets/komet_avatar.dart'; import '../../widgets/connection_status.dart'; @@ -379,6 +380,9 @@ class _CallsTabState extends State CallScreen(name: name, session: session, isGroup: true), ), ); + } on CallMicrophonePermissionException { + if (!mounted) return; + showCustomNotification(context, l10n.callMicrophonePermissionDenied); } catch (e) { if (!mounted) return; showCustomNotification(context, l10n.callsTabStartFailed('$e')); diff --git a/lib/frontend/screens/calls/group_call_view.dart b/lib/frontend/screens/calls/group_call_view.dart index fbaa2378..bb4f6f13 100644 --- a/lib/frontend/screens/calls/group_call_view.dart +++ b/lib/frontend/screens/calls/group_call_view.dart @@ -254,13 +254,15 @@ class _GroupCallViewState extends State { void _onNotice(CallNotice notice) { if (!mounted) return; final l10n = AppLocalizations.of(context)!; - showCustomNotification(context, switch (notice) { + final text = switch (notice) { CallNotice.handLoweredByAdmin => l10n.callHandLoweredByAdmin, CallNotice.allHandsLoweredByAdmin => l10n.callAllHandsLoweredByAdmin, CallNotice.micMutedByAdmin => l10n.callMicMutedByAdmin, CallNotice.cameraMutedByAdmin => l10n.callCameraMutedByAdmin, CallNotice.screenMutedByAdmin => l10n.callScreenMutedByAdmin, - }); + CallNotice.micUnavailable => null, + }; + if (text != null) showCustomNotification(context, text); } List _ordered() { @@ -879,8 +881,7 @@ class _GroupCallViewState extends State { ); return CallStage( key: ValueKey(focus), - media: - widget.mediaOf(p, avatar, source: focus.$2, stage: true) ?? avatar, + media: widget.mediaOf(p, avatar, source: focus.$2, stage: true) ?? avatar, label: screen ? l10n.callScreenOf(view.name) : view.name, labelIcon: screen ? Symbols.screen_share : Symbols.videocam, speaking: !screen && !muted && _session.isSpeaking(p.id), diff --git a/lib/frontend/screens/chats/chat/channel_recommendations.dart b/lib/frontend/screens/chats/chat/channel_recommendations.dart new file mode 100644 index 00000000..8629cc06 --- /dev/null +++ b/lib/frontend/screens/chats/chat/channel_recommendations.dart @@ -0,0 +1,74 @@ +import 'package:flutter/foundation.dart'; + +import '../../../../core/config/komet_settings.dart'; +import '../../../../models/suggested_channel.dart'; + +enum SuggestedChannelState { idle, joining, joined } + +class ChannelRecommendations extends ChangeNotifier { + ChannelRecommendations({ + required this.chatId, + required Future> Function() fetch, + required Future Function(SuggestedChannel channel) join, + }) : _fetch = fetch, + _join = join { + KometSettings.hideChannelRecommendations.addListener(notifyListeners); + KometSettings.recommendationsHiddenIn.addListener(notifyListeners); + } + + final int chatId; + final Future> Function() _fetch; + final Future Function(SuggestedChannel channel) _join; + final Map _states = {}; + List _channels = const []; + bool _requested = false; + bool _disposed = false; + + List get channels => _channels; + + bool get allowed => + !KometSettings.hideChannelRecommendations.value && + !KometSettings.recommendationsHiddenIn.value.contains(chatId); + + bool get visible => allowed && _channels.isNotEmpty; + + SuggestedChannelState stateOf(SuggestedChannel channel) => + _states[channel.id] ?? SuggestedChannelState.idle; + + Future load() async { + if (_requested || !allowed) return; + _requested = true; + final channels = await _fetch(); + if (_disposed || channels.isEmpty) return; + _channels = channels; + notifyListeners(); + } + + Future hide() => KometSettings.hideRecommendationsIn(chatId); + + Future join(SuggestedChannel channel) async { + if (stateOf(channel) != SuggestedChannelState.idle) return; + _setState(channel, SuggestedChannelState.joining); + try { + await _join(channel); + _setState(channel, SuggestedChannelState.joined); + } catch (_) { + _setState(channel, SuggestedChannelState.idle); + rethrow; + } + } + + void _setState(SuggestedChannel channel, SuggestedChannelState state) { + if (_disposed) return; + _states[channel.id] = state; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + KometSettings.hideChannelRecommendations.removeListener(notifyListeners); + KometSettings.recommendationsHiddenIn.removeListener(notifyListeners); + super.dispose(); + } +} diff --git a/lib/frontend/screens/chats/chat/channel_views.dart b/lib/frontend/screens/chats/chat/channel_views.dart new file mode 100644 index 00000000..31e5d3ab --- /dev/null +++ b/lib/frontend/screens/chats/chat/channel_views.dart @@ -0,0 +1,88 @@ +import 'dart:async'; +import 'dart:collection'; + +import 'package:flutter/foundation.dart'; + +typedef ChannelViewsFetch = + Future?> Function( + List messageIds, { + required bool count, + }); + +class ChannelViews { + ChannelViews(this._fetch, {DateTime Function()? clock}) + : _clock = clock ?? DateTime.now; + + static const Duration batchDelay = Duration(milliseconds: 300); + static const Duration freshFor = Duration(minutes: 1); + static const int batchSize = 50; + + final ChannelViewsFetch _fetch; + final DateTime Function() _clock; + final Map> _views = {}; + final Map _requestedAt = {}; + final LinkedHashSet _queue = LinkedHashSet(); + final Set _counted = {}; + Timer? _timer; + bool _disposed = false; + bool _refused = false; + + ValueListenable of(String messageId) { + final views = _views.putIfAbsent(messageId, () => ValueNotifier(null)); + _enqueue(messageId); + return views; + } + + void _enqueue(String messageId) { + if (_disposed || _refused || int.tryParse(messageId) == null) return; + final requested = _requestedAt[messageId]; + if (requested != null && _clock().difference(requested) < freshFor) { + return; + } + _queue.add(messageId); + _timer ??= Timer(batchDelay, _flush); + } + + Future _flush() async { + _timer = null; + if (_disposed || _queue.isEmpty) return; + final batch = _queue.take(batchSize).toList(growable: false); + _queue.removeAll(batch); + if (_queue.isNotEmpty) _timer = Timer(batchDelay, _flush); + final now = _clock(); + for (final id in batch) { + _requestedAt[id] = now; + } + final unseen = []; + final seen = []; + for (final id in batch) { + (_counted.add(id) ? unseen : seen).add(id); + } + final results = await Future.wait([ + if (unseen.isNotEmpty) _fetch(unseen, count: true), + if (seen.isNotEmpty) _fetch(seen, count: false), + ]); + if (_disposed) return; + if (results.contains(null)) { + _refused = true; + _timer?.cancel(); + _timer = null; + _queue.clear(); + return; + } + for (final views in results) { + for (final MapEntry(:key, :value) in views!.entries) { + _views[key]?.value = value; + } + } + } + + void dispose() { + _disposed = true; + _timer?.cancel(); + for (final views in _views.values) { + views.dispose(); + } + _views.clear(); + } +} diff --git a/lib/frontend/screens/chats/chat/chat_media_send_controller.dart b/lib/frontend/screens/chats/chat/chat_media_send_controller.dart index f180fee6..c0e088ca 100644 --- a/lib/frontend/screens/chats/chat/chat_media_send_controller.dart +++ b/lib/frontend/screens/chats/chat/chat_media_send_controller.dart @@ -9,10 +9,12 @@ import 'package:geolocator/geolocator.dart'; import '../../../../backend/modules/chats.dart'; import '../../../../backend/modules/contacts.dart'; import '../../../../backend/modules/messages.dart'; +import '../../../../backend/modules/outgoing_reply.dart'; import '../../../../backend/modules/upload_service.dart'; import '../../../../core/cache/message_session_cache.dart'; import '../../../../core/crypto/chat_crypto_service.dart'; import '../../../../core/crypto/e2ee_service.dart'; +import '../../../../core/storage/app_database.dart'; import 'package:komet_crypto/komet_crypto.dart' show ContentType; @@ -30,6 +32,12 @@ import '../../../widgets/sending_clock_icon.dart'; import 'chat_controller.dart'; import 'upload_status.dart'; +typedef _AttachSender = + Future?> Function( + void Function() beforeSend, + OutgoingReply? reply, + ); + // #***! отправка вложений (фото/видео/голос/файл/стикер/контакт/локация) + // отслеживание статуса загрузки; текстовые сообщения остаются в chat_screen.dart class ChatMediaSendController { @@ -45,6 +53,7 @@ class ChatMediaSendController { final Future Function(String text, {bool notify}) encryptOutgoing; final VoidCallback markHasScheduled; final Future Function() confirmSend; + final OutgoingReply? Function() takeReply; ChatMediaSendController({ required this.chatController, @@ -59,6 +68,7 @@ class ChatMediaSendController { required this.encryptOutgoing, required this.confirmSend, required this.markHasScheduled, + required this.takeReply, }); int get _myId => chatController.myId; @@ -81,10 +91,11 @@ class ChatMediaSendController { String? text, Uint8List? sealedText, int e2ee = CachedMessage.e2eeNone, + OutgoingReply? reply, }) { final now = DateTime.now().millisecondsSinceEpoch; final tempId = chatController.nextTempId(); - final msg = CachedMessage( + final unquoted = CachedMessage( id: tempId, accountId: _myId, chatId: _chatId, @@ -96,6 +107,7 @@ class ChatMediaSendController { sealedText: sealedText, e2ee: e2ee, ); + final msg = reply?.quotedIn(unquoted) ?? unquoted; setLastSentId(tempId); chatController.addMessage(msg); _previewInChatList(msg, 'sending'); @@ -105,6 +117,134 @@ class ChatMediaSendController { return msg; } + bool canRetry(CachedMessage message) { + if (message.status != 'error') return false; + if (message.e2ee != CachedMessage.e2eeNone) return false; + final attachments = message.attachments; + if (attachments == null || attachments.isEmpty) return false; + return switch (attachments.first) { + PhotoAttachment() => attachments.every( + (a) => a is PhotoAttachment && a.localPath != null, + ), + VideoAttachment(:final localPath) => localPath != null, + AudioAttachment(:final localPath) => localPath != null, + FileAttachment(:final localPath, :final fileId) => + localPath != null || fileId != null, + StickerAttachment(:final stickerId) => int.tryParse('$stickerId') != null, + ContactAttachment(:final contactId) => contactId != null, + LocationAttachment(:final latitude, :final longitude) => + latitude != null && longitude != null, + _ => false, + }; + } + + Future retry(CachedMessage failed) async { + if (_myId == 0 || !canRetry(failed)) return; + if (encryptionEnabled()) { + notify(_l10n.chatEncryptedUnsupportedMedia); + return; + } + final attachments = failed.attachments!; + for (final attachment in attachments) { + final path = switch (attachment) { + PhotoAttachment(:final localPath) => localPath, + VideoAttachment(:final localPath) => localPath, + AudioAttachment(:final localPath) => localPath, + FileAttachment(:final localPath) => localPath, + _ => null, + }; + if (path != null && !await File(path).exists()) { + if (isMounted()) notify(_l10n.chatRetryFileMissing); + return; + } + } + if (!isMounted()) return; + final reply = OutgoingReply.fromPayload( + failed.payload, + accountId: _myId, + chatId: _chatId, + ); + final caption = failed.text ?? ''; + _discard(failed); + switch (attachments.first) { + case PhotoAttachment(): + await _sendPhotoAlbum( + [ + for (final photo in attachments.cast()) + PickedPhoto(item: GalleryItem.fromFile(File(photo.localPath!))), + ], + caption, + waitForUpload: false, + reply: reply, + ); + case VideoAttachment(videoType: 1, :final localPath?, :final duration): + _sendVideoNoteFile(File(localPath), duration ?? 0, reply); + case VideoAttachment(:final localPath?): + await sendVideo( + PickedPhoto(item: GalleryItem.fromFile(File(localPath))), + caption, + reply: reply, + ); + case AudioAttachment(:final localPath?, :final duration, :final waveform): + _sendVoiceFile( + File(localPath), + duration ?? 0, + Uint8List.fromList((waveform ?? '').codeUnits), + reply, + ); + case FileAttachment(:final localPath?, :final name, :final size): + final source = File(localPath); + await _uploadAsFile( + source: source, + filename: name ?? source.uri.pathSegments.last, + size: size ?? await source.length(), + text: failed.text, + reply: reply, + ); + case final FileAttachment stored: + await _sendStoredFile( + stored, + reply: reply, + beforeSend: _unencryptedSendGuard(), + ); + case final StickerAttachment sticker: + await _sendAttach( + [sticker], + _stickerSender(int.parse('${sticker.stickerId}')), + reply: reply, + beforeSend: _unencryptedSendGuard(), + ); + case final ContactAttachment contact: + await _sendAttach( + [contact], + _contactSender(contact.contactId!), + reply: reply, + beforeSend: _unencryptedSendGuard(), + ); + case final LocationAttachment location: + await _sendAttach( + [location], + _locationSender( + location.latitude!, + location.longitude!, + location.zoom ?? 15, + ), + reply: reply, + beforeSend: _unencryptedSendGuard(), + ); + default: + break; + } + } + + void _discard(CachedMessage failed) { + final index = chatController.indexOfId(failed.id); + if (index != -1) chatController.removeMessageAt(index); + MessageSessionCache.removeMessage(_myId, _chatId, failed.id); + unawaited(AppDatabase.deleteMessage(_myId, _chatId, failed.id)); + bumpMessages(); + } + // #***! строку в списке чатов обновляем сами: экран чата к моменту // доставки могли уже закрыть, а пуш на своё сообщение не приходит void _previewInChatList( @@ -176,7 +316,11 @@ class ChatMediaSendController { Future sendAttachMessage( List optimistic, - Future?> Function(void Function() beforeSend) send, + Future?> Function( + void Function() beforeSend, + OutgoingReply? reply, + ) + send, ) async { if (_myId == 0) return; final beforeSend = _unencryptedSendGuard(); @@ -185,10 +329,28 @@ class ChatMediaSendController { return; } if (!await confirmSend() || !isMounted()) return; + await _sendAttach( + optimistic, + send, + reply: takeReply(), + beforeSend: beforeSend, + ); + } + + Future _sendAttach( + List optimistic, + Future?> Function( + void Function() beforeSend, + OutgoingReply? reply, + ) + send, { + required OutgoingReply? reply, + required void Function() beforeSend, + }) async { final tempId = chatController.nextTempId(); final now = DateTime.now().millisecondsSinceEpoch; - final tempMessage = CachedMessage( + final unquoted = CachedMessage( id: tempId, accountId: _myId, chatId: _chatId, @@ -197,6 +359,7 @@ class ChatMediaSendController { status: 'sending', attachments: optimistic, ); + final tempMessage = reply?.quotedIn(unquoted) ?? unquoted; chatController.addMessage(tempMessage); setLastSentId(tempId); _previewInChatList(tempMessage, 'sending'); @@ -205,7 +368,7 @@ class ChatMediaSendController { scrollToBottom(); try { - final serverMsg = await send(beforeSend); + final serverMsg = await send(beforeSend, reply); final mounted = isMounted(); final idx = chatController.indexOfId(tempId); if (mounted && idx == -1) return; @@ -218,7 +381,10 @@ class ChatMediaSendController { } return; } - final real = CachedMessage.fromPushPayload(_myId, _chatId, serverMsg); + final real = OutgoingReply.keepQuote( + CachedMessage.fromPushPayload(_myId, _chatId, serverMsg), + tempMessage, + ); if (mounted) { chatController.setMessageAt(idx, real); bumpMessages(); @@ -244,14 +410,39 @@ class ChatMediaSendController { height: sticker.height, ), ], - (beforeSend) => messagesModule.sendStickerMessage( - _chatId, - sticker.id, - beforeSend: beforeSend, - ), + _stickerSender(sticker.id), ); } + _AttachSender _stickerSender(int stickerId) => + (beforeSend, reply) => messagesModule.sendStickerMessage( + _chatId, + stickerId, + beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, + ); + + _AttachSender _contactSender(int contactId) => + (beforeSend, reply) => messagesModule.sendContactMessage( + _chatId, + contactId, + beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, + ); + + _AttachSender _locationSender(double lat, double lon, double zoom) => + (beforeSend, reply) => messagesModule.sendLocationMessage( + _chatId, + lat, + lon, + zoom: zoom, + beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, + ); + Future sendContact(CachedContact contact) async { final last = contact.lastName; final fullName = (last != null && last.isNotEmpty) @@ -267,11 +458,7 @@ class ChatMediaSendController { photoUrl: contact.baseUrl, ), ], - (beforeSend) => messagesModule.sendContactMessage( - _chatId, - contact.id, - beforeSend: beforeSend, - ), + _contactSender(contact.id), ); } @@ -308,12 +495,7 @@ class ChatMediaSendController { final lon = position.longitude; await sendAttachMessage( [LocationAttachment(latitude: lat, longitude: lon, zoom: 15)], - (beforeSend) => messagesModule.sendLocationMessage( - _chatId, - lat, - lon, - beforeSend: beforeSend, - ), + _locationSender(lat, lon, 15), ); } @@ -349,12 +531,22 @@ class ChatMediaSendController { } catch (_) {} return; } - final wave = _buildWave(amps); + _sendVoiceFile(file, durationMs, _buildWave(amps), takeReply()); + } + + void _sendVoiceFile( + File file, + int durationMs, + Uint8List wave, + OutgoingReply? reply, + ) { final placeholder = addOptimisticMediaMessage( AudioAttachment( duration: durationMs, waveform: String.fromCharCodes(wave), + localPath: file.path, ), + reply: reply, ); unawaited( @@ -366,6 +558,7 @@ class ChatMediaSendController { durationMs: durationMs, wave: wave, placeholder: placeholder, + reply: reply, ), ); } @@ -384,8 +577,13 @@ class ChatMediaSendController { } catch (_) {} return; } + _sendVideoNoteFile(file, durationMs, takeReply()); + } + + void _sendVideoNoteFile(File file, int durationMs, OutgoingReply? reply) { final placeholder = addOptimisticMediaMessage( VideoAttachment(duration: durationMs, videoType: 1, localPath: file.path), + reply: reply, ); unawaited( @@ -396,6 +594,7 @@ class ChatMediaSendController { file: file, durationMs: durationMs, placeholder: placeholder, + reply: reply, ), ); } @@ -407,21 +606,35 @@ class ChatMediaSendController { return; } if (!await confirmSend() || !isMounted()) return; - final tempId = addOptimisticMediaMessage( + showAttachmentPanel.value = false; + await _sendStoredFile( FileAttachment( fileId: entry.fileId, fileToken: entry.token, name: entry.filename, size: entry.size, ), - ).id; - showAttachmentPanel.value = false; + reply: takeReply(), + beforeSend: beforeSend, + ); + } + + Future _sendStoredFile( + FileAttachment file, { + required OutgoingReply? reply, + required void Function() beforeSend, + }) async { + final fileId = file.fileId; + if (fileId == null) return; + final tempId = addOptimisticMediaMessage(file, reply: reply).id; try { final realId = await messagesModule.sendFileMessage( _chatId, - entry.fileId, - token: entry.token, + fileId, + token: file.fileToken, beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ); updateFileMessageStatus( tempId, @@ -440,12 +653,18 @@ class ChatMediaSendController { } final beforeSend = _unencryptedSendGuard(); if (!await confirmSend() || !isMounted()) return false; - final tempId = addOptimisticMediaMessage(FileAttachment(fileId: fileId)).id; + final reply = takeReply(); + final tempId = addOptimisticMediaMessage( + FileAttachment(fileId: fileId), + reply: reply, + ).id; try { final realId = await messagesModule.sendFileMessage( _chatId, fileId, beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ); final ok = realId != null; if (!isMounted()) return ok; @@ -477,14 +696,18 @@ class ChatMediaSendController { if (_myId == 0) return; if (!await confirmSend() || !isMounted()) return; onConfirmed?.call(); - if (encryptionEnabled()) return sendEncryptedPhotos(picked, caption); + var reply = takeReply(); + if (encryptionEnabled()) { + return sendEncryptedPhotos(picked, caption, reply: reply); + } final videos = picked.where((ph) => ph.item.isVideo).toList(); final photos = picked.where((ph) => !ph.item.isVideo).toList(); if (photos.isEmpty && videos.isEmpty) return; for (var i = 0; i < videos.length; i++) { final cap = (photos.isEmpty && i == 0) ? caption : ''; - await sendVideo(videos[i], cap); + await sendVideo(videos[i], cap, reply: reply); + reply = null; } if (photos.isEmpty) return; @@ -494,17 +717,25 @@ class ChatMediaSendController { [photos[i]], i == 0 ? caption : '', waitForUpload: waitForUpload, + reply: reply, ); + reply = null; } return; } - await _sendPhotoAlbum(photos, caption, waitForUpload: waitForUpload); + await _sendPhotoAlbum( + photos, + caption, + waitForUpload: waitForUpload, + reply: reply, + ); } Future _sendPhotoAlbum( List photos, String caption, { required bool waitForUpload, + OutgoingReply? reply, }) async { final jobs = <({File file, GalleryItem? item})>[]; final attachments = []; @@ -524,7 +755,7 @@ class ChatMediaSendController { if (jobs.isEmpty || !isMounted()) return; final tempId = chatController.nextTempId(); - final placeholder = CachedMessage( + final unquoted = CachedMessage( id: tempId, accountId: _myId, chatId: _chatId, @@ -534,6 +765,7 @@ class ChatMediaSendController { status: 'sending', attachments: attachments, ); + final placeholder = reply?.quotedIn(unquoted) ?? unquoted; chatController.addMessage(placeholder); setLastSentId(tempId); @@ -549,6 +781,7 @@ class ChatMediaSendController { jobs: jobs, caption: caption, placeholder: placeholder, + reply: reply, ); if (waitForUpload) { await upload; @@ -561,6 +794,7 @@ class ChatMediaSendController { PickedPhoto video, String caption, { int? scheduledTime, + OutgoingReply? reply, }) async { if (_myId == 0) return; if (encryptionEnabled()) { @@ -609,7 +843,7 @@ class ChatMediaSendController { if (scheduledTime != null) { notify(_l10n.fontSettingsLoading); } else { - placeholder = CachedMessage( + final unquoted = CachedMessage( id: tempId, accountId: _myId, chatId: _chatId, @@ -627,6 +861,7 @@ class ChatMediaSendController { ), ], ); + placeholder = reply?.quotedIn(unquoted) ?? unquoted; chatController.addMessage(placeholder); setLastSentId(tempId); _previewInChatList(placeholder, 'sending'); @@ -644,6 +879,7 @@ class ChatMediaSendController { caption: caption, placeholder: placeholder, scheduledTime: scheduledTime, + reply: reply, ), ); } @@ -665,10 +901,17 @@ class ChatMediaSendController { final videos = picked.where((ph) => ph.item.isVideo).toList(); final photos = picked.where((ph) => !ph.item.isVideo).toList(); if (photos.isEmpty && videos.isEmpty) return; + var reply = takeReply(); for (var i = 0; i < videos.length; i++) { final cap = (photos.isEmpty && i == 0) ? caption : ''; - await sendVideo(videos[i], cap, scheduledTime: scheduledTime); + await sendVideo( + videos[i], + cap, + scheduledTime: scheduledTime, + reply: reply, + ); + reply = null; } if (photos.isEmpty) return; @@ -678,18 +921,26 @@ class ChatMediaSendController { [photos[i]], i == 0 ? caption : '', scheduledTime, + reply: reply, ); + reply = null; } return; } - await _sendScheduledPhotoAlbum(photos, caption, scheduledTime); + await _sendScheduledPhotoAlbum( + photos, + caption, + scheduledTime, + reply: reply, + ); } Future _sendScheduledPhotoAlbum( List photos, String caption, - int scheduledTime, - ) async { + int scheduledTime, { + OutgoingReply? reply, + }) async { final jobs = <({File file, GalleryItem? item})>[]; for (final photo in photos) { final edited = photo.editedFile; @@ -715,14 +966,17 @@ class ChatMediaSendController { jobs: jobs, caption: caption, scheduledTime: scheduledTime, + reply: reply, ), ); } Future sendEncryptedPhotos( List picked, - String caption, - ) async { + String caption, { + OutgoingReply? reply, + }) async { + var pendingReply = reply; final photos = picked.where((ph) => !ph.item.isVideo).toList(); if (photos.length != picked.length && isMounted()) { notify(_l10n.chatMediaSendVideoNotEncryptable); @@ -771,7 +1025,9 @@ class ChatMediaSendController { text: wire, sealedText: sealed, e2ee: CachedMessage.e2eeFile, + reply: pendingReply, ); + pendingReply = null; if (!isMounted()) return; continue; } @@ -798,7 +1054,9 @@ class ChatMediaSendController { filename: 'photo_$stamp$kEncryptedPhotoExtension', encryptedPayload: true, size: await encrypted.length(), + reply: pendingReply, ); + pendingReply = null; if (!isMounted()) return; } @@ -834,6 +1092,7 @@ class ChatMediaSendController { text: text, sealedText: sealedText, e2ee: e2ee, + reply: takeReply(), ); } @@ -846,6 +1105,7 @@ class ChatMediaSendController { Uint8List? sealedText, int e2ee = CachedMessage.e2eeNone, bool encryptedPayload = false, + OutgoingReply? reply, }) async { if (_myId == 0) return; @@ -854,10 +1114,15 @@ class ChatMediaSendController { final placeholder = scheduledTime != null ? null : addOptimisticMediaMessage( - FileAttachment(name: filename, size: size), + FileAttachment( + name: filename, + size: size, + localPath: encryptedPayload ? null : source.path, + ), text: text, sealedText: sealedText, e2ee: e2ee, + reply: reply, ); final sending = UploadService.instance.sendFile( @@ -871,6 +1136,7 @@ class ChatMediaSendController { text: text, scheduledTime: scheduledTime, encryptedPayload: encryptedPayload, + reply: reply, ); syncUploadStatus(); await sending; diff --git a/lib/frontend/screens/chats/chat/chat_scroll_navigator.dart b/lib/frontend/screens/chats/chat/chat_scroll_navigator.dart index b5cfa96f..a3f8d9ac 100644 --- a/lib/frontend/screens/chats/chat/chat_scroll_navigator.dart +++ b/lib/frontend/screens/chats/chat/chat_scroll_navigator.dart @@ -116,7 +116,7 @@ class ChatScrollNavigator { final List _returnStack = []; bool _scrollDownVisible = false; - final ValueNotifier newMessageCount = ValueNotifier(0); + final ValueNotifier unreadBelow = ValueNotifier(0); bool _clearCountScheduled = false; bool get busy => _busy > 0; @@ -126,7 +126,7 @@ class ChatScrollNavigator { _highlightTimer?.cancel(); jumpCacheExtent.dispose(); highlightMessageId.dispose(); - newMessageCount.dispose(); + unreadBelow.dispose(); } void bumpGestureEpoch() => gestureEpoch++; @@ -463,7 +463,7 @@ class ChatScrollNavigator { void scrollToBottom() { flushDeferredMessages(); _returnStack.clear(); - newMessageCount.value = 0; + unreadBelow.value = 0; if (chatController.hasNewer) { unawaited(_returnToLatest()); return; @@ -569,7 +569,7 @@ class ChatScrollNavigator { void updateScrollDownVisible() { if (!scrollController.hasClients) { _setScrollDownVisible( - newMessageCount.value > 0 || chatController.hasNewer, + unreadBelow.value > 0 || chatController.hasNewer, ); return; } @@ -580,8 +580,8 @@ class ChatScrollNavigator { pos.userScrollDirection != ScrollDirection.idle) { _returnStack.clear(); } - if (atBottom && (newMessageCount.value > 0 || hasDeferredMessages())) { - clearNewMessageCountSoon(); + if (atBottom && (unreadBelow.value > 0 || hasDeferredMessages())) { + clearUnreadBelowSoon(); } final reveal = math.min( _scrollDownRevealExtent, @@ -591,7 +591,7 @@ class ChatScrollNavigator { distanceFromBottom() >= reveal || chatController.hasNewer || _returnStack.isNotEmpty || - newMessageCount.value > 0, + unreadBelow.value > 0, ); } @@ -605,19 +605,21 @@ class ChatScrollNavigator { } } - void noteMissedMessage() { - newMessageCount.value++; + void noteMissedMessage() => showUnreadBelow(unreadBelow.value + 1); + + void showUnreadBelow(int count) { + unreadBelow.value = count; updateScrollDownVisible(); } - void clearNewMessageCountSoon() { + void clearUnreadBelowSoon() { if (_clearCountScheduled) return; _clearCountScheduled = true; _afterFrame((_) { _clearCountScheduled = false; if (!isMounted() || !isNearBottom()) return; flushDeferredMessages(); - newMessageCount.value = 0; + unreadBelow.value = 0; updateScrollDownVisible(); }); } diff --git a/lib/frontend/screens/chats/chat/chat_text_send_controller.dart b/lib/frontend/screens/chats/chat/chat_text_send_controller.dart index e0425f4f..85c080b9 100644 --- a/lib/frontend/screens/chats/chat/chat_text_send_controller.dart +++ b/lib/frontend/screens/chats/chat/chat_text_send_controller.dart @@ -7,6 +7,8 @@ import '../../../../backend/modules/chats.dart'; import '../../../../backend/modules/comments.dart'; import '../../../../backend/modules/message_copy.dart'; import '../../../../backend/modules/messages.dart'; +import '../../../../backend/modules/outbox.dart'; +import '../../../../backend/modules/outgoing_reply.dart'; import '../../../../backend/modules/sent_message.dart'; import '../../../../core/config/app_commands.dart'; import '../../../../core/crypto/message_decryption_cache.dart'; @@ -116,6 +118,39 @@ class ChatTextSendController { replySourceChatId = null; } + bool canRetry(CachedMessage message) => + !commentsMode && + message.status == 'error' && + (message.attachments?.isEmpty ?? true) && + (message.text?.isNotEmpty ?? false); + + Future retry(CachedMessage failed) async { + if (!canRetry(failed)) return; + final accountId = _myId; + final chatId = _chatId; + if (!await AppDatabase.requeueFailedMessage(accountId, chatId, failed.id)) { + return; + } + final queued = failed.copyWith(status: 'pending'); + final index = chatController.indexOfId(failed.id); + if (index != -1 && isMounted()) { + chatController.setMessageAt(index, queued); + bumpMessages(); + } + MessageSessionCache.replace(accountId, chatId, failed.id, (_) => queued); + await chats.reconcileLastMessage(accountId, chatId); + unawaited(OutboxService.instance.flush()); + } + + OutgoingReply? takeReply() { + final reply = OutgoingReply.of( + replyTo.value, + sourceChatId: replySourceChatId, + ); + cancelReply(); + return reply; + } + void setForwardRequest(ForwardRequest request) { cancelReply(); pendingForward.value = request; @@ -359,38 +394,20 @@ class ChatTextSendController { final now = DateTime.now().millisecondsSinceEpoch; final online = _api.state == SessionState.online; - final reply = replyTo.value; - final int? replyId = reply == null ? null : int.tryParse(reply.id); - final int? replySrcChatId = replyId == null ? null : replySourceChatId; - Map? replyPayload; - if (reply != null && replyId != null) { - final sourceLink = reply.payload?['link']; - replyPayload = { - 'link': { - 'type': 'REPLY', - 'chatId': replySrcChatId ?? chatId, - 'message': { - 'id': replyId, - 'sender': reply.senderId, - 'text': reply.text, - 'time': reply.time, - 'attaches': reply.payload?['attaches'] ?? const [], - if (sourceLink is Map && sourceLink['type'] == 'FORWARD') - 'link': sourceLink, - }, - }, - }; - } - replyTo.value = null; - replySourceChatId = null; + final reply = takeReply(); + final replyId = reply?.messageId; + final replySrcChatId = reply?.sourceChatId; final elements = encrypted ? const >[] : trimmedElements(content.elements, rawText, text); final Map? composedPayload = - (replyPayload == null && elements.isEmpty) + (reply == null && elements.isEmpty) ? null - : {...?replyPayload, if (elements.isNotEmpty) 'elements': elements}; + : { + if (reply != null) 'link': reply.linkIn(chatId), + if (elements.isNotEmpty) 'elements': elements, + }; final composed = CachedMessage( id: tempId, diff --git a/lib/frontend/screens/chats/chat/composer_height.dart b/lib/frontend/screens/chats/chat/composer_height.dart new file mode 100644 index 00000000..695528fe --- /dev/null +++ b/lib/frontend/screens/chats/chat/composer_height.dart @@ -0,0 +1,38 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; + +import 'sticker_panel_controller.dart'; + +class ComposerHeight extends ChangeNotifier implements ValueListenable { + ComposerHeight(this._stickers, {double initial = 96}) + : _bar = initial, + _value = initial { + _stickers.layout.addListener(_sync); + } + + final StickerPanelController _stickers; + double _bar; + double _value; + + @override + double get value => _value; + + void measured(double height) { + _bar = height - _stickers.slotHeight; + _sync(); + } + + void _sync() { + final next = math.max(0.0, _bar + _stickers.slotHeight); + if (next == _value) return; + _value = next; + notifyListeners(); + } + + @override + void dispose() { + _stickers.layout.removeListener(_sync); + super.dispose(); + } +} diff --git a/lib/frontend/screens/chats/chat/sticker_panel_controller.dart b/lib/frontend/screens/chats/chat/sticker_panel_controller.dart index c9885508..cb82f33f 100644 --- a/lib/frontend/screens/chats/chat/sticker_panel_controller.dart +++ b/lib/frontend/screens/chats/chat/sticker_panel_controller.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'dart:ui' show lerpDouble; import 'package:flutter/widgets.dart'; @@ -54,6 +55,7 @@ class StickerPanelController { final ValueNotifier keyboardInset = ValueNotifier(0); double _baseHeight = _fallbackHeight; double maxHeight = _fallbackHeight; + double safeBottom = 0; bool _landscape = false; bool _yielding = false; Timer? _typingTimer; @@ -70,6 +72,10 @@ class StickerPanelController { double get visibleHeight => currentHeight * Curves.easeOutCubic.transform(anim.value.clamp(0.0, 1.0)); + double get slotHeight => math.max(safeBottom, visibleHeight); + + double get barBottomPadding => math.max(0, safeBottom - visibleHeight); + // #***! клавиатура была открыта: панель сразу во всю её высоту, клавиатура // уезжает поверх и открывает её void showInPlaceOfKeyboard(double keyboard) { diff --git a/lib/frontend/screens/chats/chat/view/channel_recommendations_view.dart b/lib/frontend/screens/chats/chat/view/channel_recommendations_view.dart new file mode 100644 index 00000000..cff5d2d0 --- /dev/null +++ b/lib/frontend/screens/chats/chat/view/channel_recommendations_view.dart @@ -0,0 +1,352 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import 'package:komet/core/config/app_motion.dart'; +import 'package:komet/core/config/komet_settings.dart'; +import 'package:komet/core/utils/format.dart'; +import 'package:komet/core/utils/haptics.dart'; +import 'package:komet/frontend/widgets/custom_notification.dart'; +import 'package:komet/frontend/widgets/hint_bubble.dart'; +import 'package:komet/frontend/widgets/komet_avatar.dart'; +import 'package:komet/frontend/widgets/max_link_handler.dart'; +import 'package:komet/frontend/widgets/small_spinner.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:komet/models/suggested_channel.dart'; + +import '../channel_recommendations.dart'; + +class ChannelRecommendationsView extends StatefulWidget { + const ChannelRecommendationsView({super.key, required this.recommendations}); + + final ChannelRecommendations recommendations; + + @override + State createState() => + _ChannelRecommendationsViewState(); +} + +class _ChannelRecommendationsViewState extends State + with SingleTickerProviderStateMixin { + static const Duration _showDuration = Duration(milliseconds: 320); + static const Duration _hideDuration = Duration(milliseconds: 260); + static const double _cardsHeight = 178; + + late final AnimationController _presence = AnimationController( + vsync: this, + duration: AppMotion.of(_showDuration), + reverseDuration: AppMotion.of(_hideDuration), + value: widget.recommendations.visible ? 1 : 0, + ); + late final CurvedAnimation _curve = CurvedAnimation( + parent: _presence, + curve: Curves.easeOutCubic, + reverseCurve: Curves.easeInCubic, + ); + + @override + void initState() { + super.initState(); + widget.recommendations.addListener(_syncPresence); + } + + @override + void didUpdateWidget(ChannelRecommendationsView oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.recommendations == widget.recommendations) return; + oldWidget.recommendations.removeListener(_syncPresence); + widget.recommendations.addListener(_syncPresence); + _syncPresence(); + } + + @override + void dispose() { + widget.recommendations.removeListener(_syncPresence); + _curve.dispose(); + _presence.dispose(); + super.dispose(); + } + + void _syncPresence() { + if (widget.recommendations.visible) { + _presence.forward(); + } else { + _presence.reverse(); + } + } + + void _hide() { + Haptics.tap(); + final l10n = AppLocalizations.of(context)!; + unawaited(widget.recommendations.hide()); + showCustomNotification( + context, + l10n.channelRecommendationsHidden, + action: ( + label: l10n.channelRecommendationsHideEverywhere, + onTap: () => + unawaited(KometSettings.setHideChannelRecommendations(true)), + ), + ); + } + + void _open(SuggestedChannel channel) { + unawaited(tryHandleMaxLink(context, channel.link)); + } + + Future _join(BuildContext button, SuggestedChannel channel) async { + Haptics.tap(); + try { + await widget.recommendations.join(channel); + } catch (_) { + if (!button.mounted) return; + showHintBubble( + button, + AppLocalizations.of(button)!.chatScreenSubscribeFailed, + ); + } + } + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: _presence, + builder: (context, child) => _presence.isDismissed + ? const SizedBox.shrink() + : SizeTransition( + sizeFactor: _curve, + alignment: Alignment.topCenter, + child: FadeTransition(opacity: _curve, child: child), + ), + child: ListenableBuilder( + listenable: widget.recommendations, + builder: (context, _) => _content(context), + ), + ); + } + + Widget _content(BuildContext context) { + final recommendations = widget.recommendations; + final channels = recommendations.channels; + if (channels.isEmpty) return const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _RecommendationsHeader(onHide: _hide), + SizedBox( + height: _cardsHeight, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8), + itemCount: channels.length, + separatorBuilder: (_, _) => const SizedBox(width: 8), + itemBuilder: (context, index) { + final channel = channels[index]; + return _SuggestedChannelCard( + key: ValueKey(channel.id), + channel: channel, + state: recommendations.stateOf(channel), + onOpen: () => _open(channel), + onJoin: (button) => unawaited(_join(button, channel)), + ); + }, + ), + ), + ], + ), + ); + } +} + +class _RecommendationsHeader extends StatelessWidget { + const _RecommendationsHeader({required this.onHide}); + + final VoidCallback onHide; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Center( + child: Container( + padding: const EdgeInsets.only(left: 12), + decoration: BoxDecoration( + color: cs.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + l10n.channelRecommendationsTitle, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12), + ), + Tooltip( + message: l10n.channelRecommendationsHide, + child: InkResponse( + onTap: onHide, + radius: 14, + child: Padding( + padding: const EdgeInsets.fromLTRB(6, 4, 8, 4), + child: Icon( + Symbols.close, + size: 14, + color: cs.onSurfaceVariant, + ), + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _SuggestedChannelCard extends StatelessWidget { + const _SuggestedChannelCard({ + super.key, + required this.channel, + required this.state, + required this.onOpen, + required this.onJoin, + }); + + static const double width = 136; + + final SuggestedChannel channel; + final SuggestedChannelState state; + final VoidCallback onOpen; + final void Function(BuildContext button) onJoin; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final dim = cs.onSurfaceVariant; + final subscribers = channel.subscribers; + return SizedBox( + width: width, + child: Material( + color: cs.surfaceContainerHighest, + borderRadius: BorderRadius.circular(20), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onOpen, + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 14, 10, 10), + child: Column( + children: [ + KometAvatar( + name: channel.title, + imageUrl: channel.iconUrl, + size: 60, + ), + const SizedBox(height: 10), + Text( + channel.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + if (subscribers != null) ...[ + const SizedBox(height: 2), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Symbols.person, size: 13, fill: 1, color: dim), + const SizedBox(width: 2), + Text( + formatCompactCount(subscribers), + style: TextStyle(color: dim, fontSize: 12), + ), + ], + ), + ], + const Spacer(), + Builder( + builder: (button) => _JoinButton( + state: state, + onJoin: () => onJoin(button), + onOpen: onOpen, + ), + ), + ], + ), + ), + ), + ), + ); + } +} + +class _JoinButton extends StatelessWidget { + const _JoinButton({ + required this.state, + required this.onJoin, + required this.onOpen, + }); + + final SuggestedChannelState state; + final VoidCallback onJoin; + final VoidCallback onOpen; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final style = TextStyle( + color: cs.onSurface, + fontSize: 13, + fontWeight: FontWeight.w500, + ); + return SizedBox( + height: 34, + width: double.infinity, + child: Material( + color: cs.onSurface.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(12), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: switch (state) { + SuggestedChannelState.idle => onJoin, + SuggestedChannelState.joining => null, + SuggestedChannelState.joined => onOpen, + }, + child: Center( + child: AnimatedSwitcher( + duration: AppMotion.of(const Duration(milliseconds: 180)), + child: switch (state) { + SuggestedChannelState.idle => Text( + l10n.chatInfoActionSubscribe, + key: const ValueKey('join'), + style: style, + ), + SuggestedChannelState.joining => SmallSpinner( + key: const ValueKey('joining'), + size: 18, + color: cs.onSurface, + ), + SuggestedChannelState.joined => Text( + l10n.chatPreviewOpen, + key: const ValueKey('open'), + style: style, + ), + }, + ), + ), + ), + ), + ); + } +} diff --git a/lib/frontend/screens/chats/chat/view/chat_app_bar.dart b/lib/frontend/screens/chats/chat/view/chat_app_bar.dart index a9f72e0b..6a2bb147 100644 --- a/lib/frontend/screens/chats/chat/view/chat_app_bar.dart +++ b/lib/frontend/screens/chats/chat/view/chat_app_bar.dart @@ -124,44 +124,45 @@ class ChatAppBar extends StatelessWidget implements PreferredSizeWidget { 0.0, 1.0, ); + final background = chrome == ChatChromeStyle.blur + ? FrostedPanel( + tint: AppFrost.blurPanelTint(cs), + border: Border(bottom: AppFrost.hairline(cs)), + backdropKey: barBackdrop, + child: const SizedBox.expand(), + ) + : (chromeVignette && !glossyChrome) + ? IgnorePointer( + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + cs.surface, + cs.surface, + cs.surface.withValues(alpha: 0.0), + ], + stops: [0.0, fadeStop, 1.0], + ), + ), + child: const SizedBox.expand(), + ), + ) + : (chrome == ChatChromeStyle.transparent && !glossyChrome) + ? FrostedPanel( + sigma: AppFrost.sigma, + tint: AppFrost.glassTint(cs), + border: Border(bottom: AppFrost.hairline(cs)), + backdropKey: barBackdrop, + child: const SizedBox.expand(), + ) + : null; return AppBar( backgroundColor: chrome == ChatChromeStyle.color ? (glossyChrome ? Colors.transparent : cs.surfaceContainerHigh) : Colors.transparent, - flexibleSpace: chrome == ChatChromeStyle.blur - ? FrostedPanel( - tint: AppFrost.blurPanelTint(cs), - border: Border(bottom: AppFrost.hairline(cs)), - backdropKey: barBackdrop, - child: const SizedBox.expand(), - ) - : (chromeVignette && !glossyChrome) - ? IgnorePointer( - child: DecoratedBox( - decoration: BoxDecoration( - gradient: LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [ - cs.surface, - cs.surface, - cs.surface.withValues(alpha: 0.0), - ], - stops: [0.0, fadeStop, 1.0], - ), - ), - child: const SizedBox.expand(), - ), - ) - : (chrome == ChatChromeStyle.transparent && !glossyChrome) - ? FrostedPanel( - sigma: AppFrost.sigma, - tint: AppFrost.glassTint(cs), - border: Border(bottom: AppFrost.hairline(cs)), - backdropKey: barBackdrop, - child: const SizedBox.expand(), - ) - : null, + flexibleSpace: background, foregroundColor: cs.onSurface, surfaceTintColor: Colors.transparent, iconTheme: IconThemeData(color: cs.onSurface), diff --git a/lib/frontend/screens/chats/chat/view/chat_body_layout.dart b/lib/frontend/screens/chats/chat/view/chat_body_layout.dart index 49270258..3db4f9c1 100644 --- a/lib/frontend/screens/chats/chat/view/chat_body_layout.dart +++ b/lib/frontend/screens/chats/chat/view/chat_body_layout.dart @@ -1,14 +1,17 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:komet/backend/modules/chats.dart' show CachedChat; import 'package:komet/core/config/app_chat_chrome.dart'; import 'package:komet/core/config/app_visual_style.dart'; -import 'package:komet/core/storage/chat_wallpaper_store.dart' show ChatWallpaper; +import 'package:komet/core/storage/chat_wallpaper_store.dart' + show ChatWallpaper; import 'package:komet/frontend/screens/chats/chat/command_panel_controller.dart'; import 'package:komet/frontend/screens/chats/chat/chat_search_controller.dart'; import 'package:komet/frontend/screens/chats/chat/mention_panel_controller.dart'; import 'package:komet/frontend/screens/chats/chat/video_note_controller.dart'; import 'package:komet/frontend/screens/chats/chat/message_search_result.dart'; import 'package:komet/frontend/widgets/chat_wallpaper_view.dart'; +import 'package:komet/frontend/widgets/seasonal_snow.dart'; import 'package:komet/frontend/widgets/toast_placement.dart'; import 'chat_call_banner.dart'; @@ -31,7 +34,8 @@ class ChatBodyLayout extends StatelessWidget { final VoidCallback? onUnpinCurrentMessage; final VoidCallback? onJoinCall; final bool composerFrosted; - final ValueNotifier composerHeight; + final ValueListenable composerHeight; + final ValueChanged onComposerMeasured; final ValueNotifier pinnedBannerHeight; final Widget Function(BuildContext) composerAreaBuilder; final Widget messagesArea; @@ -62,6 +66,7 @@ class ChatBodyLayout extends StatelessWidget { required this.onJoinCall, required this.composerFrosted, required this.composerHeight, + required this.onComposerMeasured, required this.pinnedBannerHeight, required this.composerAreaBuilder, required this.messagesArea, @@ -124,7 +129,7 @@ class ChatBodyLayout extends StatelessWidget { Widget build(BuildContext context) { final composer = ToastObstruction( child: MeasureSize( - onHeight: (value) => composerHeight.value = value, + onHeight: onComposerMeasured, child: Builder(builder: composerAreaBuilder), ), ); @@ -142,7 +147,10 @@ class ChatBodyLayout extends StatelessWidget { fit: StackFit.expand, children: [ if (wallpaper != null) - Positioned.fill(child: ChatWallpaperView(wallpaper: wallpaper!)), + Positioned.fill( + child: ChatWallpaperView(wallpaper: wallpaper!), + ), + const Positioned.fill(child: SeasonalSnowLayer()), Positioned.fill(child: messagesArea), ValueListenableBuilder( valueListenable: composerHeight, @@ -179,6 +187,7 @@ class ChatBodyLayout extends StatelessWidget { children: [ if (wallpaper != null) Positioned.fill(child: ChatWallpaperView(wallpaper: wallpaper!)), + const Positioned.fill(child: SeasonalSnowLayer()), Positioned.fill(child: messagesArea), SearchOverlay( cs: cs, diff --git a/lib/frontend/screens/chats/chat/view/composer_area.dart b/lib/frontend/screens/chats/chat/view/composer_area.dart index de6ac969..21bbc62e 100644 --- a/lib/frontend/screens/chats/chat/view/composer_area.dart +++ b/lib/frontend/screens/chats/chat/view/composer_area.dart @@ -20,6 +20,7 @@ import 'package:komet/frontend/screens/chats/chat/video_note_controller.dart'; import 'package:komet/frontend/screens/chats/chat/voice_record_controller.dart'; import 'package:komet/frontend/widgets/attachment_panel.dart'; import 'package:komet/frontend/widgets/e2ee_banner.dart'; +import 'package:komet/frontend/widgets/format_selection_toolbar.dart'; import 'package:komet/frontend/widgets/rich_message_controller.dart'; import 'package:komet/l10n/app_localizations.dart'; @@ -76,18 +77,6 @@ class ComposerArea extends StatelessWidget { final bool crossChatReplySupported; final Future Function() onPickReplyChat; final String Function(int ms) formatElapsed; - final Widget Function( - RichMessageController controller, - BuildContext context, - EditableTextState editableState, { - ContextMenuButtonItem? pasteItem, - }) - formatContextMenu; - final ContextMenuButtonItem? Function( - BuildContext context, - EditableTextState editableState, - ) - pasteMenuItem; final Future Function()? onPasteMedia; final Future Function(KeyboardInsertedContent content) onInsertContent; final bool isMuted; @@ -154,8 +143,6 @@ class ComposerArea extends StatelessWidget { required this.crossChatReplySupported, required this.onPickReplyChat, required this.formatElapsed, - required this.formatContextMenu, - required this.pasteMenuItem, required this.onPasteMedia, required this.onInsertContent, required this.isMuted, @@ -189,9 +176,16 @@ class ComposerArea extends StatelessWidget { ); } + VoidCallback? get _pasteMediaAction { + final paste = onPasteMedia; + if (paste == null || !ClipboardMedia.supported) return null; + return () => unawaited(paste()); + } + @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + stickers.safeBottom = MediaQuery.paddingOf(context).bottom; final content = Column( mainAxisSize: MainAxisSize.min, children: [ @@ -267,7 +261,7 @@ class ComposerArea extends StatelessWidget { builder: (context, _) => _withBotStart( context, ComposerInputBar( - bottomSafe: stickers.anim.value == 0, + bottomPadding: stickers.barBottomPadding, chatType: commentsMode ? 'CHAT' : chatType, chrome: chrome, vignette: chromeVignette, @@ -298,11 +292,10 @@ class ComposerArea extends StatelessWidget { ? null : () => unawaited(onPickReplyChat()), formatElapsed: formatElapsed, - contextMenuBuilder: (ctx, state) => formatContextMenu( - messageController, - ctx, - state, - pasteItem: pasteMenuItem(ctx, state), + contextMenuBuilder: (_, state) => FormatSelectionToolbar( + controller: messageController, + editableState: state, + onPasteMedia: _pasteMediaAction, ), onPasteMedia: ClipboardMedia.supported ? onPasteMedia diff --git a/lib/frontend/screens/chats/chat/view/composer_input.dart b/lib/frontend/screens/chats/chat/view/composer_input.dart index 58474bf4..e4b29541 100644 --- a/lib/frontend/screens/chats/chat/view/composer_input.dart +++ b/lib/frontend/screens/chats/chat/view/composer_input.dart @@ -19,6 +19,7 @@ import 'package:komet/frontend/widgets/composer_morph_icon.dart'; import 'package:komet/frontend/widgets/glossy_pill.dart'; import 'package:komet/frontend/widgets/liquid_glass.dart'; import 'package:komet/frontend/widgets/sender_badge.dart'; +import 'package:komet/frontend/widgets/selection_toolbar.dart'; import 'package:komet/frontend/widgets/lottie_slash_icon.dart'; import 'package:komet/frontend/widgets/paste_media_scope.dart'; import 'package:komet/frontend/widgets/reply_preview.dart'; @@ -70,7 +71,7 @@ class ComposerInputBar extends StatelessWidget { this.forceSend = false, this.readOnly = false, this.hintText, - this.bottomSafe = true, + required this.bottomPadding, this.vignette = false, }); @@ -116,7 +117,7 @@ class ComposerInputBar extends StatelessWidget { final bool forceSend; final bool readOnly; final String? hintText; - final bool bottomSafe; + final double bottomPadding; final bool vignette; @override @@ -159,7 +160,8 @@ class ComposerInputBar extends StatelessWidget { } final bar = SafeArea( - bottom: bottomSafe, + bottom: false, + minimum: EdgeInsets.only(bottom: bottomPadding), child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -553,7 +555,7 @@ class ComposerInputBar extends StatelessWidget { ), ); - return _barSurface(cs, bar); + return SelectionToolbarFloor(child: _barSurface(cs, bar)); } bool get _flat => !ComposerChrome.isGlossy(style); diff --git a/lib/frontend/screens/chats/chat/view/message_row_widgets.dart b/lib/frontend/screens/chats/chat/view/message_row_widgets.dart index d33d1504..314a91e3 100644 --- a/lib/frontend/screens/chats/chat/view/message_row_widgets.dart +++ b/lib/frontend/screens/chats/chat/view/message_row_widgets.dart @@ -28,6 +28,7 @@ import 'package:komet/frontend/widgets/reaction_picker.dart' show availableReactions; import 'package:komet/frontend/widgets/rich_message_controller.dart'; import 'package:komet/frontend/widgets/custom_notification.dart'; +import 'package:komet/frontend/widgets/format_selection_toolbar.dart'; import 'package:komet/frontend/widgets/selection_check_circle.dart'; import 'package:komet/frontend/widgets/small_spinner.dart'; import 'package:komet/frontend/widgets/sticker_pin.dart'; @@ -40,6 +41,9 @@ import 'package:komet/models/chat_reaction_settings.dart'; import '../message_media_draft.dart'; import 'edit_media_strip.dart'; +bool isFailedOutgoingMessage(CachedMessage message, int myId) => + message.senderId == myId && message.status == 'error'; + class PinnedMessageBanner extends StatelessWidget { final String? text; final bool isPreview; @@ -228,7 +232,8 @@ class _PinnedMessageTextState extends State { class SelectableMessageRow extends StatefulWidget { final Widget child; final CachedMessage message; - final bool isMe; + final bool outgoing; + final bool failedSend; final ValueListenable> selectedIds; final Animation selectionAnim; final bool Function() isSelectionActive; @@ -239,6 +244,7 @@ class SelectableMessageRow extends StatefulWidget { final VoidCallback onDelete; final bool allowDelete; final VoidCallback? onEdit; + final VoidCallback? onRetry; final VoidCallback? onReply; final VoidCallback? onForward; final bool allowCopy; @@ -262,7 +268,8 @@ class SelectableMessageRow extends StatefulWidget { super.key, required this.child, required this.message, - required this.isMe, + required this.outgoing, + this.failedSend = false, required this.selectedIds, required this.selectionAnim, required this.isSelectionActive, @@ -273,6 +280,7 @@ class SelectableMessageRow extends StatefulWidget { required this.onDelete, this.allowDelete = true, this.onEdit, + this.onRetry, this.onReply, this.onForward, this.allowCopy = true, @@ -303,6 +311,7 @@ class _SelectableMessageRowState extends State { final GlobalKey _boundaryKey = GlobalKey(); Offset? _lastTapDown; Timer? _openTimer; + bool _menuOpen = false; bool _isPinnedNow() => widget.isPinned(); @@ -338,9 +347,11 @@ class _SelectableMessageRowState extends State { } catch (_) { return; } + if (mounted) setState(() => _menuOpen = true); Haptics.tap(); + final failed = widget.failedSend; final controller = MessageActionsController(); final offers = _reactionFilter(); final stickerId = _stickerId; @@ -349,45 +360,50 @@ class _SelectableMessageRowState extends State { snapshot: snapshot, originRect: rect, tapPoint: _lastTapDown ?? rect.center, - isMe: widget.isMe, + outgoing: widget.outgoing, bottomReservedSpace: widget.composerHeight?.value ?? 0, messageText: widget.message.text, copyText: MessageDecryptionCache.instance.readableText(widget.message), controller: controller, style: AppMessageActionsStyle.effective, interaction: MessageActionsInteraction.tap, - editHistory: widget.message.editHistory, - infoRows: _infoRows(), - loadReadBy: widget.loadReadBy, - onReaderTap: widget.onReaderTap, - loadReportReasons: widget.loadReportReasons, - onReport: widget.onReport, + editHistory: failed ? null : widget.message.editHistory, + infoRows: failed ? null : _infoRows(), + loadReadBy: failed ? null : widget.loadReadBy, + onReaderTap: failed ? null : widget.onReaderTap, + loadReportReasons: failed ? null : widget.loadReportReasons, + onReport: failed ? null : widget.onReport, onDelete: widget.onDelete, allowDelete: widget.allowDelete, - onEdit: widget.onEdit, - onReply: widget.onReply, - onForward: widget.onForward, - allowCopy: widget.allowCopy, - onMarkUnread: widget.onMarkUnread, - onPin: widget.onPin, - onCopyLink: widget.onCopyLink, - onSave: widget.onSave, - onSaveAs: widget.onSaveAs, - isPinned: _isPinnedNow(), - onPinSticker: _pinStickerAction(stickerId), - isStickerPinned: _isStickerPinned(stickerId), - onReact: _reactionsOpen || _selectedReaction != null + onEdit: failed ? null : widget.onEdit, + onReply: failed ? null : widget.onReply, + onForward: failed ? null : widget.onForward, + allowCopy: !failed && widget.allowCopy, + onMarkUnread: failed ? null : widget.onMarkUnread, + onPin: failed ? null : widget.onPin, + onCopyLink: failed ? null : widget.onCopyLink, + onSave: failed ? null : widget.onSave, + onSaveAs: failed ? null : widget.onSaveAs, + isPinned: failed ? false : _isPinnedNow(), + onPinSticker: failed ? null : _pinStickerAction(stickerId), + isStickerPinned: !failed && _isStickerPinned(stickerId), + onReact: !failed && (_reactionsOpen || _selectedReaction != null) ? widget.onReact : null, - selectedReaction: _selectedReaction, - quickReactions: _offeredQuickReactions(offers), - loadReactionEmojis: () async { - await animojiModule.ensureLoaded(); - return availableReactions() - .where((reaction) => offers(reaction.emoji)) - .toList(); + selectedReaction: failed ? null : _selectedReaction, + quickReactions: failed ? const [] : _offeredQuickReactions(offers), + loadReactionEmojis: failed + ? null + : () async { + await animojiModule.ensureLoaded(); + return availableReactions() + .where((reaction) => offers(reaction.emoji)) + .toList(); + }, + onDispose: () { + controller.dispose(); + if (mounted && _menuOpen) setState(() => _menuOpen = false); }, - onDispose: controller.dispose, ); } @@ -404,7 +420,6 @@ class _SelectableMessageRowState extends State { String? get _selectedReaction => widget.reactions?.value?['yourReaction']?.toString(); - bool Function(String emoji) _reactionFilter() { final settings = _settings; if (settings == null) return (_) => true; @@ -447,47 +462,54 @@ class _SelectableMessageRowState extends State { final origin = renderObject.localToGlobal(Offset.zero); final rect = origin & renderObject.size; - + final failed = widget.failedSend; final controller = MessageActionsController(); final stickerId = _stickerId; showMessageActions( context: ctx, originRect: rect, tapPoint: details.globalPosition, - isMe: widget.isMe, + outgoing: widget.outgoing, bottomReservedSpace: widget.composerHeight?.value ?? 0, messageText: widget.message.text, copyText: MessageDecryptionCache.instance.readableText(widget.message), controller: controller, style: MessageActionsStyle.list, interaction: MessageActionsInteraction.click, - editHistory: widget.message.editHistory, - infoRows: _infoRows(), - loadReadBy: widget.loadReadBy, - onReaderTap: widget.onReaderTap, - loadReportReasons: widget.loadReportReasons, - onReport: widget.onReport, + editHistory: failed ? null : widget.message.editHistory, + infoRows: failed ? null : _infoRows(), + loadReadBy: failed ? null : widget.loadReadBy, + onReaderTap: failed ? null : widget.onReaderTap, + loadReportReasons: failed ? null : widget.loadReportReasons, + onReport: failed ? null : widget.onReport, onDelete: widget.onDelete, allowDelete: widget.allowDelete, - onEdit: widget.onEdit, - onReply: widget.onReply, - onForward: widget.onForward, - allowCopy: widget.allowCopy, - onMarkUnread: widget.onMarkUnread, - onPin: widget.onPin, - onCopyLink: widget.onCopyLink, - onSave: widget.onSave, - onSaveAs: widget.onSaveAs, - isPinned: _isPinnedNow(), - onPinSticker: _pinStickerAction(stickerId), - isStickerPinned: _isStickerPinned(stickerId), + onEdit: failed ? null : widget.onEdit, + onReply: failed ? null : widget.onReply, + onForward: failed ? null : widget.onForward, + allowCopy: !failed && widget.allowCopy, + onMarkUnread: failed ? null : widget.onMarkUnread, + onPin: failed ? null : widget.onPin, + onCopyLink: failed ? null : widget.onCopyLink, + onSave: failed ? null : widget.onSave, + onSaveAs: failed ? null : widget.onSaveAs, + isPinned: failed ? false : _isPinnedNow(), + onPinSticker: failed ? null : _pinStickerAction(stickerId), + isStickerPinned: !failed && _isStickerPinned(stickerId), onDispose: controller.dispose, ); } void _handleTap() { if (widget.isSelectionActive()) { - widget.onToggleSelection(); + if (!widget.failedSend) widget.onToggleSelection(); + return; + } + if (widget.failedSend) { + _openTimer?.cancel(); + _openTimer = Timer(const Duration(milliseconds: 200), () { + if (mounted && !widget.isSelectionActive()) _openMenu(); + }); return; } final emoji = accountModule.doubleTapReaction.value; @@ -523,6 +545,11 @@ class _SelectableMessageRowState extends State { void _handleLongPressStart(Offset globalPosition) { _textSelectionPress = false; + if (widget.failedSend) { + _lastTapDown = globalPosition; + _openMenu(); + return; + } if (!widget.isSelectionActive()) { widget.onEnterSelection(); return; @@ -553,6 +580,49 @@ class _SelectableMessageRowState extends State { builder: (context, selected, _) { final isSelected = selected.contains(widget.message.id); final active = selected.isNotEmpty; + final messageChild = Padding( + padding: EdgeInsets.only(left: _gutterWidth * t), + child: widget.child, + ); + final sourceChild = widget.failedSend && widget.onRetry != null + ? Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + messageChild, + Padding( + padding: const EdgeInsetsDirectional.only( + end: 12, + top: 4, + bottom: 2, + ), + child: TextButton.icon( + key: ValueKey( + 'failed-message-retry-${widget.message.id}', + ), + onPressed: widget.onRetry, + icon: const Icon(Symbols.refresh, size: 17), + label: Text( + AppLocalizations.of(context)!.msgActionsRetry, + ), + style: TextButton.styleFrom( + foregroundColor: cs.error, + minimumSize: Size.zero, + padding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 6, + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + textStyle: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ) + : messageChild; return GestureDetector( behavior: HitTestBehavior.opaque, @@ -572,11 +642,14 @@ class _SelectableMessageRowState extends State { children: [ RepaintBoundary( key: _boundaryKey, - child: IgnorePointer( - ignoring: active, - child: Padding( - padding: EdgeInsets.only(left: _gutterWidth * t), - child: widget.child, + child: Opacity( + key: ValueKey( + 'message-actions-source-${widget.message.id}', + ), + opacity: _menuOpen ? 0 : 1, + child: IgnorePointer( + ignoring: active, + child: sourceChild, ), ), ), @@ -705,18 +778,11 @@ class EditMessageSheet extends StatefulWidget { final String text; final Iterable formatRanges; final List? photos; - final Widget Function( - RichMessageController controller, - BuildContext context, - EditableTextState editableState, - ) - contextMenuBuilder; const EditMessageSheet({ super.key, required this.text, required this.formatRanges, - required this.contextMenuBuilder, this.photos, }); @@ -815,8 +881,10 @@ class _EditMessageSheetState extends State { maxLines: 6, textCapitalization: TextCapitalization.sentences, style: TextStyle(color: cs.onSurface), - contextMenuBuilder: (ctx, state) => - widget.contextMenuBuilder(_controller, ctx, state), + contextMenuBuilder: (_, state) => FormatSelectionToolbar( + controller: _controller, + editableState: state, + ), decoration: InputDecoration( hintText: media == null ? l10n.scheduledMessageTextHint diff --git a/lib/frontend/screens/chats/chat/view/scroll_down_button.dart b/lib/frontend/screens/chats/chat/view/scroll_down_button.dart index 72ae950e..45459257 100644 --- a/lib/frontend/screens/chats/chat/view/scroll_down_button.dart +++ b/lib/frontend/screens/chats/chat/view/scroll_down_button.dart @@ -15,7 +15,7 @@ class ScrollDownButton extends StatelessWidget { final bool liquidChrome; final BackdropKey? pillBackdrop; final Animation scrollDownCurved; - final ValueListenable newMessageCount; + final ValueListenable unreadBelow; final VoidCallback onTap; static const double _scrollDownSize = 46.0; @@ -30,7 +30,7 @@ class ScrollDownButton extends StatelessWidget { required this.liquidChrome, required this.pillBackdrop, required this.scrollDownCurved, - required this.newMessageCount, + required this.unreadBelow, required this.onTap, }); @@ -83,7 +83,7 @@ class ScrollDownButton extends StatelessWidget { top: -5, right: -3, child: ValueListenableBuilder( - valueListenable: newMessageCount, + valueListenable: unreadBelow, builder: (context, count, _) => count <= 0 ? const SizedBox.shrink() : AnimatedValueSwap( diff --git a/lib/frontend/screens/chats/chat_folders_sheet.dart b/lib/frontend/screens/chats/chat_folders_sheet.dart new file mode 100644 index 00000000..4b15ec10 --- /dev/null +++ b/lib/frontend/screens/chats/chat_folders_sheet.dart @@ -0,0 +1,284 @@ +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../../backend/models/chat_folder.dart'; +import '../../../backend/modules/folders.dart'; +import '../../../core/protocol/packet.dart'; +import '../../../core/storage/token_storage.dart'; +import '../../../core/utils/haptics.dart'; +import '../../../l10n/app_localizations.dart'; +import '../../../main.dart'; +import '../../widgets/custom_notification.dart'; +import '../../widgets/sheet_helpers.dart'; +import '../../widgets/small_spinner.dart'; +import 'folder_edit_sheet.dart'; + +Future showChatFoldersSheet( + BuildContext context, { + required List chatIds, +}) async { + if (chatIds.isEmpty) return; + final cs = Theme.of(context).colorScheme; + final createNew = await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: cs.surfaceContainerHigh, + shape: kSheetShape, + builder: (_) => _ChatFoldersSheet(chatIds: chatIds), + ); + if (createNew != true || !context.mounted) return; + await showFolderEditSheet(context, initialChatIds: chatIds); +} + +enum _Membership { none, some, all } + +class _ChatFoldersSheet extends StatefulWidget { + final List chatIds; + + const _ChatFoldersSheet({required this.chatIds}); + + @override + State<_ChatFoldersSheet> createState() => _ChatFoldersSheetState(); +} + +class _ChatFoldersSheetState extends State<_ChatFoldersSheet> { + int? _accountId; + List _folders = const []; + bool _loading = true; + final Set _busy = {}; + + @override + void initState() { + super.initState(); + FoldersModule.revision.addListener(_load); + _load(); + } + + @override + void dispose() { + FoldersModule.revision.removeListener(_load); + super.dispose(); + } + + Future _load() async { + final accountId = _accountId ?? await TokenStorage.getActiveAccountId(); + if (accountId == null) { + if (mounted) setState(() => _loading = false); + return; + } + final folders = await FoldersModule.loadFolders(accountId); + if (!mounted) return; + setState(() { + _accountId = accountId; + _folders = [ + for (final folder in folders) + if (!FoldersModule.isAllChatsFolder(folder) && folder.canEditFilters) + folder, + ]; + _loading = false; + }); + } + + _Membership _membershipIn(ChatFolder folder) { + final included = widget.chatIds.where(folder.include.contains).length; + if (included == 0) return _Membership.none; + return included == widget.chatIds.length + ? _Membership.all + : _Membership.some; + } + + Future _toggle(ChatFolder folder) async { + final accountId = _accountId; + if (accountId == null || _busy.contains(folder.id)) return; + final add = _membershipIn(folder) != _Membership.all; + final include = add + ? [ + ...folder.include, + for (final id in widget.chatIds) + if (!folder.include.contains(id)) id, + ] + : [ + for (final id in folder.include) + if (!widget.chatIds.contains(id)) id, + ]; + setState(() => _busy.add(folder.id)); + Haptics.selection(); + try { + await FoldersModule.updateFolder( + api, + accountId, + folder, + include: include, + ); + } catch (e) { + Haptics.error(); + if (mounted) { + showCustomNotification( + context, + e is PacketError + ? e.message + : AppLocalizations.of( + context, + )!.chatFoldersUpdateFailed(folder.title), + ); + } + } finally { + if (mounted) setState(() => _busy.remove(folder.id)); + } + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final maxHeight = MediaQuery.sizeOf(context).height * 0.7; + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxHeight), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SheetGrabber(), + Padding( + padding: const EdgeInsets.fromLTRB(24, 6, 24, 10), + child: Text( + l10n.chatFoldersAddTo, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 17, + fontWeight: FontWeight.w600, + ), + ), + ), + if (_loading) + const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: SmallSpinner(), + ) + else + Flexible( + child: ListView( + shrinkWrap: true, + children: [ + for (final folder in _folders) + _FolderRow( + key: ValueKey(folder.id), + title: _folderLabel(folder), + membership: _membershipIn(folder), + busy: _busy.contains(folder.id), + onTap: () => _toggle(folder), + ), + _NewFolderRow( + label: l10n.folderActionNewFolder, + onTap: () => Navigator.pop(context, true), + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ), + ), + ); + } + + static String _folderLabel(ChatFolder folder) { + final emoji = folder.emoji; + if (emoji == null || emoji.isEmpty) return folder.title; + return '$emoji ${folder.title}'; + } +} + +class _FolderRow extends StatelessWidget { + final String title; + final _Membership membership; + final bool busy; + final VoidCallback onTap; + + const _FolderRow({ + super.key, + required this.title, + required this.membership, + required this.busy, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return InkWell( + onTap: busy ? null : onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 6), + child: Row( + children: [ + Icon(Symbols.folder, color: cs.onSurface, size: 22), + const SizedBox(width: 16), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurface, + fontSize: 15, + fontWeight: FontWeight.w500, + ), + ), + ), + SizedBox( + width: 48, + height: 48, + child: Center( + child: busy + ? const SmallSpinner(size: 20) + : Checkbox( + tristate: true, + value: switch (membership) { + _Membership.none => false, + _Membership.some => null, + _Membership.all => true, + }, + onChanged: (_) => onTap(), + ), + ), + ), + ], + ), + ), + ); + } +} + +class _NewFolderRow extends StatelessWidget { + final String label; + final VoidCallback onTap; + + const _NewFolderRow({required this.label, required this.onTap}); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), + child: Row( + children: [ + Icon(Symbols.create_new_folder, color: cs.primary, size: 22), + const SizedBox(width: 16), + Text( + label, + style: TextStyle( + color: cs.primary, + fontSize: 15, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/frontend/screens/chats/chat_info_screen.dart b/lib/frontend/screens/chats/chat_info_screen.dart index 45b35861..658f4dee 100644 --- a/lib/frontend/screens/chats/chat_info_screen.dart +++ b/lib/frontend/screens/chats/chat_info_screen.dart @@ -55,6 +55,7 @@ import '../stories/story_owner_info.dart'; import '../stories/story_peanut.dart'; import '../stories/story_ring.dart'; import '../stories/story_viewer_screen.dart'; +import 'chat_folders_sheet.dart'; import 'chat_screen.dart'; import 'group_invite_sheets.dart'; import 'join_requests_screen.dart'; @@ -506,7 +507,10 @@ class _ChatInfoScreenState extends State static const double _headerCollapsedBody = 232; static const double _headerVignette = 64; - bool get _headerHasPhoto => _chatImageUrl.isNotEmpty && !_peerDeleted; + bool get _isSavedMessages => widget.chatId == 0; + + bool get _headerHasPhoto => + !_isSavedMessages && _chatImageUrl.isNotEmpty && !_peerDeleted; Widget _buildScrollBody(ColorScheme cs) { return LayoutBuilder( @@ -850,7 +854,11 @@ class _ChatInfoScreenState extends State ), ), Offstage( - offstage: local != null || t < 0.5 || _avatarPages.length < 2, + offstage: + _isSavedMessages || + local != null || + t < 0.5 || + _avatarPages.length < 2, child: ClipRRect( borderRadius: BorderRadius.circular(radius), child: _avatarPager(cs, t), @@ -863,7 +871,8 @@ class _ChatInfoScreenState extends State ); } - int get _localAvatarUserId => widget.chatType == 'DIALOG' && !_peerDeleted + int get _localAvatarUserId => + widget.chatType == 'DIALOG' && !_peerDeleted && !_isSavedMessages ? (_otherId ?? widget.dialogPeerId ?? 0) : 0; @@ -1010,6 +1019,19 @@ class _ChatInfoScreenState extends State } Widget _headerAvatarContent(ColorScheme cs) { + if (_isSavedMessages) { + return ColoredBox( + color: cs.primary, + child: Center( + child: Icon( + Symbols.bookmark, + fill: 1, + color: cs.onPrimary, + size: _headerAvatarSize * 0.42, + ), + ), + ); + } if (_peerDeleted) { return _ghostAvatar(radius: _headerAvatarSize / 2, fontSize: 52); } @@ -1178,6 +1200,15 @@ class _ChatInfoScreenState extends State } } + if (widget.chatId != 0) { + entries.add(( + icon: Symbols.drive_file_move, + label: l10n.chatFoldersAddTo, + destructive: false, + onTap: () => showChatFoldersSheet(context, chatIds: [widget.chatId]), + )); + } + if (widget.chatType == 'DIALOG') { if (_isContact) { entries.add(( @@ -1188,6 +1219,13 @@ class _ChatInfoScreenState extends State )); } if (!_isBot && _otherId != null && _otherId != _myId) { + final storiesHidden = storiesModule.isAuthorHidden(_otherId!); + entries.add(( + icon: storiesHidden ? Symbols.visibility : Symbols.visibility_off, + label: storiesHidden ? l10n.storyMenuShow : l10n.storyMenuHide, + destructive: false, + onTap: () => _setStoriesHidden(_otherId!, !storiesHidden), + )); entries.add(( icon: _blocked ? Symbols.lock_open : Symbols.block, label: _blocked ? l10n.chatInfoMenuUnblock : l10n.chatInfoMenuBlock, @@ -1724,6 +1762,20 @@ class _ChatInfoScreenState extends State Navigator.of(context).popUntil((route) => route.isFirst); } + Future _setStoriesHidden(int ownerId, bool hidden) async { + final ok = await storiesModule.setAuthorHidden(ownerId, hidden); + if (!mounted) return; + showCustomNotification( + context, + switch ((hidden, ok)) { + (true, true) => l10n.storyHiddenNotice, + (true, false) => l10n.storyHideFailed, + (false, true) => l10n.storyShownNotice, + (false, false) => l10n.storyShowFailed, + }, + ); + } + Future _toggleBlock() async { final peerId = _otherId; if (peerId == null) return; diff --git a/lib/frontend/screens/chats/chat_list_screen.dart b/lib/frontend/screens/chats/chat_list_screen.dart index 6a821bf6..4e02227d 100644 --- a/lib/frontend/screens/chats/chat_list_screen.dart +++ b/lib/frontend/screens/chats/chat_list_screen.dart @@ -9,6 +9,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart' show ScrollCacheExtent; import 'package:flutter/scheduler.dart'; +import 'chat_folders_sheet.dart'; import 'chat_preview_card.dart'; import 'chat_screen.dart'; import 'search_screen.dart'; @@ -38,6 +39,7 @@ import '../../widgets/compact_bottom_navigation_bar.dart'; import '../../widgets/springy_tap.dart'; import '../../widgets/visible_page_tickers.dart'; import '../../widgets/informer_banner_tile.dart'; +import '../../widgets/whats_new_sheet.dart'; import '../../../backend/modules/forward_sender.dart'; import '../../../backend/modules/share_sender.dart'; import '../../widgets/lottie_slash_icon.dart'; @@ -74,6 +76,8 @@ import '../../../core/protocol/opcode_map.dart'; import '../../../core/protocol/packet.dart'; import '../../../core/utils/haptics.dart'; import '../../../core/config/build_profile.dart'; +import '../../../core/config/whats_new.dart'; +import '../../../core/config/app_motion.dart'; import '../../../core/config/app_animations.dart'; import '../../../core/config/app_frost.dart'; import '../../../core/config/app_spectrum_background.dart'; @@ -83,6 +87,7 @@ import '../../../core/cache/info_cache.dart'; import '../../../core/cache/official_options.dart'; import '../../../core/config/app_visual_style.dart'; import '../../../core/config/app_stories.dart'; +import '../../../core/whats_new/spotlight_ids.dart'; import '../../../core/config/app_colors.dart'; import '../../../core/config/komet_settings.dart'; import '../../../backend/models/chat_folder.dart'; @@ -128,6 +133,7 @@ import '../../../core/config/app_fonts.dart'; import '../lock/lock_glyph.dart'; import '../../../core/security/app_lock.dart'; import '../../widgets/verified_mark.dart'; +import '../../widgets/seasonal_snow.dart'; const String _savedWelcomeKey = 'welcome.saved.dialog.message'; @@ -298,14 +304,27 @@ class _ChatListScreenState extends State int _currentNavIndex = 0; List _chatsNavItems(AppLocalizations l10n) => [ - PillNavItem(icon: Symbols.chat_bubble, label: l10n.chatListNavChats), - PillNavItem(icon: Symbols.call, label: l10n.chatListNavCalls), - PillNavItem(icon: Symbols.person_pin, label: l10n.chatListNavContacts), + PillNavItem( + icon: Symbols.chat_bubble, + label: l10n.chatListNavChats, + spotlightId: SpotlightIds.navChats, + ), + PillNavItem( + icon: Symbols.call, + label: l10n.chatListNavCalls, + spotlightId: SpotlightIds.navCalls, + ), + PillNavItem( + icon: Symbols.person_pin, + label: l10n.chatListNavContacts, + spotlightId: SpotlightIds.navContacts, + ), PillNavItem( icon: Symbols.settings, label: l10n.attachSheetSettings, longPressable: true, animationAsset: AppAnimations.settings, + spotlightId: SpotlightIds.navSettings, ), ]; @@ -341,6 +360,7 @@ class _ChatListScreenState extends State bool _isFabOpen = false; bool _storiesAnimClosing = false; Timer? _contactRebuildTimer; + Timer? _dayRolloverTimer; bool _deferReloads = false; bool _reloadQueued = false; bool _reloadInFlight = false; @@ -877,6 +897,13 @@ class _ChatListScreenState extends State _clearSelection(); } + Future _onAddToFolderTap() async { + final chatIds = _selectedChatObjects().map((c) => c.id).toList(); + if (chatIds.isEmpty) return; + _clearSelection(); + await showChatFoldersSheet(context, chatIds: chatIds); + } + Future _onMuteTap() async { final selected = _selectedChatObjects(); if (selected.isEmpty) return; @@ -1201,6 +1228,7 @@ class _ChatListScreenState extends State ChatListScreen._root = this; } _initShare(); + _scheduleDayRollover(); _fabController = AnimationController( vsync: this, duration: const Duration(milliseconds: 350), @@ -1735,6 +1763,16 @@ class _ChatListScreenState extends State } } + void _scheduleDayRollover() { + final now = DateTime.now(); + final nextMidnight = DateTime(now.year, now.month, now.day + 1); + _dayRolloverTimer = Timer(nextMidnight.difference(now), () { + if (!mounted) return; + setState(() => _tilesRevision++); + _scheduleDayRollover(); + }); + } + void _scheduleContactRebuild() { if (!mounted) return; _contactRebuildTimer?.cancel(); @@ -1913,7 +1951,10 @@ class _ChatListScreenState extends State String _formatTime(int? timestamp) { if (timestamp == null || timestamp == 0) return ''; - return formatClock(DateTime.fromMillisecondsSinceEpoch(timestamp)); + return formatChatListStamp( + AppLocalizations.of(context)!, + DateTime.fromMillisecondsSinceEpoch(timestamp), + ); } void _onStoriesRevealTick() { @@ -2133,6 +2174,7 @@ class _ChatListScreenState extends State c.dispose(); } _contactRebuildTimer?.cancel(); + _dayRolloverTimer?.cancel(); _storiesUi.dispose(); _navDragDx.dispose(); super.dispose(); @@ -2156,6 +2198,24 @@ class _ChatListScreenState extends State return _currentNavIndex.toDouble(); } + double _navPageShift(int index, double position) { + final from = _navPageAnimStart.round(); + final to = _navPageAnimEnd.round(); + final skipsTabs = + !_navDragging && + _navPageAnimController.isAnimating && + (to - from).abs() > 1; + if (!skipsTabs) return index - position; + final progress = + ((position - _navPageAnimStart) / + (_navPageAnimEnd - _navPageAnimStart)) + .clamp(0.0, 1.0); + final direction = (to - from).sign.toDouble(); + if (index == from) return -progress * direction; + if (index == to) return (1 - progress) * direction; + return index < from ? -2.0 : 2.0; + } + void _onNavTabSelected(int index) { if (index == _currentNavIndex && !_navPageAnimController.isAnimating) { return; @@ -2172,7 +2232,11 @@ class _ChatListScreenState extends State _navPageAnimEnd = index.toDouble(); setState(() => _currentNavIndex = index); activeNavTab.value = index; - _navPageAnimController.forward(from: 0); + if (AppMotion.enabled.value) { + _navPageAnimController.forward(from: 0); + } else { + _navPageAnimController.value = 1.0; + } if (index == 0) _scheduleInformerPresentation(); } @@ -2268,32 +2332,61 @@ class _ChatListScreenState extends State } } + Future _openWhatsNew(String version) { + Haptics.tap(); + return showWhatsNewSheet(context, version); + } + + Widget _buildWhatsNewBanner(String version) { + final l10n = AppLocalizations.of(context)!; + final banner = InformerBanner( + id: 'whats-new-$version', + title: l10n.whatsNewBannerTitle(version), + description: l10n.whatsNewBannerSubtitle, + ); + return InformerBannerTile( + key: ValueKey(banner.id), + banner: banner, + onTap: () => unawaited(_openWhatsNew(version)), + onClose: () => unawaited(WhatsNew.dismiss()), + ); + } + Widget _buildInformerBanner() { - return ValueListenableBuilder( - valueListenable: bannersModule.activeBanner, - builder: (context, banner, _) { - return ClipRect( - child: AnimatedSize( - duration: const Duration(milliseconds: 260), - curve: Curves.easeOutCubic, - alignment: Alignment.topCenter, - child: banner == null - ? const SizedBox(width: double.infinity) - : InformerBannerTile( - key: ValueKey(banner.id), - banner: banner, - animojiLoader: animojiModule.fetchById, - onPresented: _markInformerPresented, - onTap: banner.isClickable - ? () => unawaited(_openInformer(banner)) - : null, - onClose: banner.hidesCloseButton - ? null - : () => unawaited(_closeInformer(banner)), - ), + return ValueListenableBuilder( + valueListenable: WhatsNew.pendingVersion, + builder: (context, whatsNew, _) => + ValueListenableBuilder( + valueListenable: bannersModule.activeBanner, + builder: (context, banner, _) { + return ClipRect( + child: AnimatedSize( + duration: const Duration(milliseconds: 260), + curve: Curves.easeOutCubic, + alignment: Alignment.topCenter, + child: whatsNew != null + ? _buildWhatsNewBanner(whatsNew) + : banner == null + ? const SizedBox(width: double.infinity) + : InformerBannerTile( + key: ValueKey(banner.id), + banner: banner, + animojiLoader: animojiModule.fetchById, + note: AppLocalizations.of( + context, + )!.informerBannerServerNote, + onPresented: _markInformerPresented, + onTap: banner.isClickable + ? () => unawaited(_openInformer(banner)) + : null, + onClose: banner.hidesCloseButton + ? null + : () => unawaited(_closeInformer(banner)), + ), + ), + ); + }, ), - ); - }, ); } @@ -2305,6 +2398,19 @@ class _ChatListScreenState extends State mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const SizedBox( + height: 0, + child: OverflowBox( + alignment: Alignment.topCenter, + minHeight: 220, + maxHeight: 220, + child: SeasonalSnowLayer( + flakeCount: 12, + seed: 1203, + opacity: 0.72, + ), + ), + ), ListenableBuilder( listenable: _storiesUi, builder: (context, _) => ClipRect( @@ -3129,38 +3235,26 @@ class _ChatListScreenState extends State child: SizedBox( width: pageW, height: pageH, - child: OverflowBox( - alignment: Alignment.topLeft, - maxWidth: pageW * 4, - maxHeight: pageH, - child: SizedBox( - width: pageW * 4, - height: pageH, - child: AnimatedBuilder( - animation: Listenable.merge([ - _navPageAnimController, - _navDragDx, - ]), - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - page(0, _getChatsBody(context)), - for (var i = 1; i <= 3; i++) - page(i, _navTab(i, contentBottomPadding)), - ], - ), - builder: (context, child) { - final pageDisplayT = _effectivePageNavRowT( - inactiveWidth: inactiveWidth, - bubbleLeftForIndex: bubbleLeftForPageT, - ); - return Transform.translate( - offset: Offset(-pageDisplayT * pageW, 0), + child: Stack( + children: [ + for (var i = 0; i <= 3; i++) + AnimatedBuilder( + animation: pageMotion, + child: page( + i, + i == 0 + ? _getChatsBody(context) + : _navTab(i, contentBottomPadding), + ), + builder: (context, child) => Transform.translate( + offset: Offset( + _navPageShift(i, pagePosition()) * pageW, + 0, + ), child: child, - ); - }, - ), - ), + ), + ), + ], ), ), ), @@ -3251,8 +3345,10 @@ class _ChatListScreenState extends State NavPillMaterial.isFrost(navStyle); return GlossyPill( onTap: _toggleFab, - color: frost || liquid + color: liquid ? AppFrost.glassTint(cs) + : frost + ? AppFrost.controlTint(cs) : cs.primaryContainer, blurSigma: frost ? AppFrost.sigma @@ -3519,6 +3615,11 @@ class _ChatListScreenState extends State ), onPressed: selected.isEmpty ? null : _onPinTap, ), + IconButton( + icon: Icon(Symbols.drive_file_move, color: cs.onSurface), + tooltip: AppLocalizations.of(context)!.chatFoldersAddTo, + onPressed: selected.isEmpty ? null : _onAddToFolderTap, + ), IconButton( icon: Icon( anyMuted ? Symbols.volume_up : Symbols.volume_off, @@ -4263,9 +4364,10 @@ class _ChatListScreenState extends State ), const SizedBox(width: 12), Expanded( - child: SizedBox( - height: 48, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 48), child: Column( + mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( @@ -4630,6 +4732,7 @@ class _ChatListScreenState extends State final record = await pushSwipeable( context, (_) => const DownloadsScreen(), + settings: const RouteSettings(name: DownloadsScreen.routeName), ); if (record == null || !mounted) return; await _openDownloadedMessage(record); diff --git a/lib/frontend/screens/chats/chat_screen.dart b/lib/frontend/screens/chats/chat_screen.dart index 0d9a03c1..01866c29 100644 --- a/lib/frontend/screens/chats/chat_screen.dart +++ b/lib/frontend/screens/chats/chat_screen.dart @@ -9,6 +9,8 @@ import 'package:path_provider/path_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; +import 'package:komet/backend/modules/channel_stats.dart'; +import 'package:komet/backend/modules/channel_suggestions.dart'; import 'package:komet/backend/modules/chat_preview.dart'; import 'package:komet/backend/modules/chats.dart'; import 'package:komet/backend/modules/comments.dart'; @@ -19,7 +21,6 @@ import 'package:komet/frontend/screens/webapp/web_app_bridge.dart' show WebAppEntryPoint; import 'package:komet/core/media/clipboard/clipboard_media.dart'; import 'package:komet/core/media/clipboard/pasted_attachment.dart'; -import 'package:komet/frontend/widgets/paste_media_toolbar.dart'; import 'package:komet/core/media/gallery_source.dart'; import 'package:komet/core/utils/format.dart'; import 'package:komet/frontend/screens/chats/chat_info_screen.dart'; @@ -72,7 +73,6 @@ import '../../../core/utils/logger.dart'; import '../../../core/utils/route_settle.dart'; import '../../../core/config/app_cache_extent.dart'; import '../../../core/config/app_swipe_back_desktop.dart'; -import '../../../core/config/app_unchecked_links.dart'; import 'chat/chat_prank_controller.dart'; import 'chat/chat_controller.dart'; import 'chat/message_flight.dart'; @@ -83,6 +83,11 @@ import 'chat/voice_record_controller.dart'; import 'chat/video_note_controller.dart'; import 'chat/command_panel_controller.dart'; import 'chat/sticker_panel_controller.dart'; +import 'chat/composer_height.dart'; +import 'chat/channel_recommendations.dart'; +import 'chat/channel_views.dart'; +import 'chat/view/channel_recommendations_view.dart'; +import '../../widgets/theme_wallpaper.dart'; import 'chat/chat_search_controller.dart'; import 'chat/message_search_result.dart'; import 'chat/typing_label.dart'; @@ -115,8 +120,6 @@ import '../../../models/contact_info.dart'; import '../../commands/commands.dart'; import '../../widgets/confirm_dialog.dart'; import '../../widgets/rich_message_controller.dart'; -import '../../widgets/link_text.dart'; -import '../../widgets/prompt_dialog.dart'; import '../../../core/utils/text_format.dart'; import '../../widgets/call_link_handler.dart'; import '../../widgets/direct_call.dart'; @@ -265,6 +268,7 @@ class _ChatScreenState extends State int _historyAutoloadSuppressCount = 0; bool get _historyAutoloadSuppressed => _historyAutoloadSuppressCount > 0; int _readMarkTime = 0; + int _unreadAfterMark = 0; late final ReadMarkerGate _readMarker = ReadMarkerGate( onFlush: _updateReadMarker, ); @@ -654,7 +658,9 @@ class _ChatScreenState extends State bool get _chromeVignette => _effectiveChrome == ChatChromeStyle.none && _wallpaper == null; - final ValueNotifier _composerHeight = ValueNotifier(96); + late final ComposerHeight _composerHeight; + ChannelRecommendations? _recommendations; + ChannelViews? _channelViewsStore; final ValueNotifier _pinnedBannerHeight = ValueNotifier(0); final ValueNotifier _floatingDate = ValueNotifier(null); @@ -715,6 +721,7 @@ class _ChatScreenState extends State encryptOutgoing: _encryptOutgoing, markHasScheduled: _markHasScheduled, confirmSend: _confirmSend, + takeReply: () => _commentsMode ? null : _textSend.takeReply(), ); if (!_commentsMode && !widget.preview) ChatScreen._open.add(this); if (!widget.preview) { @@ -765,6 +772,22 @@ class _ChatScreenState extends State onSendTyping: () => messagesModule.sendTyping(widget.chatId, 'STICKER'), softKeyboard: !isDesktopPlatform, ); + _composerHeight = ComposerHeight(_stickers); + if (_channelFeed) { + _recommendations = ChannelRecommendations( + chatId: widget.chatId, + fetch: () => ChannelSuggestions.forChannel( + api, + widget.chatId, + accountId: _myId, + ownChannelIds: chats + .chatsSnapshot() + .where((chat) => chat.type == 'CHANNEL') + .map((chat) => chat.id), + ), + join: (channel) => chats.joinChannel(api, channel.link, _myId), + ); + } _showAttachmentPanel.addListener(_onAttachPanelToggle); _commandPanel = CommandPanelController( vsync: this, @@ -1087,6 +1110,7 @@ class _ChatScreenState extends State void _resolveUnreadAnchor() { final c = chat; _readMarkTime = c?.participants[_myId] ?? 0; + _unreadAfterMark = c?.unreadCount ?? 0; final unread = c != null && c.unreadCount > 0; if (!unread) { _unreadAnchorTime = null; @@ -1146,6 +1170,7 @@ class _ChatScreenState extends State } _routeSettle.run(_kickoffHistory); _routeSettle.run(() => _routeSettled.value = true); + _routeSettle.run(() => unawaited(_recommendations?.load())); } Future>? _localHistoryLoad; @@ -1295,7 +1320,9 @@ class _ChatScreenState extends State WidgetsBinding.instance.addPostFrameCallback((_) async { if (!mounted) return; await _scrollNav.positionAt(messageId, _unreadAnchorAlignment()); - if (mounted) setState(_markPositioned); + if (!mounted) return; + setState(_markPositioned); + _afterInitialPositioned(); }); } @@ -1377,7 +1404,7 @@ class _ChatScreenState extends State void _restoreScroll(ChatScrollPoint point) { if (_scrollNav.anchorBeforeLayout(point)) { _markPositioned(); - _afterScrollRestored(); + _afterInitialPositioned(); return; } _initialPositionDone = true; @@ -1390,10 +1417,10 @@ class _ChatScreenState extends State if (!mounted) return; if (!restored) ChatScrollMemory.forget(_myId, widget.chatId); setState(_markPositioned); - _afterScrollRestored(); + _afterInitialPositioned(); } - void _afterScrollRestored() { + void _afterInitialPositioned() { WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; _scrollNav.clampIntoRange(); @@ -1543,14 +1570,12 @@ class _ChatScreenState extends State _bumpMessages(); } - if (candidate.time <= _readMarkTime) return; - _readMarkTime = candidate.time; - var remaining = _messages - .where((m) => m.time > _readMarkTime && m.senderId != _myId) - .length; - if (_chatController.hasNewer) { - remaining = math.max(remaining, chat?.unreadCount ?? 0); - } + final previousMark = _readMarkTime; + final advanced = candidate.time > previousMark; + if (advanced) _readMarkTime = candidate.time; + _unreadAfterMark = _countUnreadAfterMark(previousMark); + if (_tracksUnreadBelow) _scrollNav.showUnreadBelow(_unreadAfterMark); + if (!advanced) return; unawaited( chats.markReadUpTo( api, @@ -1558,11 +1583,45 @@ class _ChatScreenState extends State widget.chatId, candidate.id, candidate.time, - remaining: remaining, + remaining: _unreadAfterMark, ), ); } + bool get _tracksUnreadBelow => + !_commentsMode && !widget.preview && widget.chatId != 0; + + int _incomingCount({required int after, int? upTo}) { + var count = 0; + for (var i = _messages.length - 1; i >= 0; i--) { + final message = _messages[i]; + if (message.senderId == _myId) continue; + if (message.time <= after) break; + if (upTo == null || message.time <= upTo) count++; + } + return count; + } + + int _countUnreadAfterMark(int previousMark) { + final loaded = _incomingCount(after: _readMarkTime); + if (!_chatController.hasNewer) return loaded; + final justRead = _incomingCount(after: previousMark, upTo: _readMarkTime); + return math.max(loaded, _unreadAfterMark - justRead); + } + + void _noteOffscreenArrival(CachedMessage message) { + if (!_tracksUnreadBelow) { + _scrollNav.noteMissedMessage(); + return; + } + if (message.senderId == _myId || message.time <= _readMarkTime) { + _scrollNav.updateScrollDownVisible(); + return; + } + _unreadAfterMark++; + _scrollNav.showUnreadBelow(_unreadAfterMark); + } + bool _unreadSeparatorScrolledPast( bool atBottom, int topIndex, @@ -1584,6 +1643,18 @@ class _ChatScreenState extends State return false; } + bool _canRetrySend(CachedMessage message) => + _textSend.canRetry(message) || _mediaSend.canRetry(message); + + void _retrySend(CachedMessage message) { + if (_textSend.canRetry(message)) { + Haptics.send(); + unawaited(_textSend.retry(message)); + } else { + unawaited(_mediaSend.retry(message)); + } + } + Future _markMessageUnread(CachedMessage message) async { final unread = await chats.markUnread( api, @@ -1848,6 +1919,27 @@ class _ChatScreenState extends State bool get _isChannel => (chat?.type ?? widget.chatType) == 'CHANNEL'; + bool get _channelFeed => _isChannel && !_commentsMode && !widget.preview; + + ChannelViews get _channelViews => _channelViewsStore ??= ChannelViews( + (ids, {required count}) async => ChannelStats.views( + api, + widget.chatId, + ids, + countView: count && await _countsChannelViews(), + ), + ); + + Future? _serverCountsViews; + + Future _countsChannelViews() async { + if (KometSettings.antiRead.value || _myId == 0) return false; + return _serverCountsViews ??= AppDatabase.getSyncValue( + _myId, + SyncKey.viewsCountEnabled, + ).then((value) => value == '1'); + } + bool get _canPostToChannel => _hasRight(AdminRight.createPosts); bool get _canDeleteOthers => _hasRight( @@ -2115,8 +2207,10 @@ class _ChatScreenState extends State if (_isLoadingMore || !_hasMoreHistory) return; if (_messages.isEmpty) return; final pos = _scrollController.position; - if (pos.maxScrollExtent <= 0) return; - if (pos.maxScrollExtent - pos.pixels <= _historyPrefetchExtent) { + if (!pos.hasContentDimensions) return; + final oldestOnScreen = pos.maxScrollExtent <= 0; + if (oldestOnScreen || + pos.maxScrollExtent - pos.pixels <= _historyPrefetchExtent) { unawaited(_loadMoreHistory()); } } @@ -2710,6 +2804,8 @@ class _ChatScreenState extends State KeyboardCover.instance.active.removeListener(_onKeyboardCoverChanged); if (_coversKeyboard) unawaited(KeyboardCover.instance.release()); _stickers.dispose(); + _recommendations?.dispose(); + _channelViewsStore?.dispose(); _scrollController.dispose(); _shimmerStartTimer?.cancel(); _shimmerController.dispose(); @@ -3214,8 +3310,6 @@ class _ChatScreenState extends State crossChatReplySupported: _crossChatReplySupported, onPickReplyChat: _pickReplyChat, formatElapsed: formatVoiceElapsed, - formatContextMenu: _formatContextMenu, - pasteMenuItem: _pasteMenuItem, onPasteMedia: ClipboardMedia.supported ? _handlePasteMedia : null, onInsertContent: _insertKeyboardContent, isMuted: chat?.isMuted ?? false, @@ -3294,7 +3388,6 @@ class _ChatScreenState extends State text: original, formatRanges: formatRanges, photos: photos, - contextMenuBuilder: _formatContextMenu, ), ); @@ -3575,7 +3668,7 @@ class _ChatScreenState extends State _clearTyping(message.senderId); Haptics.tap(); if (_chatController.hasNewer) { - _scrollNav.noteMissedMessage(); + _noteOffscreenArrival(message); _prank.checkTrigger(message); return; } @@ -3591,7 +3684,7 @@ class _ChatScreenState extends State _scrollNav.scrollToBottom(); _scheduleReadMarker(); } else { - _scrollNav.noteMissedMessage(); + _noteOffscreenArrival(message); } _prank.checkTrigger(message); case MessageEditedEvent(:final message): @@ -3942,10 +4035,11 @@ class _ChatScreenState extends State } ChatWallpaper? _effectiveWallpaper(int accountId) { - final store = ChatWallpaperStore.instance; - final wallpaper = - store.get(accountId, widget.chatId) ?? - store.get(accountId, kGlobalWallpaperChatId); + final wallpaper = ChatWallpaperStore.instance.effective( + accountId, + widget.chatId, + ); + precacheWallpaperPattern(wallpaper); final path = wallpaper?.imagePath; if (path != null) WallpaperImages.holdRecent(path); return wallpaper; @@ -3959,14 +4053,23 @@ class _ChatScreenState extends State Future _openWallpaperSheet() async { if (_myId == 0) return; - final pick = await showChatWallpaperSheet(context, current: _wallpaper); - if (pick == null || !mounted) return; final store = ChatWallpaperStore.instance; + final pick = await showChatWallpaperSheet( + context, + current: store.get(_myId, widget.chatId), + inherited: store.effective(_myId, kGlobalWallpaperChatId), + perChat: true, + ); + if (pick == null || !mounted) return; switch (pick.type) { - case WallpaperPickType.none: + case WallpaperPickType.inherit: await store.clear(_myId, widget.chatId); _applyEffectiveWallpaper(); break; + case WallpaperPickType.none: + await store.setNone(_myId, widget.chatId); + _applyEffectiveWallpaper(); + break; case WallpaperPickType.theme: final theme = pick.theme; if (theme == null) break; @@ -4207,97 +4310,6 @@ class _ChatScreenState extends State _syncOtherReadTime(); } - static String _formatLabel(AppLocalizations l10n, TextFormat format) { - switch (format) { - case TextFormat.heading: - return l10n.chatScreenFormatHeading; - case TextFormat.strong: - return l10n.chatScreenFormatBold; - case TextFormat.emphasized: - return l10n.chatScreenFormatItalic; - case TextFormat.underline: - return l10n.chatScreenFormatUnderline; - case TextFormat.strikethrough: - return l10n.chatScreenFormatStrikethrough; - case TextFormat.monospaced: - return l10n.chatScreenFormatMonospace; - case TextFormat.code: - return l10n.chatScreenFormatRed; - case TextFormat.quote: - return l10n.chatScreenFormatQuote; - case TextFormat.link: - return l10n.chatScreenFormatLink; - case TextFormat.animoji: - return 'Animoji'; - case TextFormat.userMention: - return l10n.chatScreenFormatMention; - } - } - - Widget _formatContextMenu( - RichMessageController controller, - BuildContext context, - EditableTextState editableState, { - ContextMenuButtonItem? pasteItem, - }) { - final selection = controller.selection; - final buttonItems = []; - if (selection.isValid && !selection.isCollapsed) { - final l10n = AppLocalizations.of(context)!; - for (final format in composerFormats) { - final active = controller.isFormatActive(format); - buttonItems.add( - ContextMenuButtonItem( - label: '${active ? '✓ ' : ''}${_formatLabel(l10n, format)}', - onPressed: () { - editableState.hideToolbar(); - if (format != TextFormat.link) { - controller.toggleFormat(format); - } else if (active) { - controller.setLink(selection, null); - } else { - unawaited(_askFormatLink(controller, selection)); - } - }, - ), - ); - } - } - if (pasteItem != null) buttonItems.add(pasteItem); - buttonItems.addAll(editableState.contextMenuButtonItems); - if (pasteItem == null) { - return AdaptiveTextSelectionToolbar.buttonItems( - anchors: editableState.contextMenuAnchors, - buttonItems: buttonItems, - ); - } - return PasteMediaToolbar( - anchors: editableState.contextMenuAnchors, - buttonItems: buttonItems, - pasteItem: pasteItem, - ); - } - - Future _askFormatLink( - RichMessageController controller, - TextRange range, - ) async { - final l10n = AppLocalizations.of(context)!; - final raw = await showTextInputDialog( - context, - title: l10n.chatScreenFormatLinkTitle, - hint: l10n.chatScreenFormatLinkHint, - keyboardType: TextInputType.url, - ); - if (raw == null || !mounted) return; - final url = AppUncheckedLinks.current.value ? raw : linkFromInput(raw); - if (url == null) { - showCustomNotification(context, l10n.chatScreenFormatLinkInvalid); - return; - } - controller.setLink(range, url); - } - static bool _sameElements( List> a, List> b, @@ -5056,9 +5068,11 @@ class _ChatScreenState extends State // TODO: Локализация // TODO: Cклонения final viewInsets = MediaQuery.viewInsetsOf(context); + final viewPadding = MediaQuery.viewPaddingOf(context); final keyboard = _keyboardReserve > 0 ? math.max(viewInsets.bottom, _keyboardReserve) : viewInsets.bottom; + final heldKeyboard = keyboard > viewInsets.bottom; return ListenableBuilder( listenable: Listenable.merge([ _selectedIds, @@ -5095,17 +5109,23 @@ class _ChatScreenState extends State ), child: AnimatedBuilder( animation: _stickers.layout, - builder: (context, child) => MediaQuery( - data: context - .getInheritedWidgetOfExactType()! - .data - .copyWith( - viewInsets: viewInsets.copyWith( - bottom: math.max(0, keyboard - _stickers.visibleHeight), - ), + builder: (context, child) { + final media = context.getInheritedWidgetOfExactType()!; + final data = media.data; + return MediaQuery( + data: data.copyWith( + viewInsets: viewInsets.copyWith( + bottom: math.max(0, keyboard - _stickers.visibleHeight), ), - child: child!, - ), + padding: heldKeyboard + ? data.padding.copyWith( + bottom: math.max(0, viewPadding.bottom - keyboard), + ) + : data.padding, + ), + child: child!, + ); + }, child: Theme( data: theme, child: RepaintBoundary( @@ -5122,101 +5142,104 @@ class _ChatScreenState extends State child: HeroMode( enabled: false, child: LottieHoldScope( - isHeld: _animojiHold, - child: MessageFlightLayer( - flight: _flight, - child: ChatBodyLayout( - underlap: underlap, - cs: cs, - chat: chat, - effectiveChrome: _effectiveChrome, - liquidChrome: _liquidChrome, - pillBackdrop: _pillBackdrop, - onJumpToPinnedMessage: _jumpToPinnedMessage, - onUnpinCurrentMessage: _canPin - ? _unpinCurrentMessage - : null, - onJoinCall: _commentsMode ? null : _joinChatCall, - composerFrosted: _composerFrosted, - composerHeight: _composerHeight, - pinnedBannerHeight: _pinnedBannerHeight, - composerAreaBuilder: (context) => widget.preview - ? const SizedBox.shrink() - : _composerAreaWidget(), - messagesArea: _buildMessagesArea(), - mentionPanel: _mentionPanel, - commandPanel: _commandPanel, - note: _note, - searchAnim: _searchAnim, - search: _search, - onOpenSearchResult: _openSearchResult, - searchSenderName: _searchSenderName, - searchSenderAvatar: _searchSenderAvatar, - chromeVignette: _chromeVignette, - composerPaintsSurface: _composerPaintsSurface, - pinnedBannerTop: _pinnedBannerTop(), - defaultEdgeVignetteHeight: _defaultEdgeVignetteHeight(), - wallpaper: _wallpaper, - ), - ), + isHeld: _animojiHold, + child: MessageFlightLayer( + flight: _flight, + child: ChatBodyLayout( + underlap: underlap, + cs: cs, + chat: chat, + effectiveChrome: _effectiveChrome, + liquidChrome: _liquidChrome, + pillBackdrop: _pillBackdrop, + onJumpToPinnedMessage: _jumpToPinnedMessage, + onUnpinCurrentMessage: _canPin + ? _unpinCurrentMessage + : null, + onJoinCall: _commentsMode ? null : _joinChatCall, + composerFrosted: _composerFrosted, + composerHeight: _composerHeight, + onComposerMeasured: _composerHeight.measured, + pinnedBannerHeight: _pinnedBannerHeight, + composerAreaBuilder: (context) => widget.preview + ? const SizedBox.shrink() + : _composerAreaWidget(), + messagesArea: _buildMessagesArea(), + mentionPanel: _mentionPanel, + commandPanel: _commandPanel, + note: _note, + searchAnim: _searchAnim, + search: _search, + onOpenSearchResult: _openSearchResult, + searchSenderName: _searchSenderName, + searchSenderAvatar: _searchSenderAvatar, + chromeVignette: _chromeVignette, + composerPaintsSurface: _composerPaintsSurface, + pinnedBannerTop: _pinnedBannerTop(), + defaultEdgeVignetteHeight: _defaultEdgeVignetteHeight(), + wallpaper: _wallpaper, + ), + ), ), ), builder: (context, body) => ChatDropZone( enabled: !widget.preview && _canReply && _myId != 0, onDrop: (paths) => unawaited(_dropFiles(paths)), child: Scaffold( - backgroundColor: cs.surface, - extendBodyBehindAppBar: underlap, - appBar: _previewSafeBar(ChatAppBar( - cs: cs, - searchAnim: _searchAnim, - selectionAnim: _selectionAnim, - chrome: _effectiveChrome, - chromeVignette: _chromeVignette, - liquidChrome: _liquidChrome, - barBackdrop: _barBackdrop, - pillBackdrop: _pillBackdrop, - glossyChrome: AppVisualStyle.current.value.glossyChrome, - embedded: widget.embedded, - chatId: widget.chatId, - heroTag: _profileHeroTag, - name: _headerName(), - imageUrl: _headerAvatarUrl(), - chatType: widget.chatType, - isOfficial: widget.chatType == 'DIALOG' - ? _peerOfficial - : (chat?.isOfficial ?? false), - encrypted: _encryptionEnabled, - verified: _e2eeVerified, - myId: _myId, - headerStatus: _headerStatusNotifier, - scheduledCount: _scheduledCount, - otherUnread: _otherUnread, - showCall: - !_commentsMode && - widget.chatType == 'DIALOG' && - widget.chatId != 0 && - !_peerIsBot, - onClose: widget.onClose, - onOpenInfo: _commentsMode ? () {} : _openChatInfo, - onOpenScheduled: _openScheduledMessages, - onCall: _startCall, - onMenu: _commentsMode ? (_) {} : _openChatMenu, - selectedIds: _selectedIds, - copyableSelection: _copyableSelection, - singleEditable: _singleEditable, - singleSavable: _singleSavable, - onClearSelection: _clearSelection, - onCopySelected: _copySelected, - onEditSelected: _editSelected, - onSaveSelected: _saveSelected, - onDeleteSelected: _deleteSelected, - search: _search, - searchFocusNode: _searchFocusNode, - onCloseSearch: _closeSearch, - )), - body: body, - ), + backgroundColor: cs.surface, + extendBodyBehindAppBar: underlap, + appBar: _previewSafeBar( + ChatAppBar( + cs: cs, + searchAnim: _searchAnim, + selectionAnim: _selectionAnim, + chrome: _effectiveChrome, + chromeVignette: _chromeVignette, + liquidChrome: _liquidChrome, + barBackdrop: _barBackdrop, + pillBackdrop: _pillBackdrop, + glossyChrome: AppVisualStyle.current.value.glossyChrome, + embedded: widget.embedded, + chatId: widget.chatId, + heroTag: _profileHeroTag, + name: _headerName(), + imageUrl: _headerAvatarUrl(), + chatType: widget.chatType, + isOfficial: widget.chatType == 'DIALOG' + ? _peerOfficial + : (chat?.isOfficial ?? false), + encrypted: _encryptionEnabled, + verified: _e2eeVerified, + myId: _myId, + headerStatus: _headerStatusNotifier, + scheduledCount: _scheduledCount, + otherUnread: _otherUnread, + showCall: + !_commentsMode && + widget.chatType == 'DIALOG' && + widget.chatId != 0 && + !_peerIsBot, + onClose: widget.onClose, + onOpenInfo: _commentsMode ? () {} : _openChatInfo, + onOpenScheduled: _openScheduledMessages, + onCall: _startCall, + onMenu: _commentsMode ? (_) {} : _openChatMenu, + selectedIds: _selectedIds, + copyableSelection: _copyableSelection, + singleEditable: _singleEditable, + singleSavable: _singleSavable, + onClearSelection: _clearSelection, + onCopySelected: _copySelected, + onEditSelected: _editSelected, + onSaveSelected: _saveSelected, + onDeleteSelected: _deleteSelected, + search: _search, + searchFocusNode: _searchFocusNode, + onCloseSearch: _closeSearch, + ), + ), + body: body, + ), ), ), ), @@ -5387,277 +5410,282 @@ class _ChatScreenState extends State context, ).copyWith(scrollbars: false), child: AnchoredMessageList( - controller: _scrollController, - cacheExtent: cacheExtent, - cacheGrowthAllowed: _routeSettled, - padding: _messagesListPadding(context), - epoch: _scrollNav.listEpoch, - itemCount: items.length, - anchorIndex: _scrollNav.anchorIndexIn( - items, - _messageIdOfItem, - ), - loadingOlder: _isLoadingMore, - loadingNewer: _chatController.isLoadingNewer, - bottomSpacer: ValueListenableBuilder( - valueListenable: _composerHeight, - builder: (context, height, _) => SizedBox( - height: _composerUnderlap ? height : 0, + controller: _scrollController, + cacheExtent: cacheExtent, + cacheGrowthAllowed: _routeSettled, + padding: _messagesListPadding(context), + epoch: _scrollNav.listEpoch, + itemCount: items.length, + anchorIndex: _scrollNav.anchorIndexIn( + items, + _messageIdOfItem, ), - ), - itemBuilder: (context, itemIndex) { - final item = items[itemIndex]; - - if (item is _DateSeparatorItem) { - return DateSeparatorLabel( - key: item.key, - date: item.date, - ); - } - - if (item is _UnreadSeparatorItem) { - return UnreadSeparatorBar( - key: _unreadSeparatorKey, - ); - } - - final msgItem = item as _MessageItem; - final message = msgItem.message; - final msgIndex = msgItem.index; - final flight = _flightFor(message.id); - final isMe = message.senderId == _myId; - final prevMessage = msgIndex > 0 - ? _messages[msgIndex - 1] - : null; - final nextMessage = msgIndex < visibleCount - 1 - ? _messages[msgIndex + 1] - : null; - - final bool isChannelPost = - !_commentsMode && - _commentsEnabled && - (chat?.type ?? widget.chatType) == - 'CHANNEL' && - !message.isControl; - final bool isCommentedPost = - _commentsMode && - message.id == widget.commentPostId; - - final bubble = MessageBubble( - message: message, - isMe: isMe, - myId: _myId, - prevMessage: prevMessage, - nextMessage: nextMessage, - separatedAbove: - itemIndex > 0 && - items[itemIndex - 1] is! _MessageItem, - separatedBelow: - itemIndex + 1 < items.length && - items[itemIndex + 1] is! _MessageItem, - chatType: _commentsMode - ? 'CHAT' - : (chat?.type ?? 'CHAT'), - chatId: widget.chatId, - photoActions: _photoActions, - overrideStatus: _effectiveStatus(message), - otherReadTime: _otherReadTime, - reactionsListenable: _reactionNotifierFor( + loadingOlder: _isLoadingMore, + loadingNewer: _chatController.isLoadingNewer, + bottomSpacer: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_recommendations case final recommendations? + when !_chatController.hasNewer) + ChannelRecommendationsView( + recommendations: recommendations, + ), + ValueListenableBuilder( + valueListenable: _composerHeight, + builder: (context, height, _) => SizedBox( + height: _composerUnderlap ? height : 0, + ), + ), + ], + ), + itemBuilder: (context, itemIndex) { + final item = items[itemIndex]; + + if (item is _DateSeparatorItem) { + return DateSeparatorLabel( + key: item.key, + date: item.date, + ); + } + + if (item is _UnreadSeparatorItem) { + return UnreadSeparatorBar(key: _unreadSeparatorKey); + } + + final msgItem = item as _MessageItem; + final message = msgItem.message; + final msgIndex = msgItem.index; + final flight = _flightFor(message.id); + final isMe = message.senderId == _myId; + final prevMessage = msgIndex > 0 + ? _messages[msgIndex - 1] + : null; + final nextMessage = msgIndex < visibleCount - 1 + ? _messages[msgIndex + 1] + : null; + + final channelPost = + !_commentsMode && _isChannel && !message.isControl; + final isChannelPost = channelPost && _commentsEnabled; + final bool isCommentedPost = + _commentsMode && message.id == widget.commentPostId; + + final bubble = MessageBubble( + message: message, + isMe: isMe, + channelPost: channelPost, + views: channelPost + ? _channelViews.of(message.id) + : null, + myId: _myId, + prevMessage: prevMessage, + nextMessage: nextMessage, + separatedAbove: + itemIndex > 0 && + items[itemIndex - 1] is! _MessageItem, + separatedBelow: + itemIndex + 1 < items.length && + items[itemIndex + 1] is! _MessageItem, + chatType: _commentsMode + ? 'CHAT' + : (chat?.type ?? 'CHAT'), + chatId: widget.chatId, + photoActions: _photoActions, + overrideStatus: _effectiveStatus(message), + otherReadTime: _otherReadTime, + reactionsListenable: _reactionNotifierFor(message), + reactionAnimation: _reactionAnimation, + uploadProgress: _photoProgressFor(message), + onCancelUpload: _cancelUploadFor(message), + onCancelUploadItem: _cancelUploadItemFor(message), + onReplyTap: (id) => unawaited( + _scrollNav.goTo( + id, + time: message.replyInfo?.time ?? 0, + fromId: message.id, + ), + ), + resolveLocalMessage: _chatController.byId, + listWidth: listWidth, + onAvatarTap: _openSenderProfile, + onForwardedSourceTap: _openForwardedSource, + onStickerTap: _openStickerPack, + onReactionTap: message.isControl + ? null + : (emoji) => _reactToMessage(message, emoji), + peerName: widget.name, + peerAvatarUrl: widget.imageUrl, + senderNameOverride: isCommentedPost || channelPost + ? _chatName + : null, + senderAvatarOverride: isCommentedPost + ? _chatImageUrl + : null, + textSelection: _textSelection, + textSelectionDrag: _textSelectionDrag, + onExitTextSelection: _exitTextSelection, + commentsLabel: isChannelPost + ? _commentsLabelFor(message.id) + : null, + onCommentsTap: isChannelPost + ? () => _openComments(message) + : null, + geometry: flight?.geometry, + ); + + final canReport = !isMe && !message.isControl; + final unsent = int.tryParse(message.id) == null; + final failedSend = isFailedOutgoingMessage( + message, + _myId, + ); + final reportTypeId = _complaintTypeId( + chat?.type ?? widget.chatType, + ); + + final pressable = SelectableMessageRow( + message: message, + outgoing: isMe && !channelPost, + failedSend: failedSend, + composerHeight: _composerHeight, + selectedIds: _selectedIds, + selectionAnim: _selectionAnim, + isSelectionActive: () => _selectionMode, + onToggleSelection: () => _toggleSelection(message), + onEnterSelection: () => _enterSelection(message), + onStartTextSelection: (pos) => + _startTextSelection(message, pos), + onDragTextSelection: (pos) => + _textSelectionDrag.value = pos, + onDelete: () => + _confirmDeleteMessage(message.id, isMe), + allowDelete: + !message.isControl && + (isMe || !_isChannel || _canDeleteOthers), + onEdit: _canEditMessage(message) + ? () => _startEditMessage(message) + : null, + onRetry: isMe && _canRetrySend(message) + ? () => _retrySend(message) + : null, + onReply: message.isControl || unsent || !_canReply + ? null + : () => _textSend.startReply(message), + onForward: + message.isControl || + unsent || + (chat?.forwardDisabled ?? false) + ? null + : () => _forwardMessages([message]), + allowCopy: !(chat?.copyDisabled ?? false), + onMarkUnread: message.isControl || unsent + ? null + : () => _markMessageUnread(message), + onPin: _canPinMessage(message) + ? () => _togglePinMessage(message) + : null, + onCopyLink: _canLinkMessage(message) + ? () => _copyMessageLink(message) + : null, + onSave: _canSaveVoice(message) + ? () => _saveVoice(message) + : null, + onSaveAs: _savableFile(message) == null + ? null + : () => _saveFileAs(message), + isPinned: () => + chat?.pinnedMsgId == int.tryParse(message.id), + loadReadBy: _canShowReadBy(message) + ? () => _loadReadBy(message) + : null, + onReaderTap: _openSenderProfile, + loadReportReasons: canReport + ? () => _loadReportReasons(reportTypeId) + : null, + onReport: canReport + ? (reasonId) => _reportMessage( message, - ), - reactionAnimation: _reactionAnimation, - uploadProgress: _photoProgressFor(message), - onCancelUpload: _cancelUploadFor(message), - onCancelUploadItem: _cancelUploadItemFor( + reportTypeId, + reasonId, + ) + : null, + onReact: message.isControl + ? null + : (emoji) => _reactToMessage(message, emoji), + onDoubleTapReact: message.isControl + ? null + : (emoji) => _reactToMessage( message, + emoji, + emphasize: true, ), - onReplyTap: (id) => unawaited( - _scrollNav.goTo( - id, - time: message.replyInfo?.time ?? 0, - fromId: message.id, - ), - ), - resolveLocalMessage: _chatController.byId, - listWidth: listWidth, - onAvatarTap: _openSenderProfile, - onForwardedSourceTap: _openForwardedSource, - onStickerTap: _openStickerPack, - onReactionTap: message.isControl - ? null - : (emoji) => - _reactToMessage(message, emoji), - peerName: widget.name, - peerAvatarUrl: widget.imageUrl, - senderNameOverride: isCommentedPost - ? _chatName - : null, - senderAvatarOverride: isCommentedPost - ? _chatImageUrl - : null, - textSelection: _textSelection, - textSelectionDrag: _textSelectionDrag, - onExitTextSelection: _exitTextSelection, - commentsLabel: isChannelPost - ? _commentsLabelFor(message.id) - : null, - onCommentsTap: isChannelPost - ? () => _openComments(message) - : null, - geometry: flight?.geometry, + reactions: _reactionNotifierFor(message), + reactionSettings: _reactionSettings, + child: bubble, + ); + + final isChannel = + (chat?.type ?? widget.chatType) == 'CHANNEL'; + final swipeable = + (failedSend || + message.isControl || + isChannel || + !_canReply) + ? pressable + : SwipeToReply( + onReply: () => _textSend.startReply(message), + child: pressable, ); - final canReport = !isMe && !message.isControl; - final reportTypeId = _complaintTypeId( - chat?.type ?? widget.chatType, - ); - - final pressable = SelectableMessageRow( - message: message, - isMe: isMe, - composerHeight: _composerHeight, - selectedIds: _selectedIds, - selectionAnim: _selectionAnim, - isSelectionActive: () => _selectionMode, - onToggleSelection: () => - _toggleSelection(message), - onEnterSelection: () => - _enterSelection(message), - onStartTextSelection: (pos) => - _startTextSelection(message, pos), - onDragTextSelection: (pos) => - _textSelectionDrag.value = pos, - onDelete: () => - _confirmDeleteMessage(message.id, isMe), - allowDelete: - !message.isControl && - (isMe || !_isChannel || _canDeleteOthers), - onEdit: _canEditMessage(message) - ? () => _startEditMessage(message) - : null, - onReply: message.isControl || !_canReply - ? null - : () => _textSend.startReply(message), - onForward: - message.isControl || - (chat?.forwardDisabled ?? false) - ? null - : () => _forwardMessages([message]), - allowCopy: !(chat?.copyDisabled ?? false), - onMarkUnread: message.isControl - ? null - : () => _markMessageUnread(message), - onPin: _canPinMessage(message) - ? () => _togglePinMessage(message) - : null, - onCopyLink: _canLinkMessage(message) - ? () => _copyMessageLink(message) - : null, - onSave: _canSaveVoice(message) - ? () => _saveVoice(message) - : null, - onSaveAs: _savableFile(message) == null - ? null - : () => _saveFileAs(message), - isPinned: () => - chat?.pinnedMsgId == - int.tryParse(message.id), - loadReadBy: _canShowReadBy(message) - ? () => _loadReadBy(message) - : null, - onReaderTap: _openSenderProfile, - loadReportReasons: canReport - ? () => _loadReportReasons(reportTypeId) - : null, - onReport: canReport - ? (reasonId) => _reportMessage( - message, - reportTypeId, - reasonId, - ) - : null, - onReact: message.isControl - ? null - : (emoji) => - _reactToMessage(message, emoji), - onDoubleTapReact: message.isControl - ? null - : (emoji) => _reactToMessage( - message, - emoji, - emphasize: true, - ), - reactions: _reactionNotifierFor(message), - reactionSettings: _reactionSettings, - child: bubble, - ); - - final isChannel = - (chat?.type ?? widget.chatType) == 'CHANNEL'; - final swipeable = - (message.isControl || - isChannel || - !_canReply) - ? pressable - : SwipeToReply( - onReply: () => _textSend.startReply(message), - child: pressable, - ); - - final Widget child; - if (_deletingIds.contains(message.id)) { - child = DeletingMessageAnimation( - key: ValueKey('del_${message.id}'), - onComplete: () => _finalizeDelete(message.id), - child: IgnorePointer(child: swipeable), - ); - } else { - child = swipeable; - } - - final highlightable = - ValueListenableBuilder( - valueListenable: _scrollNav.highlightMessageId, - builder: (context, hl, c) => - AnimatedContainer( - duration: const Duration( - milliseconds: 250, - ), - color: hl == message.id - ? Theme.of(context) - .colorScheme - .primary - .withValues(alpha: 0.12) - : Colors.transparent, - child: c, - ), - child: child, - ); - - final builtItem = MessageEnter( - key: ValueKey('msg_${message.id}'), - entering: - flight != null || - _enteringIds.contains(message.id), - progress: flight?.controller, - hidden: flight?.carriesBubble ?? false, - child: RepaintBoundary( - child: KeyedSubtree( - key: _keyForMessage(message.id), - child: highlightable, - ), - ), - ); - if (widget.preview) { - return IgnorePointer(child: builtItem); - } - return message.id == _prank.bubbleId - ? KeyedSubtree( - key: _prank.bubbleKey, - child: builtItem, - ) - : builtItem; - }, + final Widget child; + if (_deletingIds.contains(message.id)) { + child = DeletingMessageAnimation( + key: ValueKey('del_${message.id}'), + onComplete: () => _finalizeDelete(message.id), + child: IgnorePointer(child: swipeable), + ); + } else { + child = swipeable; + } + + final highlightable = ValueListenableBuilder( + valueListenable: _scrollNav.highlightMessageId, + builder: (context, hl, c) => AnimatedContainer( + duration: const Duration(milliseconds: 250), + color: hl == message.id + ? Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.12) + : Colors.transparent, + child: c, + ), + child: child, + ); + + final builtItem = MessageEnter( + key: ValueKey('msg_${message.id}'), + entering: + flight != null || + _enteringIds.contains(message.id), + progress: flight?.controller, + hidden: flight?.carriesBubble ?? false, + child: RepaintBoundary( + child: KeyedSubtree( + key: _keyForMessage(message.id), + child: highlightable, + ), + ), + ); + if (widget.preview) { + return IgnorePointer(child: builtItem); + } + return message.id == _prank.bubbleId + ? KeyedSubtree( + key: _prank.bubbleKey, + child: builtItem, + ) + : builtItem; + }, ), ); }, @@ -5707,7 +5735,7 @@ class _ChatScreenState extends State liquidChrome: _liquidChrome, pillBackdrop: _pillBackdrop, scrollDownCurved: _scrollDownCurved, - newMessageCount: _scrollNav.newMessageCount, + unreadBelow: _scrollNav.unreadBelow, onTap: _scrollNav.onScrollDownTap, ), ], @@ -5853,13 +5881,15 @@ class _ChatScreenState extends State if (draft == null || !mounted) return; await _mediaSend.sendAttachMessage( [PollAttachment(pollId: 0, title: draft.title)], - (beforeSend) => messagesModule.sendPollMessage( + (beforeSend, reply) => messagesModule.sendPollMessage( widget.chatId, draft.title, draft.answers, multiple: draft.multiple, anonymous: draft.anonymous, beforeSend: beforeSend, + replyToMessageId: reply?.messageId, + replySourceChatId: reply?.sourceChatId, ), ); } @@ -5870,20 +5900,6 @@ class _ChatScreenState extends State showCustomNotification(context, message(AppLocalizations.of(context)!)); } - ContextMenuButtonItem? _pasteMenuItem( - BuildContext context, - EditableTextState editableState, - ) { - if (!ClipboardMedia.supported) return null; - return ContextMenuButtonItem( - label: AppLocalizations.of(context)!.composerPasteAttachment, - onPressed: () { - editableState.hideToolbar(); - unawaited(_pasteClipboardMedia()); - }, - ); - } - Future _handlePasteMedia() async { if (!await ClipboardMedia.hasMedia()) return false; unawaited(_pasteClipboardMedia()); diff --git a/lib/frontend/screens/chats/folder_edit_sheet.dart b/lib/frontend/screens/chats/folder_edit_sheet.dart index 23d37cc4..fca5333b 100644 --- a/lib/frontend/screens/chats/folder_edit_sheet.dart +++ b/lib/frontend/screens/chats/folder_edit_sheet.dart @@ -65,6 +65,7 @@ const Set _editableFilters = { Future showFolderEditSheet( BuildContext context, { ChatFolder? folder, + Iterable initialChatIds = const [], }) async { final cs = Theme.of(context).colorScheme; await showModalBottomSheet( @@ -72,14 +73,16 @@ Future showFolderEditSheet( isScrollControlled: true, backgroundColor: cs.surfaceContainerHigh, shape: kSheetShape, - builder: (_) => _FolderEditSheet(folder: folder), + builder: (_) => + _FolderEditSheet(folder: folder, initialChatIds: initialChatIds), ); } class _FolderEditSheet extends StatefulWidget { final ChatFolder? folder; + final Iterable initialChatIds; - const _FolderEditSheet({this.folder}); + const _FolderEditSheet({this.folder, this.initialChatIds = const []}); @override State<_FolderEditSheet> createState() => _FolderEditSheetState(); @@ -117,6 +120,8 @@ class _FolderEditSheetState extends State<_FolderEditSheet> { _preservedFilters = folder.filters .where((f) => !_editableFilters.contains(f)) .toList(); + } else { + _chatIds.addAll(widget.initialChatIds); } _load(); } diff --git a/lib/frontend/screens/contacts/contacts_tab.dart b/lib/frontend/screens/contacts/contacts_tab.dart index e280b075..f1e03b75 100644 --- a/lib/frontend/screens/contacts/contacts_tab.dart +++ b/lib/frontend/screens/contacts/contacts_tab.dart @@ -7,6 +7,7 @@ import '../../../core/config/ios_release.dart'; import '../../../core/contacts/contact_labels.dart'; import '../../../core/contacts/device_contacts_service.dart'; import '../../../core/storage/app_database.dart'; +import '../../../core/storage/token_storage.dart'; import '../../../backend/modules/contacts.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart' show api; @@ -18,6 +19,7 @@ import '../../widgets/connection_status.dart'; import '../../widgets/small_spinner.dart'; import '../../widgets/spectrum_tint.dart'; import '../../widgets/springy_tap.dart'; +import '../chats/chat_folders_sheet.dart'; import '../chats/chat_info_screen.dart'; import 'find_user_sheet.dart'; import 'nfc_exchange_sheet.dart'; @@ -188,6 +190,11 @@ class _ContactsTabState extends State with SpectrumSurface { context: context, anchorRect: box.localToGlobal(Offset.zero) & box.size, items: [ + ChatMenuItem( + icon: Symbols.drive_file_move, + label: l10n.chatFoldersAddTo, + onTap: () => _addContactToFolder(contact), + ), ChatMenuItem( icon: Symbols.delete, label: l10n.editContactDelete, @@ -198,6 +205,20 @@ class _ContactsTabState extends State with SpectrumSurface { ); } + Future _addContactToFolder(CachedContact contact) async { + final accountId = await TokenStorage.getActiveAccountId(); + if (accountId == null || !mounted) return; + final existing = await AppDatabase.findDialogChatByParticipant( + accountId, + contact.id, + ); + if (!mounted) return; + await showChatFoldersSheet( + context, + chatIds: [existing ?? (accountId ^ contact.id)], + ); + } + Future _deleteContact(CachedContact contact) async { if (_deleting.contains(contact.id)) return; final l10n = AppLocalizations.of(context)!; diff --git a/lib/frontend/screens/contacts/find_user_sheet.dart b/lib/frontend/screens/contacts/find_user_sheet.dart index fca001f3..571e877d 100644 --- a/lib/frontend/screens/contacts/find_user_sheet.dart +++ b/lib/frontend/screens/contacts/find_user_sheet.dart @@ -11,6 +11,7 @@ import '../../../core/storage/token_storage.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; import '../../../models/contact_info.dart'; +import '../../widgets/alert_note.dart'; import '../../widgets/sheet_helpers.dart'; import '../../widgets/small_spinner.dart'; @@ -273,35 +274,7 @@ class _FindUserSheetState extends State<_FindUserSheet> { ), if (_error != null) ...[ const SizedBox(height: 10), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 10, - ), - decoration: BoxDecoration( - color: cs.errorContainer.withValues(alpha: 0.5), - borderRadius: BorderRadius.circular(12), - ), - child: Row( - children: [ - Icon( - Symbols.error_outline, - size: 18, - color: cs.onErrorContainer, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - _error!, - style: TextStyle( - color: cs.onErrorContainer, - fontSize: 13, - ), - ), - ), - ], - ), - ), + AlertNote(_error!), ], const SizedBox(height: 16), FilledButton( diff --git a/lib/frontend/screens/digital_id/digital_id_web_screen.dart b/lib/frontend/screens/digital_id/digital_id_web_screen.dart index d20c14bc..1814e54c 100644 --- a/lib/frontend/screens/digital_id/digital_id_web_screen.dart +++ b/lib/frontend/screens/digital_id/digital_id_web_screen.dart @@ -6,9 +6,11 @@ import '../../../backend/modules/webapp.dart' show WebAppLaunch; import '../../../core/utils/logger.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart' show digitalIdModule, webAppModule; +import '../webapp/web_app_bridge.dart'; import '../webapp/web_app_screen.dart'; Future resetDigitalIdWebData() async { + if (!WebAppBridge.isSupported) return; await CookieManager.instance().deleteAllCookies(); try { await WebStorageManager.instance().deleteAllData(); diff --git a/lib/frontend/screens/downloads_screen.dart b/lib/frontend/screens/downloads_screen.dart index 9657dc66..e043444d 100644 --- a/lib/frontend/screens/downloads_screen.dart +++ b/lib/frontend/screens/downloads_screen.dart @@ -8,6 +8,7 @@ import 'package:path/path.dart' as p; import '../../core/utils/download_history.dart'; import '../../core/media/audio_file_track.dart'; +import '../../core/media/audio_file_metadata.dart'; import '../../core/media/media_playback.dart'; import '../../core/utils/format.dart'; import '../../core/utils/media_saver.dart'; @@ -20,8 +21,20 @@ import '../widgets/small_spinner.dart'; import '../widgets/sheet_helpers.dart'; import '../widgets/share_unopenable_file.dart'; +typedef DownloadAudioMetadataLoader = + Future Function(DownloadRecord record); + class DownloadsScreen extends StatefulWidget { - const DownloadsScreen({super.key}); + const DownloadsScreen({ + super.key, + this.highlightCacheName, + this.audioMetadataLoader, + }); + + static const routeName = '/downloads'; + + final String? highlightCacheName; + final DownloadAudioMetadataLoader? audioMetadataLoader; @override State createState() => _DownloadsScreenState(); @@ -29,6 +42,9 @@ class DownloadsScreen extends StatefulWidget { class _DownloadsScreenState extends State { late bool _loading = DownloadHistory.records.value.isEmpty; + final ScrollController _scrollController = ScrollController(); + final GlobalKey _highlightKey = GlobalKey(); + final Map> _audioMetadata = {}; @override void initState() { @@ -36,14 +52,59 @@ class _DownloadsScreenState extends State { _load(); } + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + Future _load() async { if (!_loading) { DownloadHistory.refresh().ignore(); + _revealHighlight(); return; } await DownloadHistory.load(); if (mounted) setState(() => _loading = false); await DownloadHistory.refresh(); + _revealHighlight(); + } + + Future _metadataFor(DownloadRecord record) => + _audioMetadata.putIfAbsent(record.cacheName, () async { + final loader = widget.audioMetadataLoader; + if (loader != null) return await loader(record); + final file = await DownloadHistory.fileFor(record, touch: false); + if (file == null) return null; + return await AudioFileMetadata.read(file, cacheName: record.cacheName); + }); + + void _revealHighlight() { + final cacheName = widget.highlightCacheName; + if (cacheName == null || cacheName.isEmpty) return; + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (!mounted) return; + final records = DownloadHistory.records.value; + final index = records.indexWhere((item) => item.cacheName == cacheName); + if (index < 0 || !_scrollController.hasClients) return; + final target = (index * 79.0) + .clamp(0.0, _scrollController.position.maxScrollExtent) + .toDouble(); + await _scrollController.animateTo( + target, + duration: const Duration(milliseconds: 240), + curve: Curves.easeOutCubic, + ); + if (!mounted) return; + final highlighted = _highlightKey.currentContext; + if (highlighted != null && highlighted.mounted) { + await Scrollable.ensureVisible( + highlighted, + duration: const Duration(milliseconds: 160), + alignment: 0.35, + ); + } + }); } Future _open(DownloadRecord record) async { @@ -61,7 +122,7 @@ class _DownloadsScreenState extends State { } if (record.kind == DownloadKind.audio) { try { - await MediaPlayback.instance.activateAudioFile( + final track = await AudioFileMetadata.enrich( AudioFileTrack( cacheName: record.cacheName, path: file.path, @@ -73,7 +134,12 @@ class _DownloadsScreenState extends State { messageId: record.messageId, messageTime: record.messageTime, thumbnailUrl: record.thumbnailUrl, + origin: AudioFileOrigin.downloads, ), + ); + if (!mounted) return; + await MediaPlayback.instance.activateAudioFile( + track, notificationChannelName: AppLocalizations.of( context, )!.audioPlaybackChannel, @@ -248,6 +314,7 @@ class _DownloadsScreenState extends State { } return ListView.separated( key: const ValueKey('downloads-list'), + controller: _scrollController, physics: const BouncingScrollPhysics(), padding: const EdgeInsets.only(bottom: 32), itemCount: records.length, @@ -258,8 +325,15 @@ class _DownloadsScreenState extends State { ), itemBuilder: (context, index) { final record = records[index]; + final highlighted = + record.cacheName == widget.highlightCacheName; return _DownloadTile( + key: highlighted ? _highlightKey : null, record: record, + highlighted: highlighted, + audioMetadata: record.kind == DownloadKind.audio + ? _metadataFor(record) + : null, onTap: () => _open(record), onSaveToGallery: _fitsGallery(record) ? () => _saveToGallery(record) @@ -313,13 +387,18 @@ class _DownloadsEmpty extends StatelessWidget { class _DownloadTile extends StatelessWidget { final DownloadRecord record; + final bool highlighted; + final Future? audioMetadata; final VoidCallback onTap; final VoidCallback? onSaveToGallery; final VoidCallback onSaveAs; final VoidCallback? onGoToMessage; const _DownloadTile({ + super.key, required this.record, + required this.highlighted, + required this.audioMetadata, required this.onTap, required this.onSaveToGallery, required this.onSaveAs, @@ -356,61 +435,88 @@ class _DownloadTile extends StatelessWidget { } @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => FutureBuilder( + future: audioMetadata, + builder: (context, snapshot) => _build(context, snapshot.data), + ); + + Widget _build(BuildContext context, AudioFileMetadataInfo? metadata) { final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; - final source = record.sourceName.trim().isEmpty - ? l10n.downloadsUnknownSource - : record.sourceName.trim(); - return InkWell( - onTap: onTap, - child: Padding( - padding: const EdgeInsets.fromLTRB(18, 10, 16, 10), - child: Row( - children: [ - _DownloadPreview(record: record), - const SizedBox(width: 14), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - _title(l10n), - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: cs.onSurface, - fontSize: 17, - height: 1.15, - fontWeight: FontWeight.w700, + final metadataSource = metadata?.artist?.trim().isNotEmpty == true + ? metadata!.artist!.trim() + : metadata?.album?.trim().isNotEmpty == true + ? metadata!.album!.trim() + : null; + final source = + metadataSource ?? + (record.sourceName.trim().isEmpty + ? l10n.downloadsUnknownSource + : record.sourceName.trim()); + return AnimatedContainer( + key: highlighted + ? ValueKey('download-highlight-${record.cacheName}') + : null, + duration: const Duration(milliseconds: 240), + color: highlighted ? cs.primary.withValues(alpha: 0.14) : null, + child: InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.fromLTRB(18, 10, 16, 10), + child: Row( + children: [ + _DownloadPreview( + record: record, + artworkUri: metadata?.artworkUri, + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _title(l10n, metadata), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurface, + fontSize: 17, + height: 1.15, + fontWeight: FontWeight.w700, + ), ), - ), - const SizedBox(height: 5), - Text( - '${formatBytes(l10n, record.size)} · $source', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), - ), - ], + const SizedBox(height: 5), + Text( + '${formatBytes(l10n, record.size)} · $source', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 14, + ), + ), + ], + ), ), - ), - Builder( - builder: (buttonContext) => IconButton( - key: ValueKey('download-more-${record.cacheName}'), - tooltip: MaterialLocalizations.of(context).moreButtonTooltip, - icon: Icon(Symbols.more_vert, color: cs.onSurfaceVariant), - onPressed: () => _openMenu(buttonContext), + Builder( + builder: (buttonContext) => IconButton( + key: ValueKey('download-more-${record.cacheName}'), + tooltip: MaterialLocalizations.of(context).moreButtonTooltip, + icon: Icon(Symbols.more_vert, color: cs.onSurfaceVariant), + onPressed: () => _openMenu(buttonContext), + ), ), - ), - ], + ], + ), ), ), ); } - String _title(AppLocalizations l10n) { + String _title(AppLocalizations l10n, AudioFileMetadataInfo? metadata) { + final metadataTitle = metadata?.title?.trim(); + if (metadataTitle != null && metadataTitle.isNotEmpty) return metadataTitle; if (record.name.trim().isNotEmpty) return record.name.trim(); return switch (record.kind) { DownloadKind.photo => l10n.downloadsPhoto, @@ -424,8 +530,9 @@ class _DownloadTile extends StatelessWidget { class _DownloadPreview extends StatefulWidget { final DownloadRecord record; + final Uri? artworkUri; - const _DownloadPreview({required this.record}); + const _DownloadPreview({required this.record, this.artworkUri}); @override State<_DownloadPreview> createState() => _DownloadPreviewState(); @@ -448,13 +555,21 @@ class _DownloadPreviewState extends State<_DownloadPreview> { @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + final artwork = widget.artworkUri; final preview = widget.record.thumbnailUrl; return ClipRRect( borderRadius: BorderRadius.circular(8), child: SizedBox( width: 58, height: 58, - child: preview != null && preview.isNotEmpty + child: artwork?.scheme == 'file' + ? Image.file( + File.fromUri(artwork!), + fit: BoxFit.cover, + cacheWidth: 160, + errorBuilder: (_, _, _) => _fallback(cs), + ) + : preview != null && preview.isNotEmpty ? CachedNetworkImage( imageUrl: preview, fit: BoxFit.cover, diff --git a/lib/frontend/screens/profile/appearance_screen.dart b/lib/frontend/screens/profile/appearance_screen.dart index 449e934c..259fe2b3 100644 --- a/lib/frontend/screens/profile/appearance_screen.dart +++ b/lib/frontend/screens/profile/appearance_screen.dart @@ -9,6 +9,7 @@ import '../../../core/config/app_bubble_shape.dart'; import '../../../core/config/app_pill_gradient.dart'; import '../../../core/config/app_visual_style.dart'; import '../../../core/config/app_spectrum_background.dart'; +import '../../../core/config/app_motion.dart'; import '../../../core/config/ios_release.dart'; import '../../../core/utils/bubble_radius.dart'; import '../../../core/utils/debouncer.dart'; @@ -16,6 +17,8 @@ import '../../../core/utils/haptics.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; import '../../widgets/settings_card.dart'; +import '../../widgets/spotlight.dart'; +import '../../../core/whats_new/spotlight_ids.dart'; import '../../widgets/message_actions_style_card.dart'; import '../../../core/config/app_shape.dart'; import '../../../core/utils/seed_scheme.dart'; @@ -130,6 +133,8 @@ class _AppearanceScreenState extends State { ], const SizedBox(height: 12), const _SpectrumToggleCard(), + const SizedBox(height: 12), + const _AnimationsToggleCard(), ], ), ), @@ -776,3 +781,32 @@ class _BubbleBehaviorCard extends StatelessWidget { ); } } + +class _AnimationsToggleCard extends StatelessWidget { + const _AnimationsToggleCard(); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return SpotlightTarget( + id: SpotlightIds.appearanceAnimations, + borderRadius: AppShape.cardRadius, + child: SettingsPanel( + padding: EdgeInsets.zero, + child: ValueListenableBuilder( + valueListenable: AppMotion.enabled, + builder: (context, value, _) => SettingsToggleTile( + icon: Symbols.animation, + label: l10n.appearanceAnimationsTitle, + subtitle: l10n.appearanceAnimationsSubtitle, + value: value, + onChanged: (next) { + Haptics.selection(); + AppMotion.save(next); + }, + ), + ), + ), + ); + } +} diff --git a/lib/frontend/screens/profile/chat_background_screen.dart b/lib/frontend/screens/profile/chat_background_screen.dart index fb32b919..9435b034 100644 --- a/lib/frontend/screens/profile/chat_background_screen.dart +++ b/lib/frontend/screens/profile/chat_background_screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; import '../../../core/config/app_wallpaper_tint.dart'; import '../../../core/storage/app_database.dart'; @@ -9,7 +10,6 @@ import '../../widgets/chat_wallpaper_view.dart'; import '../../widgets/custom_notification.dart'; import '../chats/chat_wallpaper_preview_screen.dart'; import '../../../core/config/app_fonts.dart'; -import '../../../core/config/app_shape.dart'; class ChatBackgroundScreen extends StatefulWidget { const ChatBackgroundScreen({super.key}); @@ -35,7 +35,7 @@ class _ChatBackgroundScreenState extends State { if (!mounted) return; setState(() { _accountId = profile?.id ?? 0; - _wallpaper = ChatWallpaperStore.instance.get( + _wallpaper = ChatWallpaperStore.instance.effective( _accountId, kGlobalWallpaperChatId, ); @@ -46,7 +46,7 @@ class _ChatBackgroundScreenState extends State { void _refresh() { if (!mounted) return; setState(() { - _wallpaper = ChatWallpaperStore.instance.get( + _wallpaper = ChatWallpaperStore.instance.effective( _accountId, kGlobalWallpaperChatId, ); @@ -59,6 +59,7 @@ class _ChatBackgroundScreenState extends State { if (pick == null || !mounted) return; final store = ChatWallpaperStore.instance; switch (pick.type) { + case WallpaperPickType.inherit: case WallpaperPickType.none: await store.clear(_accountId, kGlobalWallpaperChatId); _refresh(); @@ -143,20 +144,16 @@ class _ChatBackgroundScreenState extends State { } Widget _preview(ColorScheme cs) { + final l10n = AppLocalizations.of(context)!; + final wallpaper = _wallpaper; return Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), - child: ClipRRect( - borderRadius: AppShape.cardRadius, - child: Stack( - fit: StackFit.expand, - children: [ - if (_wallpaper != null) - ChatWallpaperView(wallpaper: _wallpaper!) - else - ColoredBox(color: cs.surfaceContainerHighest), - _SampleBubbles(cs: cs), - ], - ), + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: WallpaperPreview( + layer: wallpaper == null + ? const SizedBox.shrink() + : ChatWallpaperView(wallpaper: wallpaper), + incoming: l10n.chatBackgroundSampleIncoming, + outgoing: l10n.chatBackgroundSampleOutgoing, ), ); } @@ -166,10 +163,10 @@ class _ChatBackgroundScreenState extends State { return Container( width: double.infinity, decoration: BoxDecoration( - color: cs.surfaceContainerHigh, - borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), + color: cs.surfaceContainerLow, + borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), ), - padding: const EdgeInsets.fromLTRB(20, 18, 20, 20), + padding: const EdgeInsets.fromLTRB(20, 18, 20, 12), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -220,97 +217,14 @@ class _ChatBackgroundScreenState extends State { ), ), const SizedBox(height: 12), - GestureDetector( - onTap: _ready ? _openPicker : null, - child: Container( - height: 52, - decoration: BoxDecoration( - color: cs.primary, - borderRadius: BorderRadius.circular(16), - ), - child: Center( - child: Text( - l10n.chatBackgroundPick, - style: TextStyle( - color: cs.onPrimary, - fontSize: 16, - fontWeight: FontWeight.w700, - fontFamily: displayFontOf(context), - ), - ), - ), - ), + FilledButton.icon( + style: wallpaperButtonStyle(context), + onPressed: _ready ? _openPicker : null, + icon: const Icon(Symbols.wallpaper, size: 20), + label: Text(l10n.chatBackgroundPick), ), ], ), ); } } - -class _SampleBubbles extends StatelessWidget { - final ColorScheme cs; - - const _SampleBubbles({required this.cs}); - - @override - Widget build(BuildContext context) { - final l10n = AppLocalizations.of(context)!; - return Align( - alignment: Alignment.bottomCenter, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _bubble( - context, - text: l10n.chatBackgroundSampleIncoming, - color: cs.surfaceContainerHighest.withValues(alpha: 0.94), - textColor: cs.onSurface, - alignment: Alignment.centerLeft, - ), - const SizedBox(height: 8), - _bubble( - context, - text: l10n.chatBackgroundSampleOutgoing, - color: cs.primary, - textColor: cs.onPrimary, - alignment: Alignment.centerRight, - ), - ], - ), - ), - ); - } - - Widget _bubble( - BuildContext context, { - required String text, - required Color color, - required Color textColor, - required Alignment alignment, - }) { - return Align( - alignment: alignment, - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 260), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), - decoration: BoxDecoration( - color: color, - borderRadius: BorderRadius.circular(18), - ), - child: Text( - text, - style: TextStyle( - color: textColor, - fontSize: 15, - fontFamily: displayFontOf(context), - ), - ), - ), - ), - ); - } -} diff --git a/lib/frontend/screens/profile/cloud_storage_screen.dart b/lib/frontend/screens/profile/cloud_storage_screen.dart index d868097b..c4b3ec15 100644 --- a/lib/frontend/screens/profile/cloud_storage_screen.dart +++ b/lib/frontend/screens/profile/cloud_storage_screen.dart @@ -2,7 +2,6 @@ import 'dart:async'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:material_symbols_icons/symbols.dart'; @@ -12,6 +11,7 @@ import '../../../backend/modules/cloud_storage.dart'; import '../../../backend/modules/upload_service.dart'; import '../../../core/storage/app_database.dart'; import '../../../core/utils/format.dart'; +import '../../../core/utils/logger.dart'; import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; import '../../widgets/connection_status.dart'; @@ -22,6 +22,7 @@ import '../../widgets/info_action_sheet.dart'; import '../../widgets/glossy_pill.dart'; import '../../widgets/sheet_helpers.dart'; import '../../widgets/small_spinner.dart'; +import '../../widgets/undo_notification.dart'; import '../../../core/config/app_shape.dart'; import '../../../core/security/app_lock.dart'; @@ -35,19 +36,20 @@ class CloudStorageScreen extends StatefulWidget { } class _CloudStorageScreenState extends State - with SingleTickerProviderStateMixin, ReloadOnReconnect { - static const _translateFactor = 0.7; + with ReloadOnReconnect { static const _horizontalPadding = 32.0; - static const _hintSidePadding = 35.0; - static const _cornerSidePadding = 16.0; - static const _cornerBottomPadding = 24.0; - static const _cornerSlideAmount = 28.0; - static const _cardViewportFraction = 0.42; - - late final _UploadModeController _mode; - late final PageController _pageController; - final _currentFilePage = ValueNotifier(0); - + static const _gridPadding = 16.0; + static const _gridSpacing = 12.0; + static const _maxCardExtent = 220.0; + static const _actionsPadding = 16.0; + static const _loadMoreExtent = 600.0; + static const _emptyPagesPerLoad = 5; + + final ScrollController _gridController = ScrollController(); + bool _filesLoaded = false; + bool _hasMore = false; + bool _loadingMore = false; + int? _oldestTime; _EnvState _envState = _EnvState.loading; bool _isCreatingEnv = false; int? _envGroupId; @@ -62,17 +64,11 @@ class _CloudStorageScreenState extends State @override void initState() { super.initState(); - _mode = _UploadModeController(this); - _pageController = PageController(viewportFraction: _cardViewportFraction); - _pageController.addListener(_onPageScroll); + _gridController.addListener(_maybeLoadMore); _checkEnv(); _uploadEventSub = UploadService.instance.events.listen(_onUploadEvent); } - void _onPageScroll() { - _currentFilePage.value = _pageController.page?.round() ?? 0; - } - void _syncUploadJob() { final chatId = _envGroupId; final job = chatId == null @@ -91,9 +87,7 @@ class _CloudStorageScreenState extends State job.progress.addListener(_onUploadProgress); _onUploadProgress(); - if (_isUploading) return; - setState(() => _isUploading = true); - _mode.open(); + if (!_isUploading) setState(() => _isUploading = true); } void _onUploadProgress() { @@ -118,14 +112,21 @@ class _CloudStorageScreenState extends State return; } if (event is! UploadJobDone) return; + await _showUploaded(accountId, chatId, event.fileId); + } + Future _showUploaded(int accountId, int chatId, int? fileId) async { final newest = await CloudStorageModule.fetchLatestFile( messagesModule, accountId, chatId, - expectedFileId: event.fileId, + expectedFileId: fileId, ); - if (!mounted || newest == null) return; + if (!mounted) return; + if (newest == null) { + await _loadFiles(accountId, chatId); + return; + } _prependFile(newest); } @@ -133,10 +134,8 @@ class _CloudStorageScreenState extends State void dispose() { _uploadEventSub?.cancel(); _uploadJob?.progress.removeListener(_onUploadProgress); - _mode.dispose(); - _pageController.dispose(); - _currentFilePage.dispose(); _uploadProgress.dispose(); + _gridController.dispose(); super.dispose(); } @@ -229,29 +228,110 @@ class _CloudStorageScreenState extends State unawaited(_loadFiles(accountId, groupId)); } + Future _reload() async { + final accountId = _accountId; + final groupId = _envGroupId; + if (accountId == null || groupId == null) return; + try { + await _loadFiles(accountId, groupId); + } catch (e) { + logger.w('Облако: не удалось обновить список файлов: $e'); + } + } + Future _loadFiles(int accountId, int chatId) async { - final files = await CloudStorageModule.fetchFiles( + final page = await CloudStorageModule.fetchPage( messagesModule, accountId, chatId, ); if (!mounted) return; - setState(() => _files = files.reversed.toList()); + final boundary = page.oldestTime; + setState(() { + final older = boundary == null + ? const [] + : [ + for (final f in _files) + if (f.time < boundary) f, + ]; + _files = [...page.files, ...older]; + _filesLoaded = true; + if (older.isEmpty) { + _oldestTime = boundary; + _hasMore = boundary != null; + } + }); _syncUploadJob(); + _scheduleLoadMoreCheck(); + } + + void _scheduleLoadMoreCheck() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _maybeLoadMore(); + }); + } + + void _maybeLoadMore() { + if (!_hasMore || _loadingMore) return; + if (_gridController.hasClients && + _gridController.position.extentAfter > _loadMoreExtent) { + return; + } + unawaited(_loadMore()); + } + + static String _fileKey(CloudFile file) => '${file.messageId}_${file.fileId}'; + + Future _loadMore() async { + final accountId = _accountId; + final chatId = _envGroupId; + var cursor = _oldestTime; + if (accountId == null || chatId == null || cursor == null) return; + setState(() => _loadingMore = true); + var grew = false; + try { + for (var page = 0; page < _emptyPagesPerLoad || _files.isEmpty; page++) { + final result = await CloudStorageModule.fetchPage( + messagesModule, + accountId, + chatId, + before: cursor, + ); + if (!mounted) return; + final known = {for (final f in _files) _fileKey(f)}; + final fresh = [ + for (final f in result.files) + if (known.add(_fileKey(f))) f, + ]; + final next = result.oldestTime; + setState(() { + _files = [..._files, ...fresh]; + _oldestTime = next ?? cursor; + _hasMore = next != null; + }); + if (next == null || fresh.isNotEmpty) { + grew = fresh.isNotEmpty; + break; + } + cursor = next; + } + } catch (e) { + logger.w('Облако: не удалось подгрузить старые файлы: $e'); + } finally { + if (mounted) setState(() => _loadingMore = false); + } + if (grew) _scheduleLoadMoreCheck(); } void _prependFile(CloudFile file) { setState(() { - _files = [file, ..._files]; + _files = [ + file, + for (final f in _files) + if (f.messageId != file.messageId || f.fileId != file.fileId) f, + ]; _animateNewCard = true; }); - if (_pageController.hasClients) { - _pageController.animateToPage( - 0, - duration: const Duration(milliseconds: 350), - curve: Curves.easeOut, - ); - } Future.delayed(const Duration(milliseconds: 800), () { if (mounted) setState(() => _animateNewCard = false); }); @@ -370,40 +450,75 @@ class _CloudStorageScreenState extends State onSend: (id) async { final sentId = await messagesModule.sendFileMessage(chatId, id); if (sentId == null) return false; - final newest = await CloudStorageModule.fetchLatestFile( - messagesModule, - accountId, - chatId, - expectedFileId: id, - ); - if (mounted) { - if (newest != null) { - _prependFile(newest); - } else { - _loadFiles(accountId, chatId); - } - } + if (mounted) await _showUploaded(accountId, chatId, id); return true; }, ), ); } - void _onCardTap(CloudFile file) { - showModalBottomSheet( + Future _onCardTap(CloudFile file) async { + final delete = await showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: Colors.transparent, builder: (_) => _FileDetailsSheet(file: file), ); + if (delete == true && mounted) _deleteFile(file); } - void _onBack() { - if (_mode.isOpen) { - _mode.close(); - } else { - Navigator.pop(context); + void _deleteFile(CloudFile file) { + final l10n = AppLocalizations.of(context)!; + final removed = [ + for (final f in _files) + if (f.messageId == file.messageId) f, + ]; + setState(() { + _files = [ + for (final f in _files) + if (f.messageId != file.messageId) f, + ]; + }); + void restore() { + if (!mounted) return; + final present = {for (final f in _files) _fileKey(f)}; + setState(() { + _files = [ + ..._files, + for (final f in removed) + if (!present.contains(_fileKey(f))) f, + ]..sort((a, b) => b.time.compareTo(a.time)); + }); } + + final overlay = Overlay.of(context, rootOverlay: true); + showUndoNotification( + context, + l10n.cloudStorageFileDeleted, + onUndo: restore, + onCommit: () async { + final ok = await messagesModule.deleteMessages(file.chatId, [ + file.messageId, + ], forEveryone: true); + if (!ok) { + restore(); + if (overlay.mounted) { + showCustomNotificationOnOverlay( + overlay, + l10n.cloudStorageDeleteFailed, + ); + } + return; + } + try { + await AppDatabase.deleteMessage( + file.accountId, + file.chatId, + file.messageId, + ); + } catch (_) {} + }, + ); } @override @@ -418,7 +533,7 @@ class _CloudStorageScreenState extends State elevation: 0, leading: IconButton( icon: Icon(Symbols.arrow_back, color: cs.onSurface), - onPressed: _onBack, + onPressed: () => Navigator.pop(context), ), title: ConnectionTitleText( l10n.cloudStorageTitle, @@ -489,185 +604,170 @@ class _CloudStorageScreenState extends State } Widget _buildReady(ColorScheme cs) { - return LayoutBuilder( - builder: (context, constraints) { - final h = constraints.maxHeight; - return GestureDetector( - behavior: HitTestBehavior.opaque, - onVerticalDragUpdate: (d) => _mode.handleDragUpdate(d, h), - onVerticalDragEnd: _mode.handleDragEnd, - child: AnimatedBuilder( - animation: _mode.anim, - builder: (context, _) { - final t = Curves.easeOutCubic.transform(_mode.anim.value); - return Stack( - fit: StackFit.expand, - children: [ - _buildHint(cs, t), - _buildUploadingCenterHint(cs, t, constraints.maxWidth), - _buildEmptyState(cs, t, h), - ..._buildCornerActions(cs, t), - ], - ); - }, + return Column( + children: [ + if (_isUploading) _buildUploadProgress(cs), + Expanded( + child: RefreshIndicator( + onRefresh: _reload, + child: _files.isNotEmpty + ? _buildGrid() + : !_filesLoaded || _hasMore + ? const Center(child: SmallSpinner(size: 36)) + : _buildEmptyState(cs), ), - ); - }, + ), + _buildActions(), + ], + ); + } + + Widget _buildUploadProgress(ColorScheme cs) { + final l10n = AppLocalizations.of(context)!; + return Padding( + padding: const EdgeInsets.fromLTRB(_gridPadding, 4, _gridPadding, 8), + child: ValueListenableBuilder( + valueListenable: _uploadProgress, + builder: (context, progress, _) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + LinearProgressIndicator( + value: progress, + borderRadius: BorderRadius.circular(4), + minHeight: 5, + color: cs.primary, + backgroundColor: cs.surfaceContainerHighest, + ), + const SizedBox(height: 6), + Text( + l10n.cloudStorageUploadingPercent( + (progress * 100).toStringAsFixed(0), + ), + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 13), + ), + ], + ), + ), ); } - Widget _buildHint(ColorScheme cs, double t) { - return Positioned( - top: 0, - left: _hintSidePadding, - right: _hintSidePadding, - child: IgnorePointer( - child: Opacity( - opacity: t, - child: _DragDownHint(color: cs.onSurfaceVariant), + Widget _buildGrid() { + return CustomScrollView( + controller: _gridController, + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + SliverPadding( + padding: const EdgeInsets.fromLTRB( + _gridPadding, + 8, + _gridPadding, + _gridPadding, + ), + sliver: _buildGridItems(), ), + if (_loadingMore) + const SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.only(bottom: _gridPadding), + child: Center(child: SmallSpinner()), + ), + ), + ], + ); + } + + Widget _buildGridItems() { + return SliverGrid.builder( + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: _maxCardExtent, + mainAxisSpacing: _gridSpacing, + crossAxisSpacing: _gridSpacing, ), + itemCount: _files.length, + itemBuilder: (_, i) { + final file = _files[i]; + final card = _CloudFileCard( + key: ValueKey('${file.messageId}_${file.fileId}'), + file: file, + onTap: () => _onCardTap(file), + ); + if (i == 0 && _animateNewCard) { + return _FadeScaleEntry( + key: ValueKey('new_${file.messageId}_${file.fileId}'), + child: card, + ); + } + return card; + }, ); } - Widget _buildUploadingCenterHint( - ColorScheme cs, - double t, - double availableWidth, - ) { + Widget _buildEmptyState(ColorScheme cs) { final l10n = AppLocalizations.of(context)!; - final cardSide = availableWidth * _cardViewportFraction; - return Center( - child: Opacity( - opacity: t, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: _horizontalPadding), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_files.isNotEmpty) ...[ - SizedBox( - height: cardSide, - width: availableWidth, - child: ScrollConfiguration( - behavior: _MouseDragScrollBehavior(), - child: PageView.builder( - controller: _pageController, - itemCount: _files.length, - itemBuilder: (_, i) { - final card = _CloudFileCard( - file: _files[i], - onTap: () => _onCardTap(_files[i]), - ); - final padded = Padding( - padding: const EdgeInsets.symmetric(horizontal: 6), - child: card, - ); - if (i == 0 && _animateNewCard) { - return _FadeScaleEntry( - key: ValueKey( - '${_files[0].messageId}_${_files[0].time}', - ), - child: padded, - ); - } - return padded; - }, + return LayoutBuilder( + builder: (context, constraints) => ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + ConstrainedBox( + constraints: BoxConstraints(minHeight: constraints.maxHeight), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: _horizontalPadding, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + l10n.cloudStorageEmptyTitle, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 17, + fontWeight: FontWeight.w600, ), ), - ), - const SizedBox(height: 8), - ValueListenableBuilder( - valueListenable: _currentFilePage, - builder: (context, page, child) => Text( - '${page + 1} / ${_files.length}', - style: TextStyle(color: cs.onSurfaceVariant, fontSize: 12), + const SizedBox(height: 6), + Text( + l10n.cloudStorageEmptySubtitle, + textAlign: TextAlign.center, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), ), - ), - const SizedBox(height: 16), - ], - if (_isUploading) ...[ - ValueListenableBuilder( - valueListenable: _uploadProgress, - builder: (context, progress, _) => Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - LinearProgressIndicator( - value: progress, - borderRadius: BorderRadius.circular(4), - minHeight: 5, - color: cs.primary, - backgroundColor: cs.surfaceContainerHighest, - ), - const SizedBox(height: 8), - Text( - l10n.cloudStorageUploadingPercent( - (progress * 100).toStringAsFixed(0), - ), - style: TextStyle( - color: cs.onSurfaceVariant, - fontSize: 13, - ), - ), - ], - ), - ), - ] else if (_files.isEmpty) ...[ - Text( - l10n.cloudStorageStartUploadHint, - textAlign: TextAlign.center, - style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), - ), - ], - ], + ], + ), + ), ), - ), + ], ), ); } - Widget _buildEmptyState(ColorScheme cs, double t, double availableHeight) { + Widget _buildActions() { final l10n = AppLocalizations.of(context)!; - return Transform.translate( - offset: Offset(0, -t * availableHeight * _translateFactor), + return SafeArea( + top: false, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: _horizontalPadding), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, + padding: const EdgeInsets.fromLTRB( + _actionsPadding, + 8, + _actionsPadding, + _actionsPadding, + ), + child: Row( children: [ - Text( - l10n.cloudStorageEmptyTitle, - textAlign: TextAlign.center, - style: TextStyle( - color: cs.onSurface, - fontSize: 17, - fontWeight: FontWeight.w600, + Expanded( + child: _CornerAction( + icon: Symbols.upload_file, + label: l10n.cloudStorageFromFile, + onTap: _pickAndUploadFile, ), ), - const SizedBox(height: 6), - Text( - l10n.cloudStorageEmptySubtitle, - style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), - ), - const SizedBox(height: 24), - FilledButton( - onPressed: _mode.isOpen ? null : _mode.open, - style: FilledButton.styleFrom( - backgroundColor: cs.primary, - foregroundColor: cs.onPrimary, - padding: const EdgeInsets.symmetric( - horizontal: 32, - vertical: 14, - ), - shape: AppShape.buttonBorder, - ), - child: Text( - l10n.cloudStorageUpload, - style: const TextStyle( - fontSize: 15, - fontWeight: FontWeight.w600, - ), + const SizedBox(width: 12), + Expanded( + child: _CornerAction( + icon: Symbols.tag, + label: l10n.cloudStorageById, + onTap: _showSendByIdSheet, ), ), ], @@ -675,77 +775,6 @@ class _CloudStorageScreenState extends State ), ); } - - List _buildCornerActions(ColorScheme cs, double t) { - final l10n = AppLocalizations.of(context)!; - final slide = (1 - t) * _cornerSlideAmount; - return [ - Positioned( - bottom: _cornerBottomPadding, - left: _cornerSidePadding - slide, - child: Opacity( - opacity: t, - child: _CornerAction( - icon: Symbols.upload_file, - label: l10n.cloudStorageFromFile, - onTap: _pickAndUploadFile, - ), - ), - ), - Positioned( - bottom: _cornerBottomPadding, - right: _cornerSidePadding - slide, - child: Opacity( - opacity: t, - child: _CornerAction( - icon: Symbols.tag, - label: l10n.cloudStorageById, - onTap: _showSendByIdSheet, - ), - ), - ), - ]; - } -} - -class _UploadModeController { - static const _openDuration = Duration(milliseconds: 480); - static const _closeDuration = Duration(milliseconds: 320); - static const _dragRangeFactor = 0.55; - static const _flingVelocityThreshold = 280.0; - static const _snapMidpoint = 0.5; - - final AnimationController anim; - - _UploadModeController(TickerProvider vsync) - : anim = AnimationController( - vsync: vsync, - duration: _openDuration, - reverseDuration: _closeDuration, - ); - - bool get isOpen => anim.value > 0; - - void open() => anim.forward(); - void close() => anim.reverse(); - - void handleDragUpdate(DragUpdateDetails d, double availableHeight) { - if (anim.value == 0) return; - final delta = d.primaryDelta ?? 0; - final next = anim.value - delta / (availableHeight * _dragRangeFactor); - anim.value = next.clamp(0.0, 1.0); - } - - void handleDragEnd(DragEndDetails d) { - final v = d.primaryVelocity ?? 0; - if (v.abs() > _flingVelocityThreshold) { - v > 0 ? close() : open(); - return; - } - anim.value < _snapMidpoint ? close() : open(); - } - - void dispose() => anim.dispose(); } class _CornerAction extends StatelessWidget { @@ -762,117 +791,33 @@ class _CornerAction extends StatelessWidget { @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; - return Material( - color: Colors.transparent, - child: InkWell( - onTap: onTap, - borderRadius: BorderRadius.circular(16), - child: GlossyPill( - color: cs.surfaceContainerHigh, - borderRadius: BorderRadius.circular(16), - padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), - depth: 6, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(icon, color: cs.onSurface, size: 20), - const SizedBox(width: 8), - Text( - label, - style: TextStyle( - color: cs.onSurface, - fontSize: 14, - fontWeight: FontWeight.w600, - ), + return GlossyPill( + onTap: onTap, + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(16), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14), + depth: 6, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, color: cs.onSurface, size: 20), + const SizedBox(width: 8), + Flexible( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurface, + fontSize: 14, + fontWeight: FontWeight.w600, ), - ], + ), ), - ), - ), - ); - } -} - -class _DragDownHint extends StatefulWidget { - final Color color; - - const _DragDownHint({required this.color}); - - @override - State<_DragDownHint> createState() => _DragDownHintState(); -} - -class _DragDownHintState extends State<_DragDownHint> - with SingleTickerProviderStateMixin { - static const _cycle = Duration(milliseconds: 2800); - static const _activeFraction = 0.4; - static const _height = 3.0; - static const _slotHeight = 28.0; - static const _startY = -6.0; - static const _travel = 16.0; - static const _peakOpacity = 0.32; - - late final AnimationController _c; - - @override - void initState() { - super.initState(); - _c = AnimationController(vsync: this, duration: _cycle)..repeat(); - } - - @override - void dispose() { - _c.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return SizedBox( - height: _slotHeight, - child: AnimatedBuilder( - animation: _c, - builder: (context, _) { - final ghost = _ghostFor(_c.value); - if (ghost.opacity <= 0) return const SizedBox.shrink(); - return Stack( - children: [ - Positioned( - left: 0, - right: 0, - top: ghost.dy, - height: _height, - child: Opacity( - opacity: ghost.opacity, - child: DecoratedBox( - decoration: BoxDecoration( - color: widget.color, - borderRadius: BorderRadius.circular(2), - ), - ), - ), - ), - ], - ); - }, + ], ), ); } - - ({double dy, double opacity}) _ghostFor(double phase) { - if (phase > _activeFraction) return (dy: 0, opacity: 0); - final local = phase / _activeFraction; - final eased = Curves.easeOutCubic.transform(local); - return (dy: _startY + eased * _travel, opacity: (1 - local) * _peakOpacity); - } -} - -class _MouseDragScrollBehavior extends MaterialScrollBehavior { - @override - Set get dragDevices => { - PointerDeviceKind.touch, - PointerDeviceKind.mouse, - }; } class _FadeScaleEntry extends StatefulWidget { @@ -927,7 +872,7 @@ class _CloudFileCard extends StatelessWidget { final CloudFile file; final VoidCallback onTap; - const _CloudFileCard({required this.file, required this.onTap}); + const _CloudFileCard({super.key, required this.file, required this.onTap}); static IconData _icon(String name) { final ext = name.contains('.') ? name.split('.').last.toLowerCase() : ''; @@ -945,64 +890,65 @@ class _CloudFileCard extends StatelessWidget { }; } - static String _formatTime(int millis) { + static String _formatTime(AppLocalizations l10n, int millis) { final d = DateTime.fromMillisecondsSinceEpoch(millis); final now = DateTime.now(); if (d.year == now.year && d.month == now.month && d.day == now.day) { return formatClock(d); } - return '${d.day.toString().padLeft(2, '0')}.${d.month.toString().padLeft(2, '0')}'; + if (d.year == now.year) return formatDayMonth(l10n, d); + return formatDateNumeric(d); } @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; - return GestureDetector( + final l10n = AppLocalizations.of(context)!; + final size = file.size; + final details = [ + if (size != null) formatBytes(l10n, size), + _formatTime(l10n, file.time), + ].join(' · '); + return GlossyPill( onTap: onTap, - child: AspectRatio( - aspectRatio: 1.0, - child: GlossyPill( - color: cs.surfaceContainerLow, - borderRadius: BorderRadius.circular(16), - depth: 6, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Center( - child: Icon(_icon(file.name), color: cs.primary, size: 34), + color: cs.surfaceContainerLow, + borderRadius: BorderRadius.circular(16), + depth: 6, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Center( + child: Icon(_icon(file.name), color: cs.primary, size: 40), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + file.name, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurface, + fontSize: 13, + fontWeight: FontWeight.w600, + height: 1.2, + ), ), - ), - Padding( - padding: const EdgeInsets.fromLTRB(10, 0, 10, 10), - child: Row( - children: [ - Expanded( - child: Text( - file.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: cs.onSurface, - fontSize: 11, - fontWeight: FontWeight.w600, - ), - ), - ), - const SizedBox(width: 4), - Text( - _formatTime(file.time), - style: TextStyle( - color: cs.onSurfaceVariant, - fontSize: 10, - ), - ), - ], + const SizedBox(height: 4), + Text( + details, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 11), ), - ), - ], + ], + ), ), - ), + ], ), ); } @@ -1169,6 +1115,21 @@ class _FileDetailsSheetState extends State<_FileDetailsSheet> { ), ], ), + const SizedBox(height: 16), + Container(height: 0.5, color: cs.outlineVariant), + const SizedBox(height: 8), + TextButton.icon( + onPressed: () => Navigator.pop(context, true), + style: TextButton.styleFrom( + foregroundColor: cs.error, + padding: EdgeInsets.zero, + ), + icon: const Icon(Symbols.delete, size: 20), + label: Text( + l10n.cloudStorageDeleteFile, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), ], ), ); diff --git a/lib/frontend/screens/profile/customization_section.dart b/lib/frontend/screens/profile/customization_section.dart index 5b032510..bfae4f97 100644 --- a/lib/frontend/screens/profile/customization_section.dart +++ b/lib/frontend/screens/profile/customization_section.dart @@ -5,6 +5,8 @@ import '../../../core/utils/haptics.dart'; import '../../../l10n/app_localizations.dart'; import '../../widgets/glossy_pill.dart'; import '../../widgets/settings_card.dart'; +import '../../widgets/spotlight.dart'; +import '../../../core/whats_new/spotlight_ids.dart'; import 'app_icon_screen.dart'; import 'appearance_screen.dart'; import 'chat_background_screen.dart'; @@ -15,11 +17,13 @@ class _CustomizationCategory { final IconData icon; final String Function(AppLocalizations l10n) title; final WidgetBuilder builder; + final String spotlightId; const _CustomizationCategory({ required this.icon, required this.title, required this.builder, + required this.spotlightId, }); } @@ -38,26 +42,31 @@ class _CustomizationSectionState extends State { icon: Symbols.dark_mode, title: (l10n) => l10n.themeSettingsTitle, builder: (context) => const ThemeSettingsScreen(), + spotlightId: SpotlightIds.settingsTheme, ), _CustomizationCategory( icon: Symbols.styler, title: (l10n) => l10n.appearanceTitle, builder: (context) => const AppearanceScreen(), + spotlightId: SpotlightIds.settingsAppearance, ), _CustomizationCategory( icon: Symbols.wallpaper, title: (l10n) => l10n.customizationChatBackground, builder: (context) => const ChatBackgroundScreen(), + spotlightId: SpotlightIds.settingsChatBackground, ), _CustomizationCategory( icon: Symbols.text_fields, title: (l10n) => l10n.fontSettingsTitle, builder: (context) => const FontSettingsScreen(), + spotlightId: SpotlightIds.settingsFont, ), _CustomizationCategory( icon: Symbols.apps, title: (l10n) => l10n.customizationAppIcon, builder: (context) => const AppIconScreen(), + spotlightId: SpotlightIds.settingsAppIcon, ), ]; @@ -66,6 +75,10 @@ class _CustomizationSectionState extends State { setState(() => _expanded = !_expanded); } + void _expand() { + if (!_expanded) _toggle(); + } + void _open(_CustomizationCategory category) { Haptics.tap(); Navigator.push(context, MaterialPageRoute(builder: category.builder)); @@ -80,7 +93,12 @@ class _CustomizationSectionState extends State { depth: 6, child: Column( children: [ - _buildHeader(cs), + SpotlightTarget( + id: SpotlightIds.settingsCustomization, + borderRadius: const BorderRadius.vertical(top: Radius.circular(20)), + onActivate: _expand, + child: _buildHeader(cs), + ), AnimatedSize( duration: const Duration(milliseconds: 220), curve: Curves.easeInOut, @@ -153,11 +171,15 @@ class _CustomizationSectionState extends State { ), ); tiles.add( - SettingsNavTile( - icon: category.icon, - label: category.title(l10n), - onTap: () => _open(category), - isLast: i == _categories.length - 1, + SpotlightTarget( + id: category.spotlightId, + onActivate: () => _open(category), + child: SettingsNavTile( + icon: category.icon, + label: category.title(l10n), + onTap: () => _open(category), + isLast: i == _categories.length - 1, + ), ), ); } diff --git a/lib/frontend/screens/profile/debug_menu_screen.dart b/lib/frontend/screens/profile/debug_menu_screen.dart index 44a12243..b8b8b05a 100644 --- a/lib/frontend/screens/profile/debug_menu_screen.dart +++ b/lib/frontend/screens/profile/debug_menu_screen.dart @@ -1,16 +1,10 @@ import 'package:flutter/material.dart'; -import 'package:material_symbols_icons/symbols.dart'; import '../../../backend/modules/chats.dart'; import '../../../core/calls/call_controller.dart'; -import '../../../core/config/app_media_cache.dart'; import '../../../core/protocol/opcode_map.dart'; import '../../../core/protocol/packet.dart'; -import '../../../core/utils/format.dart'; import '../../../core/utils/logger.dart'; -import '../../../core/utils/media_cache.dart'; -import '../../../l10n/app_localizations.dart'; import '../../../main.dart'; -import '../../debug/cache_section.dart'; import '../../debug/feature_toggles_section.dart'; import '../../debug/header_section.dart'; import '../../debug/id_search_section.dart'; @@ -26,7 +20,6 @@ import '../../debug/server_section.dart'; import '../../debug/sync_probe_section.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/connection_status.dart'; -import '../../widgets/sheet_helpers.dart'; import '../../widgets/underline_tab_bar.dart'; import '../chats/profile_action_sheets.dart'; @@ -43,15 +36,12 @@ class _DebugMenuScreenState extends State { bool _hasSearched = false; final List _hits = []; final Map _errors = {}; - int _cacheSize = 0; - bool _clearingCache = false; bool _micSignalOn = true; final DebugServerController _server = DebugServerController(); @override void initState() { super.initState(); - _loadCacheSize(); _server.load(); } @@ -67,77 +57,6 @@ class _DebugMenuScreenState extends State { ); } - Future _loadCacheSize() async { - final size = await MediaCache.currentSize(); - if (mounted) setState(() => _cacheSize = size); - } - - Future _clearCache() async { - if (_clearingCache) return; - setState(() => _clearingCache = true); - final freed = await MediaCache.clear(); - if (!mounted) return; - setState(() { - _clearingCache = false; - _cacheSize = 0; - }); - showCustomNotification( - context, - 'Кэш очищен (${formatBytes(AppLocalizations.of(context)!, freed)})', - ); - } - - void _pickCacheLimit() { - final cs = Theme.of(context).colorScheme; - showModalBottomSheet( - context: context, - backgroundColor: cs.surfaceContainerHigh, - shape: kSheetShape, - builder: (sheetContext) => SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const SizedBox(height: 8), - Padding( - padding: const EdgeInsets.fromLTRB(20, 12, 20, 8), - child: Align( - alignment: Alignment.centerLeft, - child: Text( - 'Лимит кэша медиа', - style: TextStyle( - color: cs.onSurface, - fontSize: 18, - fontWeight: FontWeight.w600, - ), - ), - ), - ), - for (final preset in AppMediaCacheLimit.presets) - ListTile( - title: Text( - _limitLabel(preset), - style: TextStyle(color: cs.onSurface, fontSize: 16), - ), - trailing: AppMediaCacheLimit.current.value == preset - ? Icon(Symbols.check, color: cs.primary) - : null, - onTap: () { - AppMediaCacheLimit.save(preset); - Navigator.pop(sheetContext); - setState(() {}); - }, - ), - const SizedBox(height: 8), - ], - ), - ), - ); - } - - String _limitLabel(int bytes) => bytes <= 0 - ? 'Без лимита' - : formatBytes(AppLocalizations.of(context)!, bytes); - @override void dispose() { _server.dispose(); @@ -271,15 +190,6 @@ class _DebugMenuScreenState extends State { DebugQuickActionsSection( onExportLog: () => exportDebugLog(context), ), - DebugCacheSection( - cacheSize: _cacheSize, - clearingCache: _clearingCache, - cacheLimitLabel: _limitLabel( - AppMediaCacheLimit.current.value, - ), - onPickCacheLimit: _pickCacheLimit, - onClearCache: _clearCache, - ), DebugPreviewsSection( micSignalOn: _micSignalOn, onMicSignalChanged: _sendMicSignal, diff --git a/lib/frontend/screens/profile/devices_screen.dart b/lib/frontend/screens/profile/devices_screen.dart index 54535176..a1203599 100644 --- a/lib/frontend/screens/profile/devices_screen.dart +++ b/lib/frontend/screens/profile/devices_screen.dart @@ -341,9 +341,9 @@ class _DevicesScreenState extends State cs, id: session.uniqueId, title: - session.client + + _displayPlatform(session, session.client) + (session.current ? l10n.devicesCurrentSuffix : ''), - platform: session.info, + platform: _displayPlatform(session, session.info), location: session.location, status: session.current ? l10n.devicesOnlineStatus : null, time: session.current @@ -388,6 +388,21 @@ class _DevicesScreenState extends State ); } + static final _appleDevicePattern = RegExp( + r'iphone|ipad', + caseSensitive: false, + ); + static final _androidPattern = RegExp(r'android', caseSensitive: false); + + String _displayPlatform(SessionInfo session, String text) { + if (kIsWeb || defaultTargetPlatform != TargetPlatform.iOS) return text; + final isAppleDevice = + _appleDevicePattern.hasMatch(session.client) || + _appleDevicePattern.hasMatch(session.info); + if (!isAppleDevice) return text; + return text.replaceAll(_androidPattern, 'iOS'); + } + Widget _buildShimmerItem(ColorScheme cs) { return AnimatedBuilder( animation: _shimmerController, diff --git a/lib/frontend/screens/profile/komet_settings_screen.dart b/lib/frontend/screens/profile/komet_settings_screen.dart index 3a9f3670..649f2cd6 100644 --- a/lib/frontend/screens/profile/komet_settings_screen.dart +++ b/lib/frontend/screens/profile/komet_settings_screen.dart @@ -99,6 +99,16 @@ class KometSettingsScreen extends StatelessWidget { onChanged: KometSettings.setShowTypingTime, ), ), + ValueListenableBuilder( + valueListenable: KometSettings.hideChannelRecommendations, + builder: (context, value, _) => SettingsToggleTile( + icon: Symbols.explore_off, + label: l10n.kometSettingsHideRecommendations, + subtitle: l10n.kometSettingsHideRecommendationsSubtitle, + value: value, + onChanged: KometSettings.setHideChannelRecommendations, + ), + ), ], ), const SizedBox(height: 20), @@ -128,7 +138,6 @@ class KometSettingsScreen extends StatelessWidget { onChanged: KometSettings.setShowHiddenChats, ), ), - ], ), const SizedBox(height: 20), @@ -156,7 +165,17 @@ class KometSettingsScreen extends StatelessWidget { label: 'Anti read', subtitle: l10n.kometSettingsAntiReadSubtitle, value: value, - onChanged: KometSettings.setAntiRead, + onChanged: _setAntiRead, + ), + ), + ValueListenableBuilder( + valueListenable: KometSettings.antiStoryView, + builder: (context, value, _) => SettingsToggleTile( + icon: Symbols.history_toggle_off, + label: 'Anti story view', + subtitle: l10n.kometSettingsAntiStoryViewSubtitle, + value: value, + onChanged: KometSettings.setAntiStoryView, ), ), ], @@ -199,7 +218,17 @@ class KometSettingsScreen extends StatelessWidget { Future _setGhostMode(bool value) async { await KometSettings.setGhostMode(value); - if (!value) await chats.restoreGhostReads(); + await _restoreReadsWhenSent(); api.sendPing(interactive: !value); } + + Future _setAntiRead(bool value) async { + await KometSettings.setAntiRead(value); + await _restoreReadsWhenSent(); + } + + Future _restoreReadsWhenSent() async { + if (KometSettings.ghostMode.value || KometSettings.antiRead.value) return; + await chats.restoreGhostReads(); + } } diff --git a/lib/frontend/screens/profile/password_entry_screen.dart b/lib/frontend/screens/profile/password_entry_screen.dart index b389ab92..521d6958 100644 --- a/lib/frontend/screens/profile/password_entry_screen.dart +++ b/lib/frontend/screens/profile/password_entry_screen.dart @@ -3,6 +3,7 @@ import 'package:material_symbols_icons/symbols.dart'; import '../../../main.dart' show accountModule; import '../../../core/storage/app_database.dart'; import '../../../l10n/app_localizations.dart'; +import '../../widgets/alert_note.dart'; import '../../widgets/animated_slash_icon.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/glossy_pill.dart'; @@ -283,17 +284,9 @@ class _PasswordEntryScreenState extends State { ), const SizedBox(height: 20), if (_errorMessage != null) - Container( - padding: const EdgeInsets.all(12), + AlertNote( + _errorMessage!, margin: const EdgeInsets.only(bottom: 12), - decoration: BoxDecoration( - color: cs.errorContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Text( - _errorMessage!, - style: TextStyle(color: cs.onErrorContainer), - ), ), _PasswordField( controller: _passwordController, @@ -694,28 +687,9 @@ class _TwoFactorSetupScreenState extends State { _buildStepIndicator(cs), const SizedBox(height: 24), if (_errorMessage != null) - Container( - padding: const EdgeInsets.all(12), + AlertNote( + _errorMessage!, margin: const EdgeInsets.only(bottom: 16), - decoration: BoxDecoration( - color: cs.errorContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Row( - children: [ - Icon(Symbols.error, color: cs.error, size: 20), - const SizedBox(width: 8), - Expanded( - child: Text( - _errorMessage!, - style: TextStyle( - color: cs.onErrorContainer, - fontSize: 14, - ), - ), - ), - ], - ), ), _buildCurrentStep(cs), const SizedBox(height: 24), @@ -1066,17 +1040,9 @@ class _TwoFactorPasswordChangeScreenState crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_errorMessage != null) - Container( - padding: const EdgeInsets.all(12), + AlertNote( + _errorMessage!, margin: const EdgeInsets.only(bottom: 16), - decoration: BoxDecoration( - color: cs.errorContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Text( - _errorMessage!, - style: TextStyle(color: cs.onErrorContainer), - ), ), Text( l10n.passwordEntryNewPassword, @@ -1244,17 +1210,9 @@ class _TwoFactorEmailChangeScreenState crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_errorMessage != null) - Container( - padding: const EdgeInsets.all(12), + AlertNote( + _errorMessage!, margin: const EdgeInsets.only(bottom: 16), - decoration: BoxDecoration( - color: cs.errorContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Text( - _errorMessage!, - style: TextStyle(color: cs.onErrorContainer), - ), ), if (_step == 0) ...[ Text( @@ -1403,38 +1361,15 @@ class _TwoFactorRemoveScreenState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Container( - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: cs.errorContainer.withValues(alpha: 0.5), - borderRadius: BorderRadius.circular(12), - ), - child: Row( - children: [ - Icon(Symbols.warning, color: cs.error), - const SizedBox(width: 12), - Expanded( - child: Text( - l10n.passwordEntryRemoveWarning, - style: TextStyle(color: cs.onSurface), - ), - ), - ], - ), + AlertNote( + l10n.passwordEntryRemoveWarning, + icon: Symbols.warning, ), const SizedBox(height: 24), if (_errorMessage != null) - Container( - padding: const EdgeInsets.all(12), + AlertNote( + _errorMessage!, margin: const EdgeInsets.only(bottom: 16), - decoration: BoxDecoration( - color: cs.errorContainer, - borderRadius: BorderRadius.circular(12), - ), - child: Text( - _errorMessage!, - style: TextStyle(color: cs.onErrorContainer), - ), ), SizedBox( width: double.infinity, diff --git a/lib/frontend/screens/profile/settings_tab.dart b/lib/frontend/screens/profile/settings_tab.dart index 4fd9691b..be57d017 100644 --- a/lib/frontend/screens/profile/settings_tab.dart +++ b/lib/frontend/screens/profile/settings_tab.dart @@ -3,7 +3,7 @@ import 'dart:math' as math; import 'dart:ui' show lerpDouble; import 'package:cached_network_image/cached_network_image.dart'; -import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/foundation.dart' show kIsWeb, listEquals; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show HapticFeedback; import 'package:material_symbols_icons/symbols.dart'; @@ -24,6 +24,9 @@ import '../../../main.dart'; import '../../../backend/modules/contacts.dart'; import '../../widgets/animated_slash_icon.dart'; import 'media_devices_screen.dart'; +import 'storage_screen.dart'; +import '../../widgets/spotlight.dart'; +import '../../../core/whats_new/spotlight_ids.dart'; import '../../widgets/attachment/photo_hero.dart'; import '../../widgets/avatar_gallery.dart'; import '../../widgets/badged_icon.dart'; @@ -317,7 +320,8 @@ class _SettingsTabState extends State AvatarPhoto? get _currentAvatar { if (_avatarPhotos.isEmpty) return null; - return _avatarPhotos[_avatarIndex.clamp(0, _avatarPhotos.length - 1) + return _avatarPhotos[_avatarIndex + .clamp(0, _avatarPhotos.length - 1) .toInt()]; } @@ -724,6 +728,7 @@ class _SettingsTabState extends State color: cs.onSurfaceVariant, ), label: l10n.chatSettingsTitle, + spotlightId: SpotlightIds.settingsChats, onTap: () { Navigator.push( context, @@ -737,6 +742,7 @@ class _SettingsTabState extends State _SettingsItem( icon: Symbols.notifications_active, label: l10n.notificationsTitle, + spotlightId: SpotlightIds.settingsNotifications, onTap: () { Navigator.push( context, @@ -750,6 +756,7 @@ class _SettingsTabState extends State _SettingsItem( icon: Symbols.translate, label: l10n.loginLanguage, + spotlightId: SpotlightIds.settingsLanguage, onTap: () { Navigator.push( context, @@ -762,6 +769,7 @@ class _SettingsTabState extends State _SettingsItem( icon: Symbols.videocam, label: l10n.mediaDevicesTitle, + spotlightId: SpotlightIds.settingsMediaDevices, onTap: () { Navigator.push( context, @@ -772,16 +780,32 @@ class _SettingsTabState extends State ); }, ), + if (!kIsWeb) + _SettingsItem( + icon: Symbols.storage, + label: l10n.storageTitle, + spotlightId: SpotlightIds.settingsStorage, + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => const StorageScreen(), + ), + ); + }, + ), _SettingsItem( icon: Symbols.cloud, label: BuildProfile.isStoreRelease ? l10n.settingsTabCloudStorage : l10n.settingsTabCloudStorageBeta, + spotlightId: SpotlightIds.settingsCloud, onTap: () => _openCloudStorage(context), ), _SettingsItem( icon: Symbols.vpn_lock, label: l10n.proxySettingsTitle, + spotlightId: SpotlightIds.settingsProxy, onTap: () { final cs = Theme.of(context).colorScheme; showModalBottomSheet( @@ -800,8 +824,10 @@ class _SettingsTabState extends State if (BuildProfile.spoofUi) _SettingsItem( icon: Symbols.shield_lock, - label: AppLocalizations.of(context)! - .profileMenuSpoof, + label: AppLocalizations.of( + context, + )!.profileMenuSpoof, + spotlightId: SpotlightIds.settingsSpoof, onTap: () { Navigator.push( context, @@ -814,6 +840,7 @@ class _SettingsTabState extends State _SettingsItem( icon: Symbols.lock, label: l10n.securityTitle, + spotlightId: SpotlightIds.settingsSecurity, onTap: () { Navigator.push( context, @@ -829,6 +856,7 @@ class _SettingsTabState extends State _SettingsItem( icon: Symbols.devices, label: l10n.devicesTitle, + spotlightId: SpotlightIds.settingsDevices, onTap: () { Navigator.push( context, @@ -920,6 +948,7 @@ class _SettingsTabState extends State color: cs.onSurfaceVariant, ), label: 'Komet', + spotlightId: SpotlightIds.settingsKomet, onTap: () { Navigator.push( context, @@ -1554,7 +1583,7 @@ class _SettingsTabState extends State return SettingsCard( children: List.generate(items.length, (index) { final item = items[index]; - return SettingsNavTile( + final tile = SettingsNavTile( icon: item.icon, leading: item.leading, label: item.label, @@ -1562,6 +1591,13 @@ class _SettingsTabState extends State onTap: item.onTap, isLast: index == items.length - 1, ); + final spotlightId = item.spotlightId; + if (spotlightId == null) return tile; + return SpotlightTarget( + id: spotlightId, + onActivate: item.onTap, + child: tile, + ); }), ); } @@ -1573,6 +1609,7 @@ class _SettingsItem { final String label; final VoidCallback? onTap; final Color? tintColor; + final String? spotlightId; const _SettingsItem({ this.icon, @@ -1580,5 +1617,6 @@ class _SettingsItem { required this.label, this.onTap, this.tintColor, + this.spotlightId, }); } diff --git a/lib/frontend/screens/profile/storage_screen.dart b/lib/frontend/screens/profile/storage_screen.dart new file mode 100644 index 00000000..5746c00b --- /dev/null +++ b/lib/frontend/screens/profile/storage_screen.dart @@ -0,0 +1,845 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../../core/cache/cache_janitor.dart'; +import '../../../core/config/app_cache_limit.dart'; +import '../../../core/config/app_shape.dart'; +import '../../../core/whats_new/spotlight_ids.dart'; +import '../../../core/utils/format.dart'; +import '../../../core/utils/haptics.dart'; +import '../../../core/utils/route_settle.dart'; +import '../../../l10n/app_localizations.dart'; +import '../../widgets/confirm_dialog.dart'; +import '../../widgets/connection_status.dart'; +import '../../widgets/custom_notification.dart'; +import '../../widgets/route_probe.dart'; +import '../../widgets/section_header.dart'; +import '../../widgets/settings_card.dart'; +import '../../widgets/small_spinner.dart'; +import '../../widgets/spotlight.dart'; + +class StorageScreen extends StatefulWidget { + const StorageScreen({super.key}); + + @override + State createState() => _StorageScreenState(); +} + +class _StorageScreenState extends State { + late final RouteSettle _routeSettle = RouteSettle(isMounted: () => mounted); + StorageReport? _report; + bool _scanFailed = false; + bool _clearing = false; + final Set _selected = { + for (final category in StorageCategory.values) + if (category.evictable) category, + }; + int _limit = AppCacheLimit.current.value; + + @override + void initState() { + super.initState(); + unawaited(_scan()); + } + + @override + void dispose() { + _routeSettle.dispose(); + super.dispose(); + } + + static int _presetIndexOf(int limit) { + const presets = AppCacheLimit.presets; + final exact = presets.indexOf(limit); + if (exact != -1) return exact; + var nearest = 0; + for (var i = 0; i < presets.length; i++) { + final preset = presets[i]; + if (preset == AppCacheLimit.unlimited) continue; + if ((preset - limit).abs() < (presets[nearest] - limit).abs()) { + nearest = i; + } + } + return nearest; + } + + Future _scan() async { + try { + final report = await CacheJanitor.instance.scan(); + _routeSettle.run( + () => setState(() { + _report = report; + _scanFailed = false; + }), + ); + } catch (_) { + _routeSettle.run(() => setState(() => _scanFailed = true)); + } + } + + void _toggle(StorageCategory category) { + Haptics.selection(); + setState(() { + if (!_selected.remove(category)) _selected.add(category); + }); + } + + Future _clear() async { + final report = _report; + if (report == null || _clearing) return; + final l10n = AppLocalizations.of(context)!; + final categories = { + for (final category in _selected) + if (report.of(category) > 0) category, + }; + if (categories.isEmpty) return; + if (categories.contains(StorageCategory.keptMedia)) { + final confirmed = await showConfirmDialog( + context, + message: l10n.storageClearKeptMessage, + confirmLabel: l10n.storageClearKeptConfirm, + destructive: true, + ); + if (!confirmed || !mounted) return; + } + setState(() => _clearing = true); + try { + final (:freed, :report) = await CacheJanitor.instance.clear(categories); + if (!mounted) return; + setState(() { + _report = report; + _clearing = false; + }); + showCustomNotification( + context, + l10n.storageCleared(formatBytes(l10n, freed)), + ); + } catch (_) { + if (!mounted) return; + setState(() => _clearing = false); + showCustomNotification(context, l10n.storageClearFailed); + } + } + + void _onLimitChanged(double value) { + final limit = AppCacheLimit.presets[value.round()]; + if (limit == _limit) return; + Haptics.selection(); + setState(() => _limit = limit); + } + + Future _onLimitChangeEnd(double value) async { + await AppCacheLimit.save(AppCacheLimit.presets[value.round()]); + final report = await CacheJanitor.instance.trim(); + if (!mounted) return; + if (report == null) { + await _scan(); + } else { + setState(() => _report = report); + } + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + + return RouteProbe( + onRoute: _routeSettle.bind, + child: Scaffold( + backgroundColor: cs.surface, + appBar: ConnectionTitleBar( + titleText: l10n.storageTitle, + backgroundColor: cs.surface, + ), + body: SafeArea( + top: false, + child: ListView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.fromLTRB(16, 12, 16, 120), + children: [ + SpotlightTarget( + id: SpotlightIds.storageUsage, + borderRadius: AppShape.cardRadius, + child: SettingsPanel(child: _buildUsage(context)), + ), + const SizedBox(height: 20), + SectionHeader( + l10n.storageLimitTitle, + padding: const EdgeInsets.fromLTRB(8, 0, 8, 8), + ), + SpotlightTarget( + id: SpotlightIds.storageLimit, + borderRadius: AppShape.cardRadius, + child: SettingsPanel( + child: _LimitPicker( + limit: _limit, + index: _presetIndexOf(_limit), + onChanged: _onLimitChanged, + onChangeEnd: _onLimitChangeEnd, + ), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildUsage(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final report = _report; + final still = MediaQuery.disableAnimationsOf(context); + + final Widget child; + if (report != null) { + child = _UsagePanel( + key: const ValueKey('usage'), + report: report, + selected: _selected, + clearing: _clearing, + onToggle: _toggle, + onClear: _clear, + ); + } else { + child = SizedBox( + key: ValueKey(_scanFailed), + height: 160, + child: Center( + child: _scanFailed + ? Text( + l10n.storageScanFailed, + textAlign: TextAlign.center, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), + ) + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + SmallSpinner(size: 20, color: cs.onSurfaceVariant), + const SizedBox(width: 12), + Text( + l10n.storageScanning, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 14, + ), + ), + ], + ), + ), + ); + } + + return AnimatedSize( + duration: still ? Duration.zero : const Duration(milliseconds: 360), + curve: Curves.easeOutCubic, + alignment: Alignment.topCenter, + child: AnimatedSwitcher( + duration: still ? Duration.zero : const Duration(milliseconds: 220), + switchOutCurve: const Threshold(1), + layoutBuilder: (current, previous) => Stack( + alignment: Alignment.topCenter, + children: [...previous, ?current], + ), + child: child, + ), + ); + } +} + +abstract final class _Motion { + static const Duration reveal = Duration(milliseconds: 1100); + static const Duration change = Duration(milliseconds: 480); + static const Duration collapseGrace = Duration(milliseconds: 80); + static const Curve curve = Curves.easeOutCubic; + static const Interval sweep = Interval(0, 0.7, curve: Curves.easeOutCubic); + + static Interval row(int index) { + final start = (0.18 + index * 0.08).clamp(0.0, 0.7); + return Interval(start, (start + 0.4).clamp(0.0, 1.0), curve: curve); + } +} + +class _UsagePanel extends StatefulWidget { + const _UsagePanel({ + super.key, + required this.report, + required this.selected, + required this.clearing, + required this.onToggle, + required this.onClear, + }); + + final StorageReport report; + final Set selected; + final bool clearing; + final ValueChanged onToggle; + final VoidCallback onClear; + + @override + State<_UsagePanel> createState() => _UsagePanelState(); +} + +class _UsagePanelState extends State<_UsagePanel> + with SingleTickerProviderStateMixin { + late final AnimationController _reveal = AnimationController( + vsync: this, + duration: _Motion.reveal, + ); + late final Animation _sweep = _reveal.drive( + CurveTween(curve: _Motion.sweep), + ); + final Map> _entrances = {}; + final Set _collapsing = {}; + Timer? _collapseTimer; + + Animation _entrance(int index) => _entrances.putIfAbsent( + index, + () => _reveal.drive(CurveTween(curve: _Motion.row(index))), + ); + + @override + void didUpdateWidget(_UsagePanel oldWidget) { + super.didUpdateWidget(oldWidget); + final gone = [ + for (final category in StorageCategory.values) + if (oldWidget.report.of(category) > 0 && + widget.report.of(category) == 0) + category, + ]; + if (gone.isEmpty) return; + _collapsing.addAll(gone); + _collapseTimer?.cancel(); + _collapseTimer = Timer(_Motion.change + _Motion.collapseGrace, () { + if (mounted) setState(_collapsing.clear); + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (MediaQuery.disableAnimationsOf(context)) { + _reveal.value = 1; + } else if (_reveal.isDismissed) { + _reveal.forward(); + } + } + + @override + void dispose() { + _collapseTimer?.cancel(); + _reveal.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final report = widget.report; + final still = MediaQuery.disableAnimationsOf(context); + final change = still ? Duration.zero : _Motion.change; + final total = report.total; + final selectedBytes = widget.selected + .where((category) => category.clearable) + .fold(0, (sum, category) => sum + report.of(category)); + final cacheBytes = StorageCategory.values + .where((category) => category.clearable) + .fold(0, (sum, category) => sum + report.of(category)); + + var shown = 0; + final rows = [ + for (final category in StorageCategory.values) + if (report.of(category) > 0 || _collapsing.contains(category)) + _RowSlot( + key: ValueKey(category), + visible: report.of(category) > 0, + duration: change, + entrance: _entrance(report.of(category) > 0 ? shown++ : shown), + child: _UsageRow( + category: category, + bytes: report.of(category), + total: total, + duration: still ? Duration.zero : _Motion.reveal, + selected: widget.selected.contains(category), + onToggle: category.clearable && !widget.clearing + ? () => widget.onToggle(category) + : null, + ), + ), + ]; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _CountingBytes( + bytes: total, + duration: still ? Duration.zero : _Motion.reveal, + builder: (context, bytes) => Text( + formatBytes(l10n, bytes), + style: TextStyle( + color: cs.onSurface, + fontSize: 48, + fontWeight: FontWeight.w600, + height: 1.1, + ), + ), + ), + const SizedBox(height: 2), + Text( + l10n.storageTotalCaption, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 13), + ), + const SizedBox(height: 18), + _UsageBar(report: report, reveal: _sweep, duration: change), + const SizedBox(height: 10), + ...rows, + const SizedBox(height: 16), + FilledButton( + onPressed: selectedBytes > 0 && !widget.clearing + ? widget.onClear + : null, + style: FilledButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 14), + ), + child: widget.clearing + ? SmallSpinner(size: 20, color: cs.onPrimary) + : Text( + cacheBytes == 0 + ? l10n.storageEmpty + : selectedBytes == 0 + ? l10n.storageNothingSelected + : l10n.storageClear(formatBytes(l10n, selectedBytes)), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ); + } +} + +class _CountingBytes extends StatelessWidget { + const _CountingBytes({ + required this.bytes, + required this.duration, + required this.builder, + }); + + final int bytes; + final Duration duration; + final Widget Function(BuildContext context, int bytes) builder; + + @override + Widget build(BuildContext context) => TweenAnimationBuilder( + tween: Tween(begin: 0, end: bytes.toDouble()), + duration: duration, + curve: _Motion.curve, + builder: (context, value, _) => builder(context, value.round()), + ); +} + +abstract final class _StoragePalette { + static const List _light = [ + Color(0xFF2A78D6), + Color(0xFFEB6834), + Color(0xFF1BAF7A), + Color(0xFFEDA100), + Color(0xFFE87BA4), + Color(0xFF008300), + ]; + static const List _dark = [ + Color(0xFF3987E5), + Color(0xFFD95926), + Color(0xFF199E70), + Color(0xFFC98500), + Color(0xFFD55181), + Color(0xFF008300), + ]; + + static Color of(BuildContext context, StorageCategory category) { + final theme = Theme.of(context); + if (!category.clearable) return theme.colorScheme.outline; + final series = theme.brightness == Brightness.dark ? _dark : _light; + return series[category.index]; + } +} + +String _categoryLabel(AppLocalizations l10n, StorageCategory category) => + switch (category) { + StorageCategory.photos => l10n.storageCategoryPhotos, + StorageCategory.videos => l10n.storageCategoryVideos, + StorageCategory.files => l10n.storageCategoryFiles, + StorageCategory.voice => l10n.storageCategoryVoice, + StorageCategory.stickers => l10n.storageCategoryStickers, + StorageCategory.keptMedia => l10n.storageCategoryKept, + StorageCategory.database => l10n.storageCategoryDatabase, + }; + +String? _categoryHint(AppLocalizations l10n, StorageCategory category) => + switch (category) { + StorageCategory.keptMedia => l10n.storageCategoryKeptHint, + StorageCategory.database => l10n.storageCategoryDatabaseHint, + _ => null, + }; + +final Map<(String, int), NumberFormat> _percentFormats = {}; + +String _shareLabel(BuildContext context, int bytes, int total) { + final locale = Localizations.localeOf(context).toString(); + final share = total == 0 ? 0.0 : bytes / total; + final digits = share > 0 && share < 0.01 ? 1 : 0; + final format = _percentFormats.putIfAbsent(( + locale, + digits, + ), () => NumberFormat.percentPattern(locale)..maximumFractionDigits = digits); + return format.format(share); +} + +class _UsageBar extends StatelessWidget { + const _UsageBar({ + required this.report, + required this.reveal, + required this.duration, + }); + + static const double _height = 8; + static const double _gap = 2; + static const double _minPart = 3; + + final StorageReport report; + final Animation reveal; + final Duration duration; + + List _widths(double usable, List sizes) { + final total = report.total; + if (total == 0) return [for (final _ in sizes) 0]; + final raw = [for (final size in sizes) usable * size / total]; + final visible = [ + for (final w in raw) + if (w > 0) w, + ]; + final small = visible.where((w) => w < _minPart).length; + final largeSum = visible + .where((w) => w >= _minPart) + .fold(0.0, (a, b) => a + b); + final rest = usable - small * _minPart; + return [ + for (final w in raw) + if (w <= 0) + 0 + else if (w < _minPart) + _minPart + else + largeSum > 0 ? w / largeSum * rest : w, + ]; + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final total = report.total; + final categories = StorageCategory.values; + final sizes = [for (final category in categories) report.of(category)]; + final description = [ + for (final category in categories) + if (report.of(category) > 0) + '${_categoryLabel(l10n, category)} ' + '${formatBytes(l10n, report.of(category))} ' + '${_shareLabel(context, report.of(category), total)}', + ].join(', '); + + return Semantics( + label: description, + child: ExcludeSemantics( + child: SizedBox( + height: _height, + child: LayoutBuilder( + builder: (context, constraints) { + final full = constraints.maxWidth; + final visibleCount = sizes.where((size) => size > 0).length; + final usable = (full - _gap * (visibleCount - 1).clamp(0, 99)) + .clamp(0.0, double.infinity); + final widths = _widths(usable, sizes); + var seenVisible = false; + final segments = []; + for (var i = 0; i < categories.length; i++) { + final visible = widths[i] > 0; + final leadingGap = visible && seenVisible ? _gap : 0.0; + if (visible) seenVisible = true; + segments.add( + AnimatedContainer( + key: ValueKey(categories[i]), + duration: duration, + curve: _Motion.curve, + width: widths[i], + margin: EdgeInsets.only(left: leadingGap), + color: _StoragePalette.of(context, categories[i]), + child: visible + ? Tooltip( + message: + '${_categoryLabel(l10n, categories[i])} · ' + '${formatBytes(l10n, sizes[i])} · ' + '${_shareLabel(context, sizes[i], total)}', + child: const SizedBox.expand(), + ) + : null, + ), + ); + } + return Align( + alignment: Alignment.centerLeft, + child: ClipRRect( + borderRadius: BorderRadius.circular(_height / 2), + child: AnimatedBuilder( + animation: reveal, + builder: (context, child) => Align( + alignment: Alignment.centerLeft, + widthFactor: reveal.value, + child: child, + ), + child: SizedBox( + width: full, + height: _height, + child: OverflowBox( + alignment: Alignment.centerLeft, + maxWidth: double.infinity, + child: Row( + mainAxisSize: MainAxisSize.min, + children: segments, + ), + ), + ), + ), + ), + ); + }, + ), + ), + ), + ); + } +} + +class _RowSlot extends StatelessWidget { + const _RowSlot({ + super.key, + required this.visible, + required this.duration, + required this.entrance, + required this.child, + }); + + final bool visible; + final Duration duration; + final Animation entrance; + final Widget child; + + @override + Widget build(BuildContext context) { + return AnimatedCrossFade( + duration: duration, + sizeCurve: _Motion.curve, + alignment: Alignment.topCenter, + crossFadeState: visible + ? CrossFadeState.showFirst + : CrossFadeState.showSecond, + firstChild: FadeTransition( + opacity: entrance, + child: SlideTransition( + position: entrance.drive( + Tween(begin: const Offset(0, 0.35), end: Offset.zero), + ), + child: child, + ), + ), + secondChild: const SizedBox(width: double.infinity), + ); + } +} + +class _UsageRow extends StatelessWidget { + const _UsageRow({ + required this.category, + required this.bytes, + required this.total, + required this.duration, + required this.selected, + required this.onToggle, + }); + + final StorageCategory category; + final int bytes; + final int total; + final Duration duration; + final bool selected; + final VoidCallback? onToggle; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final hint = _categoryHint(l10n, category); + + return InkWell( + onTap: onToggle, + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row( + children: [ + SizedBox( + width: 40, + child: category.clearable + ? Checkbox( + value: selected, + onChanged: onToggle == null ? null : (_) => onToggle!(), + ) + : Icon( + Symbols.lock, + size: 20, + weight: 400, + color: cs.onSurfaceVariant, + ), + ), + const SizedBox(width: 6), + Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: _StoragePalette.of(context, category), + borderRadius: BorderRadius.circular(3), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + _categoryLabel(l10n, category), + style: TextStyle( + color: cs.onSurface, + fontSize: 15.5, + fontWeight: FontWeight.w500, + ), + ), + if (hint != null) + Text( + hint, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 12.5, + height: 1.3, + ), + ), + ], + ), + ), + const SizedBox(width: 12), + _CountingBytes( + bytes: bytes, + duration: duration, + builder: (context, shown) => Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + formatBytes(l10n, shown), + style: TextStyle( + color: cs.onSurface, + fontSize: 15, + fontWeight: FontWeight.w600, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + Text( + _shareLabel(context, shown, total), + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 12, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _LimitPicker extends StatelessWidget { + const _LimitPicker({ + required this.limit, + required this.index, + required this.onChanged, + required this.onChangeEnd, + }); + + final int limit; + final int index; + final ValueChanged onChanged; + final ValueChanged onChangeEnd; + + static String _label(AppLocalizations l10n, int bytes) => + bytes == AppCacheLimit.unlimited + ? l10n.storageLimitUnlimited + : formatBytes(l10n, bytes); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + const presets = AppCacheLimit.presets; + final hint = cs.onSurfaceVariant; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + _label(l10n, limit), + style: TextStyle( + color: cs.onSurface, + fontSize: 20, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 4), + Slider( + value: index.toDouble(), + max: (presets.length - 1).toDouble(), + divisions: presets.length - 1, + onChanged: onChanged, + onChangeEnd: onChangeEnd, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + _label(l10n, presets.first), + style: TextStyle(color: hint, fontSize: 11), + ), + Text( + _label(l10n, presets.last), + style: TextStyle(color: hint, fontSize: 11), + ), + ], + ), + const SizedBox(height: 14), + Text( + l10n.storageLimitHint, + style: TextStyle(color: hint, fontSize: 13, height: 1.35), + ), + ], + ); + } +} diff --git a/lib/frontend/screens/stories/story_viewer_screen.dart b/lib/frontend/screens/stories/story_viewer_screen.dart index ae1a34c4..526ce999 100644 --- a/lib/frontend/screens/stories/story_viewer_screen.dart +++ b/lib/frontend/screens/stories/story_viewer_screen.dart @@ -12,11 +12,20 @@ import 'package:video_player/video_player.dart'; import '../../../core/protocol/packet.dart'; import '../../../core/storage/app_database.dart'; import '../../../core/utils/haptics.dart'; +import '../../../backend/modules/complaints.dart'; +import '../../../backend/modules/stories.dart'; +import '../../../backend/modules/story_reply_sender.dart'; +import '../../../core/media/thumbhash.dart'; +import '../../../core/media/video_preloader.dart'; +import '../../../core/utils/media_saver.dart'; import '../../../core/media/video_request_headers.dart'; -import '../../../main.dart' show api, storiesModule; +import '../../../core/utils/media_cache.dart'; +import '../../../main.dart' show api, appRouteObserver, storiesModule; import '../../../models/story.dart'; import '../../widgets/custom_notification.dart'; import '../../widgets/komet_avatar.dart'; +import '../../widgets/max_link_nav.dart'; +import '../../widgets/route_probe.dart'; import '../chats/profile_action_sheets.dart'; import '../../widgets/small_spinner.dart'; import 'story_owner_info.dart'; @@ -24,9 +33,41 @@ import '../../../core/config/app_frost.dart'; import '../../../core/config/app_fonts.dart'; import '../../../l10n/app_localizations.dart'; import '../../widgets/official_name.dart'; +import '../../../core/utils/media_cache_names.dart'; const Duration _photoDuration = Duration(seconds: 5); +enum StoryViewerMenuAction { profile, hide, save, report, delete } + +List storyViewerMenuActions({ + required bool isOwn, + bool opensProfile = false, + bool allowsHidingAuthor = false, + bool allowsSaving = false, + bool allowsComplaints = false, +}) => isOwn + ? const [StoryViewerMenuAction.save, StoryViewerMenuAction.delete] + : [ + if (opensProfile) StoryViewerMenuAction.profile, + if (allowsHidingAuthor) StoryViewerMenuAction.hide, + if (allowsSaving) StoryViewerMenuAction.save, + if (allowsComplaints) StoryViewerMenuAction.report, + ]; + +Duration storySeekPosition({ + required Duration start, + required double deltaX, + required double viewportWidth, + required Duration duration, +}) { + final total = duration.inMicroseconds; + if (total <= 0) return Duration.zero; + final width = viewportWidth.abs() < 1 ? 1.0 : viewportWidth.abs(); + final delta = (total * deltaX / width).round(); + final target = (start.inMicroseconds + delta).clamp(0, total).toInt(); + return Duration(microseconds: target); +} + Offset? storyOriginOf(BuildContext context) { final box = context.findRenderObject() as RenderBox?; if (box == null || !box.hasSize) return null; @@ -41,17 +82,20 @@ Future openStoryViewer( required List previews, int initialIndex = 0, Map ownerOverrides = const {}, + Map> initialStories = const {}, Offset? origin, }) { return Navigator.of(context).push( PageRouteBuilder( opaque: false, + allowSnapshotting: false, transitionDuration: const Duration(milliseconds: 420), reverseTransitionDuration: const Duration(milliseconds: 320), pageBuilder: (_, _, _) => StoryViewerScreen( previews: previews, initialIndex: initialIndex, ownerOverrides: ownerOverrides, + initialStories: initialStories, ), transitionsBuilder: (context, animation, _, child) { return AnimatedBuilder( @@ -108,12 +152,14 @@ class StoryViewerScreen extends StatefulWidget { final List previews; final int initialIndex; final Map ownerOverrides; + final Map> initialStories; const StoryViewerScreen({ super.key, required this.previews, this.initialIndex = 0, this.ownerOverrides = const {}, + this.initialStories = const {}, }); @override @@ -121,7 +167,7 @@ class StoryViewerScreen extends StatefulWidget { } class _StoryViewerScreenState extends State - with SingleTickerProviderStateMixin { + with SingleTickerProviderStateMixin, RouteAware { late final PageController _ownerController; late int _ownerIndex; late final AnimationController _photoProgress; @@ -133,15 +179,27 @@ class _StoryViewerScreenState extends State final ValueNotifier _segment = ValueNotifier(0); int _storyIndex = 0; bool _paused = false; + bool _seeking = false; + double? _seekStartX; + Duration _seekStartPosition = Duration.zero; + Duration? _seekPreviewPosition; + Duration? _pendingSeekPosition; + bool _seekBusy = false; + bool _finishSeekWhenIdle = false; + int _seekEpoch = 0; double _dragDy = 0; bool _dragging = false; static const double _dismissThreshold = 120; VideoPlayerController? _video; + final ValueNotifier _videoLoading = ValueNotifier(null); + int _videoEpoch = 0; int _myId = 0; bool _deleting = false; + ModalRoute? _route; + bool _resumeWhenUncovered = false; StoryPreview get _owner => widget.previews[_ownerIndex]; @@ -158,6 +216,7 @@ class _StoryViewerScreenState extends State super.initState(); _ownerIndex = widget.initialIndex.clamp(0, widget.previews.length - 1); _ownerController = PageController(initialPage: _ownerIndex); + _stories.addAll(widget.initialStories); _photoProgress = AnimationController(vsync: this, duration: _photoDuration) ..addListener(() => _segment.value = _photoProgress.value) ..addStatusListener((s) { @@ -181,7 +240,9 @@ class _StoryViewerScreenState extends State @override void dispose() { + appRouteObserver.unsubscribe(this); _disposeVideo(); + _videoLoading.dispose(); _photoProgress.dispose(); _segment.dispose(); _ownerController.dispose(); @@ -189,6 +250,15 @@ class _StoryViewerScreenState extends State } void _disposeVideo() { + _videoEpoch++; + _seekEpoch++; + _seeking = false; + _seekStartX = null; + _seekPreviewPosition = null; + _pendingSeekPosition = null; + _seekBusy = false; + _finishSeekWhenIdle = false; + _videoLoading.value = null; _video?.removeListener(_onVideoTick); _video?.dispose(); _video = null; @@ -235,26 +305,48 @@ class _StoryViewerScreenState extends State final story = _currentStory; if (story == null) return; - _markViewed(story); storiesModule.setLastViewed(story.owner.ownerId, story.id); final media = story.media; if (media != null && media.isVideo && (media.url?.isNotEmpty ?? false)) { - _startVideo(media.url!); + unawaited(_startVideo(story, media.url!)); } else { + _markViewed(story); _photoProgress.forward(from: 0); } + _preloadAfter(index); } - Future _startVideo(String url) async { - final uri = Uri.parse(url); - final controller = VideoPlayerController.networkUrl( - uri, - httpHeaders: videoRequestHeaders( - uri, - sessionUserAgent: api.session?.userAgent(), + static Map _cdnHeaders(Uri uri) => + videoRequestHeaders(uri, sessionUserAgent: api.session?.userAgent()); + + static String _videoCacheName(Story story) => + storyVideoCacheName(story.owner.ownerId, story.id); + + static const int _storyVideoMaxBytes = 64 * 1024 * 1024; + + void _cacheVideo(Story story, String url) { + unawaited( + VideoPreloader.load( + _videoCacheName(story), + () async => url, + headers: _cdnHeaders, + maxBytes: _storyVideoMaxBytes, + cancelled: () => !mounted, ), ); + } + + Future _startVideo(Story story, String url) async { + final epoch = _videoEpoch; + _videoLoading.value = 0; + final cached = await MediaCache.existing(_videoCacheName(story)); + if (!mounted || epoch != _videoEpoch) return; + final uri = Uri.parse(url); + final controller = cached != null + ? VideoPlayerController.file(cached) + : VideoPlayerController.networkUrl(uri, httpHeaders: _cdnHeaders(uri)); + if (cached == null) _cacheVideo(story, url); _video = controller; try { await controller.initialize(); @@ -263,23 +355,44 @@ class _StoryViewerScreenState extends State return; } controller.addListener(_onVideoTick); - await controller.play(); - setState(() {}); + _videoLoading.value = null; + _markViewed(story); + if (!_paused) await controller.play(); + if (mounted) setState(() {}); } catch (_) { if (_video == controller) { _disposeVideo(); + _markViewed(story); _photoProgress.forward(from: 0); } } } + void _preloadAfter(int index) { + final next = index + 1 < _ownerStories.length + ? _ownerStories[index + 1] + : null; + final media = next?.media; + final url = media?.url; + if (next == null || media == null || !media.isVideo) return; + if (url == null || url.isEmpty) return; + _cacheVideo(next, url); + } + void _onVideoTick() { final c = _video; if (c == null || !c.value.isInitialized) return; final total = c.value.duration.inMilliseconds; if (total <= 0) return; - _segment.value = (c.value.position.inMilliseconds / total).clamp(0.0, 1.0); - if (c.value.position >= c.value.duration && !c.value.isPlaying) { + if (!_seeking) { + _segment.value = (c.value.position.inMilliseconds / total).clamp( + 0.0, + 1.0, + ); + } + if (!_seeking && + c.value.position >= c.value.duration && + !c.value.isPlaying) { _advance(); } } @@ -316,7 +429,7 @@ class _StoryViewerScreenState extends State curve: Curves.easeInOutCubic, ); } else { - Navigator.of(context).maybePop(); + _close(); } } @@ -346,11 +459,97 @@ class _StoryViewerScreenState extends State final video = _video; if (video != null && video.value.isInitialized) { paused ? video.pause() : video.play(); - } else { + } else if (_videoLoading.value == null) { paused ? _photoProgress.stop() : _photoProgress.forward(); } } + void _onStoryHoldStart(LongPressStartDetails details) { + final video = _video; + final canSeek = video != null && video.value.isInitialized; + _seekStartX = details.globalPosition.dx; + _seekStartPosition = canSeek ? video.value.position : Duration.zero; + _seekPreviewPosition = canSeek ? _seekStartPosition : null; + if (canSeek) { + _seekEpoch++; + _pendingSeekPosition = null; + _seekBusy = false; + _finishSeekWhenIdle = false; + setState(() => _seeking = true); + } + _setPaused(true); + } + + void _onStoryHoldMove(LongPressMoveUpdateDetails details, double width) { + final video = _video; + final startX = _seekStartX; + if (!_seeking || + video == null || + !video.value.isInitialized || + startX == null) { + return; + } + final duration = video.value.duration; + final target = storySeekPosition( + start: _seekStartPosition, + deltaX: details.globalPosition.dx - startX, + viewportWidth: width, + duration: duration, + ); + if (target == _seekPreviewPosition) return; + setState(() => _seekPreviewPosition = target); + final total = duration.inMicroseconds; + if (total > 0) { + _segment.value = (target.inMicroseconds / total).clamp(0.0, 1.0); + } + _queueStorySeek(video, target); + } + + void _queueStorySeek(VideoPlayerController video, Duration target) { + _pendingSeekPosition = target; + if (_seekBusy) return; + _seekBusy = true; + unawaited(_drainStorySeek(video, _seekEpoch)); + } + + Future _drainStorySeek(VideoPlayerController video, int epoch) async { + while (mounted && _video == video && epoch == _seekEpoch && _seeking) { + final target = _pendingSeekPosition; + if (target == null) break; + _pendingSeekPosition = null; + try { + await video.seekTo(target); + } catch (_) {} + } + if (!mounted || _video != video || epoch != _seekEpoch) return; + _seekBusy = false; + if (_pendingSeekPosition != null) { + _queueStorySeek(video, _pendingSeekPosition!); + return; + } + if (!_finishSeekWhenIdle) return; + setState(() { + _seeking = false; + _seekPreviewPosition = null; + _finishSeekWhenIdle = false; + }); + _setPaused(false); + } + + void _onStoryHoldEnd() { + final video = _video; + final target = _seekPreviewPosition; + _seekStartX = null; + if (!_seeking || video == null || target == null) { + _seeking = false; + _seekPreviewPosition = null; + _setPaused(false); + return; + } + _finishSeekWhenIdle = true; + _queueStorySeek(video, target); + } + void _onDragStart(DragStartDetails _) { _dragging = true; _setPaused(true); @@ -363,7 +562,7 @@ class _StoryViewerScreenState extends State void _onDragEnd(DragEndDetails d) { final v = d.primaryVelocity ?? 0; if (_dragDy > _dismissThreshold || v > 700) { - Navigator.of(context).maybePop(); + _close(); return; } setState(() { @@ -373,43 +572,105 @@ class _StoryViewerScreenState extends State _setPaused(false); } + void _onRoute(ModalRoute route) { + _route = route; + if (route is PageRoute) appRouteObserver.subscribe(this, route); + } + + @override + void didPushNext() => _pauseUntilUncovered(); + + @override + void didPopNext() { + if (!_resumeWhenUncovered) return; + _resumeWhenUncovered = false; + _setPaused(false); + } + + void _pauseUntilUncovered() { + if (_paused) return; + _resumeWhenUncovered = true; + _setPaused(true); + } + + void _close() { + final route = _route; + if (route == null || route.isCurrent) { + Navigator.of(context).maybePop(); + } else if (route.isActive) { + Navigator.of(context).removeRoute(route); + } + } + + Future _openOwnerProfile() async { + final owner = _owner.owner; + _pauseUntilUncovered(); + final opened = owner.isUser + ? await openContactById(context, owner.ownerId) + : await openChatById(context, owner.ownerId); + if (!mounted || (opened && _route?.isCurrent == false)) return; + didPopNext(); + } + // #***! меню своей истории, пока открыто — история на паузе Future _openStoryMenu() async { final story = _currentStory; if (story == null || _deleting) return; final wasPaused = _paused; _setPaused(true); - final delete = await _pickDelete(); + final action = await _pickOwnStoryAction(); if (!mounted) return; - final confirmed = delete && await _confirmDelete(); - if (!mounted) return; - if (confirmed) { - await _deleteStory(story); - if (!mounted) return; + switch (action) { + case StoryViewerMenuAction.save: + await _saveStory(story); + case StoryViewerMenuAction.delete: + if (await _confirmDelete()) { + if (!mounted) return; + await _deleteStory(story); + } + case null: + case StoryViewerMenuAction.profile: + case StoryViewerMenuAction.hide: + case StoryViewerMenuAction.report: + break; } + if (!mounted) return; if (!wasPaused && _currentStory != null) _setPaused(false); } - Future _pickDelete() async { - final picked = await showModalBottomSheet( - context: context, - showDragHandle: true, - builder: (sheetContext) { - final cs = Theme.of(sheetContext).colorScheme; - return SafeArea( - child: ListTile( - leading: Icon(Symbols.delete, color: cs.error), - title: Text( - AppLocalizations.of(sheetContext)!.msgActionsDelete, - style: TextStyle(color: cs.error), + Future _pickOwnStoryAction() => + showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) { + final cs = Theme.of(sheetContext).colorScheme; + final l10n = AppLocalizations.of(sheetContext)!; + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Symbols.download), + title: Text(l10n.storyMenuSave), + onTap: () => Navigator.of( + sheetContext, + ).pop(StoryViewerMenuAction.save), + ), + ListTile( + leading: Icon(Symbols.delete, color: cs.error), + title: Text( + l10n.msgActionsDelete, + style: TextStyle(color: cs.error), + ), + onTap: () => Navigator.of( + sheetContext, + ).pop(StoryViewerMenuAction.delete), + ), + ], ), - onTap: () => Navigator.of(sheetContext).pop(true), - ), - ); - }, - ); - return picked ?? false; - } + ); + }, + ); Future _confirmDelete() async { final l10n = AppLocalizations.of(context)!; @@ -460,67 +721,71 @@ class _StoryViewerScreenState extends State @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.transparent, - body: Stack( - children: [ - TweenAnimationBuilder( - tween: Tween(end: _dragDy), - duration: _dragging - ? Duration.zero - : const Duration(milliseconds: 320), - curve: Curves.easeOutCubic, - child: PageView.builder( - controller: _ownerController, - onPageChanged: _onOwnerPageChanged, - itemCount: widget.previews.length, - physics: const BouncingScrollPhysics(), - itemBuilder: (context, index) { - final content = index == _ownerIndex - ? _buildActiveOwner() - : _OwnerCover( - preview: widget.previews[index], - overrideInfo: - widget.ownerOverrides[widget - .previews[index] - .owner - .ownerId], - ); - return _CubePage( - controller: _ownerController, - index: index, - fallbackPage: _ownerIndex.toDouble(), - child: content, - ); - }, - ), - builder: (context, dy, child) { - final p = (dy.abs() / 320).clamp(0.0, 1.0); - return Stack( - fit: StackFit.expand, - children: [ - Positioned.fill( - child: IgnorePointer( - child: ColoredBox( - color: Colors.black.withValues(alpha: 1.0 - p * 0.7), + return RouteProbe( + onRoute: _onRoute, + child: Scaffold( + backgroundColor: Colors.transparent, + resizeToAvoidBottomInset: false, + body: Stack( + children: [ + TweenAnimationBuilder( + tween: Tween(end: _dragDy), + duration: _dragging + ? Duration.zero + : const Duration(milliseconds: 320), + curve: Curves.easeOutCubic, + child: PageView.builder( + controller: _ownerController, + onPageChanged: _onOwnerPageChanged, + itemCount: widget.previews.length, + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) { + final content = index == _ownerIndex + ? _buildActiveOwner() + : _OwnerCover( + preview: widget.previews[index], + overrideInfo: + widget.ownerOverrides[widget + .previews[index] + .owner + .ownerId], + ); + return _CubePage( + controller: _ownerController, + index: index, + fallbackPage: _ownerIndex.toDouble(), + child: content, + ); + }, + ), + builder: (context, dy, child) { + final p = (dy.abs() / 320).clamp(0.0, 1.0); + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: IgnorePointer( + child: ColoredBox( + color: Colors.black.withValues(alpha: 1.0 - p * 0.7), + ), ), ), - ), - Transform.translate( - offset: Offset(0, dy), - child: Transform.scale( - scale: 1.0 - p * 0.12, - child: ClipRRect( - borderRadius: BorderRadius.circular(p * 26), - child: child, + Transform.translate( + offset: Offset(0, dy), + child: Transform.scale( + scale: 1.0 - p * 0.12, + child: ClipRRect( + borderRadius: BorderRadius.circular(p * 26), + child: child, + ), ), ), - ), - ], - ); - }, - ), - ], + ], + ); + }, + ), + ], + ), ), ); } @@ -531,20 +796,39 @@ class _StoryViewerScreenState extends State final stories = _ownerStories; final story = _currentStory; + final card = LayoutBuilder( + builder: (context, constraints) => GestureDetector( + onTapUp: (details) { + if (details.localPosition.dx < constraints.maxWidth * 0.32) { + _rewind(); + } else { + _advance(); + } + }, + onLongPressStart: _onStoryHoldStart, + onLongPressMoveUpdate: (details) => + _onStoryHoldMove(details, constraints.maxWidth), + onLongPressEnd: (_) => _onStoryHoldEnd(), + onLongPressCancel: _onStoryHoldEnd, + child: _buildCardContent(ownerId, loading, stories, story), + ), + ); return GestureDetector( - onTapUp: (details) { - final width = MediaQuery.of(context).size.width; - if (details.localPosition.dx < width * 0.32) { - _rewind(); - } else { - _advance(); - } - }, - onLongPressStart: (_) => _setPaused(true), - onLongPressEnd: (_) => _setPaused(false), onVerticalDragStart: _onDragStart, onVerticalDragUpdate: _onDragUpdate, onVerticalDragEnd: _onDragEnd, + child: _StoryFrame(card: card, bottom: _buildBottomBar(story)), + ); + } + + Widget _buildCardContent( + int ownerId, + bool loading, + List stories, + Story? story, + ) { + return ColoredBox( + color: Colors.black, child: Stack( fit: StackFit.expand, children: [ @@ -555,7 +839,11 @@ class _StoryViewerScreenState extends State child: story?.media != null ? KeyedSubtree( key: ValueKey('$ownerId:${story!.id}'), - child: _StoryMediaView(media: story.media!, video: _video), + child: _StoryMediaView( + media: story.media!, + video: _video, + loading: _videoLoading, + ), ) : (loading ? const SizedBox.expand(key: ValueKey('loading')) @@ -571,27 +859,302 @@ class _StoryViewerScreenState extends State )), ), const _TopScrim(), + if (_seeking && _seekPreviewPosition != null && _video != null) + _StorySeekOverlay( + position: _seekPreviewPosition!, + duration: _video!.value.duration, + ), if (loading) const Center(child: SmallSpinner(size: 28, color: Colors.white)), - SafeArea( - child: Column( - children: [ - _buildProgressBars(stories.length), - _buildHeader(), - const Spacer(), - ], - ), + Column( + children: [ + _buildProgressBars(stories.length), + _buildHeader(), + const Spacer(), + ], + ), + ], + ), + ); + } + + Widget _buildBottomBar(Story? story) { + if (story == null) return const SizedBox.shrink(); + if (_isOwnStory(story)) { + final views = story.viewsCount; + if (views == null) return const SizedBox.shrink(); + return Row( + children: [ + const SizedBox(width: 16), + const Icon(Symbols.visibility, color: Colors.white70, size: 20), + const SizedBox(width: 6), + Text( + '$views', + style: const TextStyle(color: Colors.white70, fontSize: 14), ), ], + ); + } + if (!story.allowsReplies && !story.allowsReactions) { + return const SizedBox.shrink(); + } + return _StoryReplyBar( + key: ValueKey('reply-${story.owner.ownerId}'), + canReply: story.allowsReplies, + canLike: story.allowsReactions, + liked: story.liked, + onLike: () => _toggleLike(story), + onSend: (text) => _sendReply(story, text), + onTyping: _holdForInput, + ); + } + + bool _opensProfile(Story story) => !_isOwnStory(story) && story.allowsProfile; + + bool _hasMenu(Story story) => storyViewerMenuActions( + isOwn: _isOwnStory(story), + opensProfile: _opensProfile(story), + allowsHidingAuthor: story.allowsHidingAuthor, + allowsSaving: story.allowsSaving, + allowsComplaints: story.allowsComplaints, + ).isNotEmpty; + + void _holdForInput(bool typing) { + if (typing) { + _pauseUntilUncovered(); + } else { + didPopNext(); + } + } + + void _replaceLocal(Story updated) { + final ownerId = updated.owner.ownerId; + final list = _stories[ownerId]; + if (list == null) return; + final index = list.indexWhere((s) => s.id == updated.id); + if (index < 0) return; + setState(() => _stories[ownerId] = [...list]..[index] = updated); + } + + Future _toggleLike(Story story) async { + Haptics.selection(); + final next = story.liked ? null : StoriesModule.like; + _replaceLocal( + next == null + ? story.copyWith(clearReaction: true) + : story.copyWith(reaction: next), + ); + final ok = await storiesModule.react(story, next); + if (!mounted || ok) return; + _replaceLocal(story); + showCustomNotification( + context, + AppLocalizations.of(context)!.storyLikeFailed, + ); + } + + Future _sendReply(Story story, String text) async { + final trimmed = text.trim(); + if (trimmed.isEmpty) return false; + final result = await StoryReplySender.send(story, trimmed); + if (!mounted) return false; + final l10n = AppLocalizations.of(context)!; + switch (result.outcome) { + case StoryReplyOutcome.sent: + final navigatorContext = Navigator.of(context).context; + showCustomNotification( + context, + l10n.storyReplySent, + action: ( + label: l10n.storyReplyOpenChat, + onTap: () { + if (mounted) _close(); + unawaited(openChatById(navigatorContext, result.chatId)); + }, + ), + ); + return true; + case StoryReplyOutcome.encryptedChat: + showCustomNotification(context, l10n.storyReplyEncrypted); + return false; + case StoryReplyOutcome.failed: + showCustomNotification(context, l10n.storyReplyFailed); + return false; + } + } + + Future _openForeignMenu() async { + final story = _currentStory; + if (story == null) return; + _pauseUntilUncovered(); + final l10n = AppLocalizations.of(context)!; + final action = await showModalBottomSheet( + context: context, + showDragHandle: true, + builder: (sheetContext) { + final cs = Theme.of(sheetContext).colorScheme; + Widget item( + StoryViewerMenuAction action, + IconData icon, + String label, + ) => ListTile( + leading: Icon( + icon, + color: action == StoryViewerMenuAction.report ? cs.error : null, + ), + title: Text( + label, + style: action == StoryViewerMenuAction.report + ? TextStyle(color: cs.error) + : null, + ), + onTap: () => Navigator.of(sheetContext).pop(action), + ); + return SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_opensProfile(story)) + item( + StoryViewerMenuAction.profile, + Symbols.account_circle, + l10n.storyMenuProfile, + ), + if (story.allowsHidingAuthor) + item( + StoryViewerMenuAction.hide, + Symbols.visibility_off, + l10n.storyMenuHide, + ), + if (story.allowsSaving) + item( + StoryViewerMenuAction.save, + Symbols.download, + l10n.storyMenuSave, + ), + if (story.allowsComplaints) + item( + StoryViewerMenuAction.report, + Symbols.report, + l10n.storyMenuReport, + ), + ], + ), + ); + }, + ); + if (!mounted) return; + switch (action) { + case StoryViewerMenuAction.profile: + await _openOwnerProfile(); + return; + case StoryViewerMenuAction.hide: + await _hideAuthor(story); + case StoryViewerMenuAction.save: + await _saveStory(story); + case StoryViewerMenuAction.report: + await _reportStory(story); + case StoryViewerMenuAction.delete: + case null: + break; + } + if (mounted && _route?.isCurrent != false) didPopNext(); + } + + Future _hideAuthor(Story story) async { + final ownerId = story.owner.ownerId; + final ok = await storiesModule.setAuthorHidden(ownerId, true); + if (!mounted) return; + final l10n = AppLocalizations.of(context)!; + if (!ok) { + showCustomNotification(context, l10n.storyHideFailed); + return; + } + showCustomNotification( + context, + l10n.storyHiddenNotice, + action: ( + label: l10n.storyHiddenUndo, + onTap: () => unawaited(storiesModule.setAuthorHidden(ownerId, false)), ), ); + _nextOwner(); + } + + Future _saveStory(Story story) async { + final media = story.media; + final url = media?.url; + if (media == null || url == null || url.isEmpty) return; + final MediaSaveResult result; + if (media.isVideo) { + final file = await VideoPreloader.load( + _videoCacheName(story), + () async => url, + priority: true, + headers: _cdnHeaders, + ); + result = file == null + ? const MediaSaveResult(ok: false, failure: MediaSaveFailure.noLink) + : await saveLocalMedia( + file, + saveName: 'story_${story.id}.mp4', + kind: SaveMediaKind.video, + ); + } else { + result = await saveImageFromUrl(url); + } + if (!mounted) return; + final l10n = AppLocalizations.of(context)!; + showCustomNotification( + context, + result.ok + ? l10n.photoViewerSavedToGallery + : l10n.notificationsSaveFailed(result.errorText(l10n)), + ); + } + + Future _reportStory(Story story) async { + final l10n = AppLocalizations.of(context)!; + await showComplaintCard( + context, + title: l10n.chatInfoComplaintTitle, + subtitle: l10n.chatInfoComplaintSubtitle, + sendLabel: l10n.chatInfoComplaintSend, + closeLabel: l10n.chatInfoComplaintClose, + emptyLabel: l10n.chatInfoComplaintEmpty, + loadReasons: () async { + final reasons = await ComplaintsModule.reasonsFor( + api, + ComplaintsModule.storyTypeId, + ); + return reasons + .map((r) => (id: r.reasonId, title: r.reasonTitle)) + .toList(); + }, + onSend: (reasonId) async { + final ok = await ComplaintsModule.sendComplaint( + api, + reasonId: reasonId, + typeId: ComplaintsModule.storyTypeId, + ids: [story.id], + parentId: story.owner.ownerId, + ); + if (mounted) { + showCustomNotification( + context, + ok ? l10n.chatInfoComplaintSent : l10n.chatInfoComplaintFailed, + ); + } + return ok; + }, + ); } Widget _buildProgressBars(int count) { if (count <= 0) count = 1; return AnimatedOpacity( duration: const Duration(milliseconds: 200), - opacity: _paused ? 0.35 : 1.0, + opacity: _seeking ? 1.0 : (_paused ? 0.35 : 1.0), child: Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 4), child: Row( @@ -626,63 +1189,79 @@ class _StoryViewerScreenState extends State overrideInfo: widget.ownerOverrides[preview.owner.ownerId], builder: (context, info) => Row( children: [ - Container( - padding: const EdgeInsets.all(1.6), - decoration: BoxDecoration( - shape: BoxShape.circle, - border: Border.all( - color: Colors.white.withValues(alpha: 0.85), - width: 1.6, - ), - ), - child: KometAvatar( - name: info?.name.isNotEmpty == true ? info!.name : '?', - size: 34, - imageUrl: info?.avatarUrl, - ), - ), - const SizedBox(width: 10), Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - OfficialName( - contactId: preview.owner.ownerId, - text: info?.name.isNotEmpty == true ? info!.name : '…', - iconSize: 15, - style: TextStyle( - color: Colors.white, - fontSize: 15, - fontWeight: FontWeight.w600, - fontFamily: displayFontOf(context), - shadows: [Shadow(color: Colors.black54, blurRadius: 4)], + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: story != null && _opensProfile(story) + ? _openOwnerProfile + : null, + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(1.6), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all( + color: Colors.white.withValues(alpha: 0.85), + width: 1.6, + ), + ), + child: KometAvatar( + name: info?.name.isNotEmpty == true ? info!.name : '?', + size: 34, + imageUrl: info?.avatarUrl, + ), ), - ), - if (story != null && story.time > 0) - Text( - _timeAgo(AppLocalizations.of(context)!, story.time), - style: TextStyle( - color: Colors.white.withValues(alpha: 0.8), - fontSize: 12, - shadows: const [ - Shadow(color: Colors.black54, blurRadius: 4), + const SizedBox(width: 10), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + OfficialName( + contactId: preview.owner.ownerId, + text: info?.name.isNotEmpty == true + ? info!.name + : '…', + iconSize: 15, + style: TextStyle( + color: Colors.white, + fontSize: 15, + fontWeight: FontWeight.w600, + fontFamily: displayFontOf(context), + shadows: [ + Shadow(color: Colors.black54, blurRadius: 4), + ], + ), + ), + if (story != null && story.time > 0) + Text( + _timeAgo( + AppLocalizations.of(context)!, + story.time, + ), + style: TextStyle( + color: Colors.white.withValues(alpha: 0.8), + fontSize: 12, + shadows: const [ + Shadow(color: Colors.black54, blurRadius: 4), + ], + ), + ), ], ), ), - ], + ], + ), ), ), - if (_isOwnStory(story)) + if (story != null && _hasMenu(story)) _RoundIconButton( key: const ValueKey('story-more'), - icon: Symbols.more_horiz, - onTap: _openStoryMenu, + icon: Symbols.more_vert, + onTap: _isOwnStory(story) ? _openStoryMenu : _openForeignMenu, ), - _RoundIconButton( - icon: Symbols.close, - onTap: () => Navigator.of(context).maybePop(), - ), + _RoundIconButton(icon: Symbols.close, onTap: _close), ], ), ), @@ -690,6 +1269,51 @@ class _StoryViewerScreenState extends State } } +class _StorySeekOverlay extends StatelessWidget { + const _StorySeekOverlay({required this.position, required this.duration}); + + final Duration position; + final Duration duration; + + static String _time(Duration value) { + final seconds = value.inSeconds.clamp(0, 359999); + final minutes = seconds ~/ 60; + final rest = seconds % 60; + return '$minutes:${rest.toString().padLeft(2, '0')}'; + } + + @override + Widget build(BuildContext context) { + return IgnorePointer( + child: Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.56), + borderRadius: BorderRadius.circular(18), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Symbols.swap_horiz, color: Colors.white, size: 20), + const SizedBox(width: 7), + Text( + '${_time(position)} / ${_time(duration)}', + style: const TextStyle( + color: Colors.white, + fontSize: 14, + fontWeight: FontWeight.w600, + fontFeatures: [ui.FontFeature.tabularFigures()], + ), + ), + ], + ), + ), + ), + ); + } +} + // ─── Cube (3D fold) page transform ──────────────────────────────────────── class _CubePage extends StatelessWidget { final PageController controller; @@ -859,99 +1483,142 @@ final Expando _storyPreviews = Expando('storyPreview'); ImageProvider? _previewProvider(StoryMedia media) { final cached = _storyPreviews[media]; if (cached != null) return cached; + final bytes = _previewBytes(media); + if (bytes == null) return null; + final provider = MemoryImage(bytes); + _storyPreviews[media] = provider; + return provider; +} + +Uint8List? _previewBytes(StoryMedia media) { final previewData = media.previewData; - if (previewData == null) return null; - final comma = previewData.indexOf(','); - if (comma < 0) return null; - try { - final provider = MemoryImage( - base64Decode(previewData.substring(comma + 1)), - ); - _storyPreviews[media] = provider; - return provider; - } catch (_) { - return null; + final comma = previewData?.indexOf(',') ?? -1; + if (previewData != null && comma >= 0) { + try { + return base64Decode(previewData.substring(comma + 1)); + } catch (_) {} } + final thumbhash = media.thumbhash; + return thumbhash == null ? null : thumbHashToPng(thumbhash); } class _StoryMediaView extends StatelessWidget { final StoryMedia media; final VideoPlayerController? video; + final ValueListenable loading; - const _StoryMediaView({required this.media, this.video}); + const _StoryMediaView({ + required this.media, + required this.loading, + this.video, + }); + + static const double _portraitLimit = 0.8; + + double get _aspect { + if ((media.width ?? 0) > 0 && (media.height ?? 0) > 0) { + return media.aspectRatio; + } + final value = video?.value; + if (value == null || !value.isInitialized) return media.aspectRatio; + final raw = value.aspectRatio; + return value.rotationCorrection % 180 == 0 ? raw : 1 / raw; + } @override Widget build(BuildContext context) { final preview = _previewProvider(media); - final Widget blurBg = preview != null - ? Positioned.fill( - child: ImageFiltered( - imageFilter: ui.ImageFilter.blur( - sigmaX: AppFrost.mediaBackdropSigma, - sigmaY: AppFrost.mediaBackdropSigma, - ), - child: Image(image: preview, fit: BoxFit.cover), + final aspect = _aspect; + final fit = aspect < _portraitLimit ? BoxFit.cover : BoxFit.contain; + Widget framed(Widget child) => SizedBox.expand( + child: FittedBox( + fit: fit, + clipBehavior: Clip.hardEdge, + child: SizedBox(width: aspect * 1000, height: 1000, child: child), + ), + ); + final poster = media.thumbnailUrl?.isNotEmpty ?? false + ? framed( + CachedNetworkImage( + imageUrl: media.thumbnailUrl!, + fit: BoxFit.fill, + placeholder: preview == null + ? null + : (_, _) => Image(image: preview, fit: BoxFit.fill), + errorWidget: (_, _, _) => preview == null + ? const SizedBox.shrink() + : Image(image: preview, fit: BoxFit.fill), ), ) - : const SizedBox.shrink(); + : preview == null + ? const SizedBox.shrink() + : framed(Image(image: preview, fit: BoxFit.fill)); + + final children = [ + if (preview != null) + Positioned.fill( + child: ImageFiltered( + imageFilter: ui.ImageFilter.blur( + sigmaX: AppFrost.mediaBackdropSigma, + sigmaY: AppFrost.mediaBackdropSigma, + ), + child: Image(image: preview, fit: BoxFit.cover), + ), + ), + ]; if (media.isVideo) { final c = video; - Widget fg; - if (c != null && c.value.isInitialized) { - fg = Center( - child: AspectRatio( - aspectRatio: c.value.aspectRatio, - child: VideoPlayer(c), - ), - ); - } else if (media.thumbnailUrl?.isNotEmpty ?? false) { - fg = CachedNetworkImage( - imageUrl: media.thumbnailUrl!, - fit: BoxFit.contain, - ); - } else if (preview != null) { - fg = Center( - child: Image(image: preview, fit: BoxFit.contain), - ); - } else { - fg = const SizedBox.shrink(); - } - return Stack(fit: StackFit.expand, children: [blurBg, fg]); + children.add( + c != null && c.value.isInitialized ? framed(VideoPlayer(c)) : poster, + ); + children.add( + ValueListenableBuilder( + valueListenable: loading, + builder: (context, progress, _) => progress == null + ? const SizedBox.shrink() + : Center( + child: SizedBox( + width: 44, + height: 44, + child: CircularProgressIndicator( + value: progress > 0 ? progress : null, + strokeWidth: 3, + color: Colors.white, + backgroundColor: Colors.white24, + ), + ), + ), + ), + ); + return Stack(fit: StackFit.expand, children: children); } final url = media.url; - Widget fg; - if (url == null || url.isEmpty) { - fg = preview != null - ? Center( - child: Image(image: preview, fit: BoxFit.contain), - ) - : const SizedBox.shrink(); - } else { - fg = CachedNetworkImage( - imageUrl: url, - fit: BoxFit.contain, - fadeInDuration: const Duration(milliseconds: 200), - placeholder: preview != null - ? (context, _) => Center( - child: Image(image: preview, fit: BoxFit.contain), - ) - : null, - errorWidget: (context, _, _) => preview != null - ? Center( - child: Image(image: preview, fit: BoxFit.contain), - ) - : const Center( - child: Icon( - Symbols.broken_image, - color: Colors.white54, - size: 48, - ), + children.add( + url == null || url.isEmpty + ? poster + : framed( + CachedNetworkImage( + imageUrl: url, + fit: BoxFit.fill, + fadeInDuration: const Duration(milliseconds: 200), + placeholder: preview != null + ? (_, _) => Image(image: preview, fit: BoxFit.fill) + : null, + errorWidget: (_, _, _) => preview != null + ? Image(image: preview, fit: BoxFit.fill) + : const Center( + child: Icon( + Symbols.broken_image, + color: Colors.white54, + size: 48, + ), + ), ), - ); - } - return Stack(fit: StackFit.expand, children: [blurBg, fg]); + ), + ); + return Stack(fit: StackFit.expand, children: children); } } @@ -963,25 +1630,198 @@ class _OwnerCover extends StatelessWidget { @override Widget build(BuildContext context) { - return ColoredBox( - color: Colors.black, - child: Center( - child: StoryOwnerBuilder( - owner: preview.owner, - overrideInfo: overrideInfo, - builder: (context, info) => Column( - mainAxisSize: MainAxisSize.min, + return _StoryFrame( + card: ColoredBox( + color: Colors.black, + child: Center( + child: StoryOwnerBuilder( + owner: preview.owner, + overrideInfo: overrideInfo, + builder: (context, info) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + KometAvatar( + name: info?.name.isNotEmpty == true ? info!.name : '?', + size: 92, + imageUrl: info?.avatarUrl, + ), + const SizedBox(height: 14), + const SmallSpinner(size: 22, color: Colors.white30), + ], + ), + ), + ), + ), + ); + } +} + +class _StoryFrame extends StatelessWidget { + final Widget card; + final Widget? bottom; + + const _StoryFrame({required this.card, this.bottom}); + + static const double bottomBarHeight = 64; + static const double _aspect = 9 / 16; + + @override + Widget build(BuildContext context) { + final padding = MediaQuery.paddingOf(context); + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + final lift = math.max(0.0, keyboard - padding.bottom); + return Padding( + padding: EdgeInsets.only(top: padding.top, bottom: padding.bottom), + child: LayoutBuilder( + builder: (context, constraints) { + final cardMaxHeight = constraints.maxHeight - bottomBarHeight; + final width = math.min(constraints.maxWidth, cardMaxHeight * _aspect); + final height = math.min(cardMaxHeight, width / _aspect); + return Column( children: [ - KometAvatar( - name: info?.name.isNotEmpty == true ? info!.name : '?', - size: 92, - imageUrl: info?.avatarUrl, + SizedBox( + width: width, + height: height, + child: ClipRRect( + borderRadius: BorderRadius.circular(14), + child: card, + ), + ), + const Spacer(), + Transform.translate( + offset: Offset(0, -lift), + child: SizedBox( + width: width, + height: bottomBarHeight, + child: bottom, + ), ), - const SizedBox(height: 14), - const SmallSpinner(size: 22, color: Colors.white30), ], - ), - ), + ); + }, + ), + ); + } +} + +class _StoryReplyBar extends StatefulWidget { + final bool canReply; + final bool canLike; + final bool liked; + final VoidCallback onLike; + final Future Function(String text) onSend; + final ValueChanged onTyping; + + const _StoryReplyBar({ + super.key, + required this.canReply, + required this.canLike, + required this.liked, + required this.onLike, + required this.onSend, + required this.onTyping, + }); + + @override + State<_StoryReplyBar> createState() => _StoryReplyBarState(); +} + +class _StoryReplyBarState extends State<_StoryReplyBar> { + final TextEditingController _text = TextEditingController(); + final FocusNode _focus = FocusNode(); + bool _sending = false; + + @override + void initState() { + super.initState(); + _focus.addListener(_onFocus); + _text.addListener(_onText); + } + + @override + void dispose() { + _focus.removeListener(_onFocus); + _text.removeListener(_onText); + _focus.dispose(); + _text.dispose(); + super.dispose(); + } + + void _onFocus() => widget.onTyping(_focus.hasFocus); + + void _onText() => setState(() {}); + + Future _send() async { + if (_sending) return; + setState(() => _sending = true); + final ok = await widget.onSend(_text.text); + if (!mounted) return; + setState(() => _sending = false); + if (!ok) return; + _text.clear(); + _focus.unfocus(); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final typed = _text.text.trim().isNotEmpty; + final Widget trailing = typed || _sending + ? IconButton( + key: const ValueKey('story-reply-send'), + onPressed: _sending ? null : _send, + icon: _sending + ? const SmallSpinner(size: 20, color: Colors.white) + : const Icon(Symbols.send, fill: 1, color: Colors.white), + ) + : widget.canLike + ? IconButton( + key: const ValueKey('story-like'), + onPressed: widget.onLike, + icon: Icon( + Symbols.favorite, + fill: widget.liked ? 1 : 0, + color: widget.liked ? const Color(0xFFFF3B5C) : Colors.white, + size: 28, + ), + ) + : const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.fromLTRB(8, 10, 4, 10), + child: Row( + children: [ + if (widget.canReply) + Expanded( + child: TextField( + controller: _text, + focusNode: _focus, + readOnly: _sending, + textInputAction: TextInputAction.send, + onSubmitted: (_) => _send(), + style: const TextStyle(color: Colors.white, fontSize: 15), + cursorColor: Colors.white, + decoration: InputDecoration( + hintText: l10n.storyReplyHint, + hintStyle: const TextStyle(color: Colors.white60), + isDense: true, + filled: true, + fillColor: Colors.white.withValues(alpha: 0.12), + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 10, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(22), + borderSide: BorderSide.none, + ), + ), + ), + ) + else + const Spacer(), + const SizedBox(width: 4), + trailing, + ], ), ); } diff --git a/lib/frontend/screens/webapp/web_app_bridge.dart b/lib/frontend/screens/webapp/web_app_bridge.dart index 1be623ca..b9af35cf 100644 --- a/lib/frontend/screens/webapp/web_app_bridge.dart +++ b/lib/frontend/screens/webapp/web_app_bridge.dart @@ -219,8 +219,11 @@ class WebAppBridge { : {originPolicy!.origin}, ); + static bool get isSupported => + !kIsWeb && defaultTargetPlatform != TargetPlatform.linux; + Future attach(InAppWebViewController controller) async { - if (defaultTargetPlatform == TargetPlatform.linux || kIsWeb) { + if (!isSupported) { throw UnsupportedError('Secure mini-app bridge is unavailable'); } _disposed = false; diff --git a/lib/frontend/screens/webapp/web_app_screen.dart b/lib/frontend/screens/webapp/web_app_screen.dart index eb4ae1f2..94234c4f 100644 --- a/lib/frontend/screens/webapp/web_app_screen.dart +++ b/lib/frontend/screens/webapp/web_app_screen.dart @@ -77,7 +77,7 @@ class _WebAppScreenState extends State { @override void initState() { super.initState(); - _load(); + if (WebAppBridge.isSupported) _load(); } @override @@ -195,16 +195,6 @@ class _WebAppScreenState extends State { NavigationAction action, ) async { final uri = action.request.url; - if (action.isForMainFrame == true && - (uri == null || - _bridge?.originPolicy?.accepts(Uri.parse(uri.toString())) != - true)) { - _bridge?.documentStarted(null); - if (uri != null && mounted) { - await openExternalUrl(context, uri.toString(), fromWebContent: true); - } - return NavigationActionPolicy.CANCEL; - } final callback = widget.onExternalCallback; if (callback != null && uri?.queryParameters['externalCallback'] == '1') { try { @@ -234,8 +224,24 @@ class _WebAppScreenState extends State { } return NavigationActionPolicy.CANCEL; } + final leavesOrigin = + action.isForMainFrame == true && + (uri == null || + _bridge?.originPolicy?.accepts(Uri.parse(uri.toString())) != true); final handler = widget.shouldOverrideUrlLoading; - if (handler != null) return handler(controller, action, _launch?.url); + if (handler != null) { + final policy = await handler(controller, action, _launch?.url); + if (leavesOrigin && policy != NavigationActionPolicy.CANCEL) { + _bridge?.documentStarted(null); + } + return policy; + } + if (leavesOrigin) { + if (uri != null && mounted) { + await openExternalUrl(context, uri.toString(), fromWebContent: true); + } + return NavigationActionPolicy.CANCEL; + } if (uri != null && leavesWebView(uri.scheme)) { if (mounted) { @@ -291,6 +297,7 @@ class _WebAppScreenState extends State { } Widget _buildBody(ColorScheme cs) { + if (!WebAppBridge.isSupported) return const _UnsupportedPlatformView(); if (_loadError != null) { return ErrorView(message: _loadError!, onRetry: _load); } @@ -383,3 +390,29 @@ class _WebAppScreenState extends State { ); } } + +class _UnsupportedPlatformView extends StatelessWidget { + const _UnsupportedPlatformView(); + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Symbols.web_asset_off, size: 48, color: cs.onSurfaceVariant), + const SizedBox(height: 16), + Text( + AppLocalizations.of(context)!.webAppUnsupportedPlatform, + textAlign: TextAlign.center, + style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14), + ), + ], + ), + ), + ); + } +} diff --git a/lib/frontend/widgets/alert_note.dart b/lib/frontend/widgets/alert_note.dart new file mode 100644 index 00000000..c59c3270 --- /dev/null +++ b/lib/frontend/widgets/alert_note.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/config/app_shape.dart'; + +class AlertNote extends StatelessWidget { + AlertNote(String message, {super.key, this.icon = Symbols.error, this.margin}) + : messages = [message]; + + const AlertNote.all( + this.messages, { + super.key, + this.icon = Symbols.error, + this.margin, + }); + + final List messages; + final IconData icon; + final EdgeInsetsGeometry? margin; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final style = TextStyle(color: cs.onSurface, fontSize: 13.5, height: 1.35); + return Container( + margin: margin, + padding: const EdgeInsets.fromLTRB(12, 10, 14, 10), + decoration: BoxDecoration( + color: cs.surfaceContainerHighest, + borderRadius: AppShape.buttonRadius, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var i = 0; i < messages.length; i++) ...[ + if (i > 0) const SizedBox(height: 8), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 1), + child: Icon(icon, size: 18, color: cs.error), + ), + const SizedBox(width: 10), + Expanded(child: Text(messages[i], style: style)), + ], + ), + ], + ], + ), + ); + } +} diff --git a/lib/frontend/widgets/app_motion_scope.dart b/lib/frontend/widgets/app_motion_scope.dart new file mode 100644 index 00000000..11fe30bc --- /dev/null +++ b/lib/frontend/widgets/app_motion_scope.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +import '../../core/config/app_motion.dart'; + +class AppMotionScope extends StatelessWidget { + const AppMotionScope({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return ValueListenableBuilder( + valueListenable: AppMotion.enabled, + child: child, + builder: (context, enabled, child) { + final media = MediaQuery.of(context); + return MediaQuery( + data: media.copyWith( + disableAnimations: media.disableAnimations || !enabled, + ), + child: child!, + ); + }, + ); + } +} + +class MotionAwarePageTransitions extends PageTransitionsBuilder { + const MotionAwarePageTransitions(this.animated); + + final PageTransitionsBuilder animated; + + @override + DelegatedTransitionBuilder? get delegatedTransition => + animated.delegatedTransition; + + @override + Duration get transitionDuration => AppMotion.of(animated.transitionDuration); + + @override + Duration get reverseTransitionDuration => + AppMotion.of(animated.reverseTransitionDuration); + + @override + Widget buildTransitions( + PageRoute route, + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) => animated.buildTransitions( + route, + context, + animation, + secondaryAnimation, + child, + ); +} diff --git a/lib/frontend/widgets/attachment/attachment_sheet.dart b/lib/frontend/widgets/attachment/attachment_sheet.dart index 6239470e..5ed42414 100644 --- a/lib/frontend/widgets/attachment/attachment_sheet.dart +++ b/lib/frontend/widgets/attachment/attachment_sheet.dart @@ -825,42 +825,7 @@ class _AttachmentSheetState extends State { left: 0, right: 0, bottom: 0, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - AnimatedBuilder( - animation: Listenable.merge([ - _selected, - _pageController, - ]), - builder: (context, _) { - final count = _selected.value.length; - final galleryT = (1 - _currentPageT()).clamp( - 0.0, - 1.0, - ); - if (count == 0 || galleryT == 0) { - return const SizedBox.shrink(); - } - return Padding( - padding: const EdgeInsets.only( - right: 16, - bottom: 8, - ), - child: Opacity( - opacity: galleryT, - child: IgnorePointer( - ignoring: galleryT < 0.5, - child: _buildSendButton(cs), - ), - ), - ); - }, - ), - _buildBottomBar(), - ], - ), + child: _buildBottomBar(), ), ], ), @@ -1348,16 +1313,23 @@ class _AttachmentSheetState extends State { } Widget _buildSendButton(ColorScheme cs) { - return Material( - color: cs.primary, - shape: const StadiumBorder(), - elevation: 3, - child: InkWell( - customBorder: const StadiumBorder(), - onTap: () => _sendSelection(), - child: Padding( - padding: const EdgeInsets.all(14), - child: Icon(Symbols.send, color: cs.onPrimary, size: 24, weight: 500), + return Tooltip( + message: AppLocalizations.of(context)!.pasteAttachSend, + child: Material( + color: cs.primary, + shape: const CircleBorder(), + child: InkWell( + customBorder: const CircleBorder(), + onTap: () => _sendSelection(), + child: SizedBox.square( + dimension: _captionMinHeight, + child: Icon( + Symbols.send, + color: cs.onPrimary, + size: 24, + weight: 500, + ), + ), ), ), ); @@ -1485,17 +1457,18 @@ class _AttachmentSheetState extends State { padding: const EdgeInsets.symmetric( vertical: (SlidingPillNav.height - _captionMinHeight) / 2, ), - child: Container( - constraints: const BoxConstraints(minHeight: _captionMinHeight), - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), - decoration: BoxDecoration( - color: _composerColor(cs), - borderRadius: BorderRadius.circular(26), - border: Border.all(color: _composerBorderColor(cs), width: 0.5), - ), - child: Row( - children: [ - Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: Container( + constraints: const BoxConstraints(minHeight: _captionMinHeight), + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), + decoration: BoxDecoration( + color: _composerColor(cs), + borderRadius: BorderRadius.circular(26), + border: Border.all(color: _composerBorderColor(cs), width: 0.5), + ), child: TextField( controller: _captionCtrl, minLines: 1, @@ -1514,8 +1487,10 @@ class _AttachmentSheetState extends State { ), ), ), - ], - ), + ), + const SizedBox(width: 8), + _buildSendButton(cs), + ], ), ); } diff --git a/lib/frontend/widgets/attachment/bubbles/bubble_context.dart b/lib/frontend/widgets/attachment/bubbles/bubble_context.dart index b7d77bc8..458716f8 100644 --- a/lib/frontend/widgets/attachment/bubbles/bubble_context.dart +++ b/lib/frontend/widgets/attachment/bubbles/bubble_context.dart @@ -82,9 +82,11 @@ class BubbleContext { final bool hasPhotoWithCaption; final bool hasMultiplePhotosNoCaption; final Map? reactionInfo; + final ValueListenable? views; final CachedMessage message; final bool isMe; + final bool showsStatus; final int myId; final String chatType; final int? chatId; @@ -112,6 +114,7 @@ class BubbleContext { required this.hasMultiplePhotosNoCaption, required this.message, required this.isMe, + bool? showsStatus, required this.myId, required this.chatType, this.chatId, @@ -125,11 +128,13 @@ class BubbleContext { this.onStickerTap, this.onForwardedSourceTap, this.reactionInfo, + this.views, this.presentation, this.metaInFooter = false, this.likelyForwarded = false, this.selectable, - }) : dim = text.withValues(alpha: 0.7); + }) : dim = text.withValues(alpha: 0.7), + showsStatus = showsStatus ?? isMe; String? get contentText => presentation == null ? message.text : presentation!.text; @@ -151,6 +156,7 @@ class BubbleContext { hasMultiplePhotosNoCaption: hasMultiplePhotosNoCaption, message: message, isMe: isMe, + showsStatus: showsStatus, myId: myId, chatType: chatType, chatId: chatId, @@ -164,6 +170,7 @@ class BubbleContext { onStickerTap: onStickerTap, onForwardedSourceTap: onForwardedSourceTap, reactionInfo: reactionInfo, + views: views, presentation: value, metaInFooter: metaInFooter, likelyForwarded: likelyForwarded, @@ -188,11 +195,14 @@ class BubbleContext { Color get systemTint => cs.onPrimaryContainer.withValues(alpha: 0.12); - List metaMarks(Color color) { + List metaMarks(Color color, {double fontSize = 11}) { final typingMs = message.typingMs; + final views = this.views; return [ if (likelyForwarded) LikelyForwardedMark(color: color), if (typingMs != null) TypingTimeMark(typingMs: typingMs, color: color), + if (views != null) + ViewsMark(views: views, color: color, fontSize: fontSize), ]; } @@ -227,7 +237,7 @@ class BubbleContext { children: [ ...metaMarks(dim), Text(timeLabel, style: TextStyle(color: dim, fontSize: 11)), - if (isMe) ...[const SizedBox(width: 4), statusIcon()], + if (showsStatus) ...[const SizedBox(width: 4), statusIcon()], if (message.deleted) ...[const SizedBox(width: 4), deletedIcon()], ], ), @@ -276,7 +286,7 @@ class BubbleContext { const SizedBox(width: 3), const Icon(Symbols.delete, size: 11, color: Colors.white), ], - if (isMe) ...[ + if (showsStatus) ...[ const SizedBox(width: 3), statusIcon(color: Colors.white, size: 12), ], diff --git a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart index 3bb0e010..f0f24fe4 100644 --- a/lib/frontend/widgets/attachment/bubbles/file_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/file_bubble.dart @@ -14,6 +14,7 @@ import '../../../../core/utils/media_cache.dart'; import '../../../../core/utils/format.dart'; import '../../../../core/utils/haptics.dart'; import '../../../../core/media/audio_file_track.dart'; +import '../../../../core/media/audio_file_metadata.dart'; import '../../../../core/media/audio_playback_controller.dart'; import '../../../../core/media/media_playback.dart'; import '../../../../core/crypto/chat_crypto_service.dart'; @@ -27,6 +28,9 @@ import '../../share_unopenable_file.dart'; import '../../upload_progress_ring.dart'; import 'bubble_context.dart'; +typedef FileBubbleAudioMetadataLoader = + Future Function(String cacheName); + typedef FileBubbleOpener = Future Function( String cacheName, @@ -41,6 +45,10 @@ class FileBubble extends StatefulWidget { final FileAttachment file; final bool fill; final FileBubbleOpener openFile; + final FileBubbleOpener? cacheAudioFile; + final FileBubbleAudioMetadataLoader? loadAudioMetadata; + final AudioFileEnricher? enrichAudioFile; + final AudioFileActivator? activateAudioFile; const FileBubble({ super.key, @@ -48,6 +56,10 @@ class FileBubble extends StatefulWidget { required this.file, this.fill = false, this.openFile = openCachedFile, + this.cacheAudioFile, + this.loadAudioMetadata, + this.enrichAudioFile, + this.activateAudioFile, }); static bool isViewableImage(String name) => @@ -107,11 +119,12 @@ class _FileBubbleState extends State { builder: (context, _) { final cached = MediaCache.presence(cacheName).value; final progress = MediaDownloadProgress.notifier(cacheName).value; - final busy = _opening || progress != null; + final openingFile = _opening && !audioFile; + final busy = openingFile || progress != null; final available = fileId != null && ctx.uploadProgress == null; final status = progress != null ? 'Загрузка ${(progress * 100).round()}%' - : _opening + : openingFile ? 'Открытие…' : cached ? 'Открыть' @@ -240,6 +253,15 @@ class _FileBubbleState extends State { ), ], ), + if (audioFile && cached) + _AudioFileMetadataPreview( + cacheName: cacheName, + fallbackTitle: name, + fallbackArtworkUrl: previewUrl, + textColor: ctx.text, + dimColor: ctx.dim, + loader: widget.loadAudioMetadata, + ), if (audioFile) _AudioFilePlaybackControl( cacheName: cacheName, @@ -311,7 +333,6 @@ class _FileBubbleState extends State { '.heif', }; - Uint8List? get _sealedTicket => ctx.message.e2ee == CachedMessage.e2eeFile ? ctx.message.sealedText : null; @@ -631,9 +652,9 @@ class _FileBubbleState extends State { await AudioPlaybackController.instance.toggle(); return; } - final cached = (await MediaCache.existing(cacheName)) != null; + final cached = MediaCache.presence(cacheName).value; if (!cached) MediaDownloadProgress.set(cacheName, 0); - final result = await ensureCachedFile( + final result = await (widget.cacheAudioFile ?? ensureCachedFile)( cacheName, _fileUrl, onProgress: (value) => MediaDownloadProgress.set(cacheName, value), @@ -662,7 +683,7 @@ class _FileBubbleState extends State { return; } try { - await playback.activateAudioFile( + final track = await (widget.enrichAudioFile ?? AudioFileMetadata.enrich)( AudioFileTrack( cacheName: cacheName, path: result.path!, @@ -673,6 +694,9 @@ class _FileBubbleState extends State { messageTime: ctx.message.time, thumbnailUrl: _thumbnailUrl, ), + ); + await (widget.activateAudioFile ?? playback.activateAudioFile)( + track, notificationChannelName: l10n.audioPlaybackChannel, ); } catch (_) { @@ -683,6 +707,147 @@ class _FileBubbleState extends State { } } +class _AudioFileMetadataPreview extends StatefulWidget { + const _AudioFileMetadataPreview({ + required this.cacheName, + required this.fallbackTitle, + required this.fallbackArtworkUrl, + required this.textColor, + required this.dimColor, + this.loader, + }); + + final String cacheName; + final String fallbackTitle; + final String fallbackArtworkUrl; + final Color textColor; + final Color dimColor; + final FileBubbleAudioMetadataLoader? loader; + + @override + State<_AudioFileMetadataPreview> createState() => + _AudioFileMetadataPreviewState(); +} + +class _AudioFileMetadataPreviewState extends State<_AudioFileMetadataPreview> { + late Future _metadata = _load(); + + @override + void didUpdateWidget(covariant _AudioFileMetadataPreview oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.cacheName != widget.cacheName || + oldWidget.loader != widget.loader) { + _metadata = _load(); + } + } + + Future _load() async { + final loader = widget.loader; + if (loader != null) return loader(widget.cacheName); + final file = await MediaCache.existing(widget.cacheName); + if (file == null) return null; + return AudioFileMetadata.read(file, cacheName: widget.cacheName); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _metadata, + builder: (context, snapshot) { + final metadata = snapshot.data; + final title = metadata?.title?.trim(); + final artist = metadata?.artist?.trim(); + final album = metadata?.album?.trim(); + final subtitle = [ + if (artist != null && artist.isNotEmpty) artist, + if (album != null && album.isNotEmpty && album != artist) album, + ].join(' · '); + final artwork = metadata?.artworkUri; + final fallbackArtwork = widget.fallbackArtworkUrl.trim(); + if ((title == null || title.isEmpty) && + subtitle.isEmpty && + artwork == null && + fallbackArtwork.isEmpty) { + return const SizedBox.shrink(); + } + + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Row( + children: [ + if (artwork != null || fallbackArtwork.isNotEmpty) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(7), + child: SizedBox( + key: ValueKey('audio-metadata-cover-${widget.cacheName}'), + width: 36, + height: 36, + child: _artwork(artwork, fallbackArtwork), + ), + ), + const SizedBox(width: 9), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title == null || title.isEmpty + ? widget.fallbackTitle + : title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: widget.textColor, + fontSize: 13, + fontWeight: FontWeight.w600, + height: 1.15, + ), + ), + if (subtitle.isNotEmpty) ...[ + const SizedBox(height: 2), + Text( + subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: widget.dimColor, + fontSize: 11, + height: 1.15, + ), + ), + ], + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _artwork(Uri? artwork, String fallbackArtwork) { + if (artwork != null && artwork.scheme == 'file') { + return Image.file( + File.fromUri(artwork), + fit: BoxFit.cover, + filterQuality: FilterQuality.low, + errorBuilder: (_, _, _) => const SizedBox.shrink(), + ); + } + final url = artwork?.toString() ?? fallbackArtwork; + return CachedNetworkImage( + imageUrl: url, + fit: BoxFit.cover, + memCacheWidth: 72, + memCacheHeight: 72, + errorWidget: (_, _, _) => const SizedBox.shrink(), + ); + } +} + class _AudioFilePlaybackControl extends StatelessWidget { const _AudioFilePlaybackControl({ required this.cacheName, diff --git a/lib/frontend/widgets/attachment/bubbles/media_autoplay.dart b/lib/frontend/widgets/attachment/bubbles/media_autoplay.dart index 948b0184..b6eb31b9 100644 --- a/lib/frontend/widgets/attachment/bubbles/media_autoplay.dart +++ b/lib/frontend/widgets/attachment/bubbles/media_autoplay.dart @@ -12,6 +12,7 @@ import '../../../../core/media/auto_download_gate.dart'; import '../../../../core/media/video_preloader.dart'; import '../../../../core/utils/logger.dart'; import '../../../../models/attachment.dart'; +import '../../../../core/utils/media_cache_names.dart'; typedef MediaAutoplayBuilder = Widget Function(BuildContext context, Widget surface, bool playing); @@ -50,7 +51,7 @@ class AutoplayClip { final localPath = video.localPath; if (localPath == null && (videoId == null || token == null)) return null; return AutoplayClip( - cacheName: 'videopreview_$videoId.mp4', + cacheName: videoPreviewCacheName(videoId), localPath: localPath, resolveUrl: videoId == null || token == null ? null @@ -73,7 +74,7 @@ class AutoplayClip { return null; } return AutoplayClip( - cacheName: 'gif_$photoId.mp4', + cacheName: gifCacheName(photoId), resolveUrl: () async => url, frameSize: _sizeOf(photo.width, photo.height), setting: KometSettings.autoplayGif, diff --git a/lib/frontend/widgets/attachment/bubbles/meta_marks.dart b/lib/frontend/widgets/attachment/bubbles/meta_marks.dart index c65d87d5..89defe43 100644 --- a/lib/frontend/widgets/attachment/bubbles/meta_marks.dart +++ b/lib/frontend/widgets/attachment/bubbles/meta_marks.dart @@ -72,3 +72,42 @@ class TypingTimeMark extends StatelessWidget { ); } } + +class ViewsMark extends StatelessWidget { + final ValueListenable views; + final Color color; + final double fontSize; + + const ViewsMark({ + super.key, + required this.views, + required this.color, + this.fontSize = 11, + }); + + @override + Widget build(BuildContext context) => ValueListenableBuilder( + valueListenable: views, + builder: (context, count, _) { + if (count == null) return const SizedBox.shrink(); + return Semantics( + label: '${AppLocalizations.of(context)!.channelPostViews}: $count', + excludeSemantics: true, + child: Padding( + padding: const EdgeInsets.only(right: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Symbols.visibility, size: fontSize + 2, color: color), + const SizedBox(width: 2), + Text( + formatCompactCount(count), + style: TextStyle(color: color, fontSize: fontSize), + ), + ], + ), + ), + ); + }, + ); +} diff --git a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart index 7363a49a..1ca81fc7 100644 --- a/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/photo_bubble.dart @@ -279,47 +279,49 @@ class PhotoBubble extends StatelessWidget { ctx, photo, builder: (context, surface, playing) => Stack( - children: [ - _buildLetterboxedImage( - ctx, - photo, - size, - shown, - memWidth: memWidth, - memHeight: memHeight, - ), - Positioned.fill( - child: shown == size - ? surface - : Center(child: SizedBox.fromSize(size: shown, child: surface)), - ), - ..._mediaBadges(ctx, photo, compact: false, playing: playing), - if (ctx.uploadProgress != null) - _buildUploadOverlay(ctx, ctx.uploadProgress!, 0), - if (ctx.uploadProgress == null) + children: [ + _buildLetterboxedImage( + ctx, + photo, + size, + shown, + memWidth: memWidth, + memHeight: memHeight, + ), Positioned.fill( - child: Builder( - builder: (tileContext) => GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - if (_awaitsManualLoad(photo)) { - AutoDownloadGate.loadManually(_previewUrlOf(photo)); - return; - } - _openMedia( - ctx.context, - 0, - tileContext: tileContext, - radius: radius, - memWidth: memWidth, - memHeight: memHeight, - letterboxed: shown != size, - ); - }, + child: shown == size + ? surface + : Center( + child: SizedBox.fromSize(size: shown, child: surface), + ), + ), + ..._mediaBadges(ctx, photo, compact: false, playing: playing), + if (ctx.uploadProgress != null) + _buildUploadOverlay(ctx, ctx.uploadProgress!, 0), + if (ctx.uploadProgress == null) + Positioned.fill( + child: Builder( + builder: (tileContext) => GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + if (_awaitsManualLoad(photo)) { + AutoDownloadGate.loadManually(_previewUrlOf(photo)); + return; + } + _openMedia( + ctx.context, + 0, + tileContext: tileContext, + radius: radius, + memWidth: memWidth, + memHeight: memHeight, + letterboxed: shown != size, + ); + }, + ), ), ), - ), - ], + ], ), ), ); @@ -471,11 +473,11 @@ class PhotoBubble extends StatelessWidget { KometSettings.autoDownloadPhoto, ]), builder: (context, _) { - if (!AutoDownloadGate.allows( - KometSettings.autoDownloadPhoto.value, - imageUrl, - )) { - return _manualLoadTile(ctx, photo, imageUrl, width, height); + final autoDownload = KometSettings.autoDownloadPhoto.value; + if (!AutoDownloadGate.allows(autoDownload, imageUrl)) { + return AutoDownloadGate.awaitsTap(autoDownload, imageUrl) + ? _manualLoadTile(ctx, photo, imageUrl, width, height) + : _buildPreviewImage(ctx, photo, width, height); } return NetworkPhoto( url: imageUrl, diff --git a/lib/frontend/widgets/attachment/bubbles/share_bubble.dart b/lib/frontend/widgets/attachment/bubbles/share_bubble.dart index a767f064..f768c827 100644 --- a/lib/frontend/widgets/attachment/bubbles/share_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/share_bubble.dart @@ -2,9 +2,9 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import '../../../../core/utils/haptics.dart'; -import '../../../../core/utils/link_opener.dart'; import '../../../../models/attachment.dart'; import '../../formatted_message_text.dart'; +import '../../link_confirm_sheet.dart'; import 'bubble_context.dart'; class ShareBubble extends StatelessWidget { @@ -33,7 +33,7 @@ class ShareBubble extends StatelessWidget { ? null : () { Haptics.tap(); - openExternalUrl(ctx.context, share.url!); + openMessageLink(ctx.context, share.url!); }, child: Container( decoration: BoxDecoration( diff --git a/lib/frontend/widgets/attachment/bubbles/sticker_bubble.dart b/lib/frontend/widgets/attachment/bubbles/sticker_bubble.dart index b83ec78b..950e9790 100644 --- a/lib/frontend/widgets/attachment/bubbles/sticker_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/sticker_bubble.dart @@ -3,7 +3,6 @@ import 'package:material_symbols_icons/symbols.dart'; import '../../../../models/attachment.dart'; import '../../lottie_image.dart'; -import '../../sending_clock_icon.dart'; import 'bubble_context.dart'; class StickerBubble extends StatelessWidget { @@ -73,9 +72,9 @@ class StickerBubble extends StatelessWidget { fontWeight: FontWeight.w500, ), ), - if (ctx.isMe) ...[ + if (ctx.showsStatus) ...[ const SizedBox(width: 3), - _buildStickerStatusIcon(), + ctx.statusIcon(color: Colors.white, size: 13), ], if (ctx.message.deleted) ...[ const SizedBox(width: 3), @@ -85,13 +84,4 @@ class StickerBubble extends StatelessWidget { ), ); } - - Widget _buildStickerStatusIcon() { - final status = ctx.overrideStatus ?? ctx.message.status; - final v = messageStatusVisual(status, dimColor: Colors.white); - if (isSendingStatus(status)) { - return SendingClockIcon(color: v.color, size: 13); - } - return Icon(v.icon, size: 13, color: v.color); - } } diff --git a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart index 098a2aaf..3bb9c4d5 100644 --- a/lib/frontend/widgets/attachment/bubbles/video_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/video_bubble.dart @@ -98,10 +98,11 @@ class VideoBubble extends StatelessWidget { KometSettings.autoDownloadVideo, ]), builder: (context, _) { - if (!AutoDownloadGate.allows( - KometSettings.autoDownloadVideo.value, - previewUrl, - )) { + final autoDownload = KometSettings.autoDownloadVideo.value; + if (!AutoDownloadGate.allows(autoDownload, previewUrl)) { + if (!AutoDownloadGate.awaitsTap(autoDownload, previewUrl)) { + return placeholder(); + } return SizedBox( width: width, height: height, diff --git a/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart b/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart index 817cc756..40d3bf7f 100644 --- a/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart +++ b/lib/frontend/widgets/attachment/bubbles/voice_bubble.dart @@ -24,6 +24,8 @@ class VoiceMessageBubble extends StatefulWidget { final String url; final Color textColor; final bool isMe; + final bool showsStatus; + final ValueListenable? views; final bool deleted; final String? status; final ValueListenable? otherReadTime; @@ -47,6 +49,8 @@ class VoiceMessageBubble extends StatefulWidget { required this.url, required this.textColor, required this.isMe, + required this.showsStatus, + this.views, this.deleted = false, this.status, this.otherReadTime, @@ -188,6 +192,8 @@ class _VoiceMessageBubbleState extends State { final dim = widget.textColor.withValues(alpha: 0.6); return [ if (widget.likelyForwarded) LikelyForwardedMark(color: dim), + if (widget.views case final views?) + ViewsMark(views: views, color: dim, fontSize: 10), Text( formatClock( DateTime.fromMillisecondsSinceEpoch(widget.time), @@ -195,7 +201,10 @@ class _VoiceMessageBubbleState extends State { ), style: TextStyle(color: dim, fontSize: 10), ), - if (widget.isMe) ...[const SizedBox(width: 2), _buildStatusIcon()], + if (widget.showsStatus) ...[ + const SizedBox(width: 2), + _buildStatusIcon(), + ], if (widget.deleted) ...[ const SizedBox(width: 2), Icon(Symbols.delete, size: 13, color: dim), diff --git a/lib/frontend/widgets/auth_limits_sheet.dart b/lib/frontend/widgets/auth_limits_sheet.dart index e9c3895d..c90bd19a 100644 --- a/lib/frontend/widgets/auth_limits_sheet.dart +++ b/lib/frontend/widgets/auth_limits_sheet.dart @@ -68,6 +68,7 @@ Future showAuthLimitsSheet( body: l10n.authLimitsLoginSessionsBody, ), ], + footnote: l10n.authLimitsServerNote, confirmLabel: l10n.authLimitsConfirm, ); case AuthEntry.registration: @@ -94,6 +95,7 @@ Future showAuthLimitsSheet( body: l10n.authLimitsSignupMoreBody, ), ], + footnote: l10n.authLimitsServerNote, confirmLabel: l10n.authLimitsConfirm, ); } diff --git a/lib/frontend/widgets/avatar_photo_actions.dart b/lib/frontend/widgets/avatar_photo_actions.dart index 113aeeef..871ab958 100644 --- a/lib/frontend/widgets/avatar_photo_actions.dart +++ b/lib/frontend/widgets/avatar_photo_actions.dart @@ -9,6 +9,7 @@ import '../../l10n/app_localizations.dart'; import 'chat_menu_overlay.dart'; import 'custom_notification.dart'; import 'sheet_helpers.dart'; +import '../../core/utils/media_cache_names.dart'; // #***! на телефоне аватарка едет в галерею, на десктопе в выбранную папку String avatarSaveLabel(BuildContext context) { @@ -36,7 +37,7 @@ Future saveAvatarPhoto(BuildContext context, String url) async { } final dialogTitle = avatarSaveLabel(context); - final cacheName = 'avatar_${url.hashCode & 0x7fffffff}.jpg'; + final cacheName = avatarCacheName(url); final file = await MediaCache.getOrDownload(cacheName, url); if (!context.mounted) return; if (file == null) { diff --git a/lib/frontend/widgets/call_link_handler.dart b/lib/frontend/widgets/call_link_handler.dart index a4f1fdc5..6c64972a 100644 --- a/lib/frontend/widgets/call_link_handler.dart +++ b/lib/frontend/widgets/call_link_handler.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '../../core/calls/call_controller.dart'; +import '../../core/calls/call_permissions.dart'; import '../../core/calls/call_link.dart'; import '../../l10n/app_localizations.dart'; import '../screens/calls/call_screen.dart'; @@ -78,6 +79,10 @@ Future joinGroupCall( builder: (_) => CallScreen(name: name, session: session, isGroup: true), ), ); + } on CallMicrophonePermissionException { + if (context.mounted) { + showCustomNotification(context, l10n.callMicrophonePermissionDenied); + } } catch (_) { if (context.mounted) { showCustomNotification(context, l10n.callLinkHandlerJoinFailed); diff --git a/lib/frontend/widgets/chat_info/shared_content_tabs.dart b/lib/frontend/widgets/chat_info/shared_content_tabs.dart index ca5104cc..10ea6875 100644 --- a/lib/frontend/widgets/chat_info/shared_content_tabs.dart +++ b/lib/frontend/widgets/chat_info/shared_content_tabs.dart @@ -15,7 +15,6 @@ import '../../../core/utils/download_history.dart'; import '../../../core/utils/download_progress.dart'; import '../../../core/utils/file_download.dart'; import '../../../core/utils/format.dart'; -import '../../../core/utils/link_opener.dart'; import '../../../core/utils/logger.dart'; import '../../../core/utils/media_saver.dart'; import '../../../core/utils/route_settle.dart'; @@ -24,6 +23,7 @@ import '../../../models/attachment.dart'; import '../../screens/chats/chat_screen.dart'; import '../custom_notification.dart'; import '../komet_avatar.dart'; +import '../link_confirm_sheet.dart'; import '../photo_viewer.dart'; import '../reload_on_reconnect.dart'; import '../route_probe.dart'; @@ -1103,7 +1103,7 @@ class _LinkRow extends StatelessWidget { : image?.previewData; return InkWell( - onTap: url.isEmpty ? null : () => openExternalUrl(context, url), + onTap: url.isEmpty ? null : () => openMessageLink(context, url), borderRadius: BorderRadius.circular(12), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), diff --git a/lib/frontend/widgets/chat_wallpaper_sheet.dart b/lib/frontend/widgets/chat_wallpaper_sheet.dart index 5a21664d..7344b514 100644 --- a/lib/frontend/widgets/chat_wallpaper_sheet.dart +++ b/lib/frontend/widgets/chat_wallpaper_sheet.dart @@ -5,19 +5,21 @@ import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; +import 'package:komet/core/config/app_motion.dart'; import 'package:komet/core/config/chat_wallpaper_themes.dart'; -import 'package:komet/core/config/app_colors.dart'; import 'package:komet/core/storage/chat_wallpaper_store.dart'; +import 'package:komet/core/utils/haptics.dart'; import 'package:komet/core/utils/image_utils.dart'; import 'package:komet/frontend/screens/profile/custom_gradient_editor_screen.dart'; import 'package:komet/l10n/app_localizations.dart'; import 'chat_wallpaper_view.dart'; import 'mesh_gradient_background.dart'; +import 'theme_wallpaper.dart'; import 'custom_notification.dart'; import '../../core/config/app_fonts.dart'; import '../../core/security/app_lock.dart'; -enum WallpaperPickType { none, theme, gallery, gradient } +enum WallpaperPickType { inherit, none, theme, gallery, gradient } class WallpaperPick { final WallpaperPickType type; @@ -26,22 +28,28 @@ class WallpaperPick { final bool gradientAnimated; final double gradientRotation; + const WallpaperPick.inherit() + : type = WallpaperPickType.inherit, + theme = null, + gradientColors = null, + gradientAnimated = false, + gradientRotation = 0; const WallpaperPick.none() : type = WallpaperPickType.none, theme = null, gradientColors = null, - gradientAnimated = true, + gradientAnimated = false, gradientRotation = 0; const WallpaperPick.gallery() : type = WallpaperPickType.gallery, theme = null, gradientColors = null, - gradientAnimated = true, + gradientAnimated = false, gradientRotation = 0; const WallpaperPick.theme(this.theme) : type = WallpaperPickType.theme, gradientColors = null, - gradientAnimated = true, + gradientAnimated = false, gradientRotation = 0; const WallpaperPick.gradient( this.gradientColors, { @@ -51,7 +59,6 @@ class WallpaperPick { theme = null; } -// #***! путь, а не байты: withData грузит файл в java-кучу и валит процесс на OOM Future pickWallpaperBytes(BuildContext context) async { final result = await AppLock.instance.external( () => FilePicker.platform.pickFiles(type: FileType.image), @@ -80,19 +87,61 @@ Future pickWallpaperBytes(BuildContext context) async { Future showChatWallpaperSheet( BuildContext context, { required ChatWallpaper? current, + ChatWallpaper? inherited, + bool perChat = false, }) { return Navigator.of(context).push( MaterialPageRoute( fullscreenDialog: true, - builder: (_) => ChatWallpaperGalleryScreen(current: current), + builder: (_) => ChatWallpaperGalleryScreen( + current: current, + inherited: inherited, + perChat: perChat, + ), ), ); } +sealed class _Choice { + const _Choice(); +} + +final class _InheritChoice extends _Choice { + const _InheritChoice(); +} + +final class _NoneChoice extends _Choice { + const _NoneChoice(); +} + +final class _CurrentChoice extends _Choice { + const _CurrentChoice(); +} + +final class _PresetChoice extends _Choice { + const _PresetChoice(this.theme); + + final ChatWallpaperTheme theme; + + @override + bool operator ==(Object other) => + other is _PresetChoice && other.theme.id == theme.id; + + @override + int get hashCode => theme.id.hashCode; +} + class ChatWallpaperGalleryScreen extends StatefulWidget { final ChatWallpaper? current; - - const ChatWallpaperGalleryScreen({super.key, required this.current}); + final ChatWallpaper? inherited; + final bool perChat; + + const ChatWallpaperGalleryScreen({ + super.key, + required this.current, + this.inherited, + this.perChat = false, + }); @override State createState() => @@ -101,47 +150,52 @@ class ChatWallpaperGalleryScreen extends StatefulWidget { class _ChatWallpaperGalleryScreenState extends State { - ChatWallpaperTheme? _selected; - bool _keepsImage = false; + late final _Choice _initial = _choiceFor(widget.current); + late _Choice _choice = _initial; - @override - void initState() { - super.initState(); + _Choice _choiceFor(ChatWallpaper? wallpaper) { + if (wallpaper == null) { + return widget.perChat ? const _InheritChoice() : const _NoneChoice(); + } + if (wallpaper.isNone) return const _NoneChoice(); + if (!wallpaper.isImage && !wallpaper.isGradient) { + final theme = chatWallpaperThemeById(wallpaper.themeId); + if (theme != null) return _PresetChoice(theme); + } + return const _CurrentChoice(); + } + + ChatWallpaper? get _ownCustom { final current = widget.current; - _keepsImage = current?.isImage ?? false; - _selected = current == null || current.isImage - ? null - : chatWallpaperThemeById(current.themeId); + if (current == null || current.isNone) return null; + return _choiceFor(current) is _CurrentChoice ? current : null; } - bool get _changed { - if (_keepsImage) return false; - if (widget.current?.isImage == true) return true; - return _selected?.id != chatWallpaperThemeById(widget.current?.themeId)?.id; + void _select(_Choice choice) { + if (choice == _choice) return; + Haptics.selection(); + setState(() => _choice = choice); } void _apply() { - if (_selected == null) { - Navigator.pop(context, const WallpaperPick.none()); - } else { - Navigator.pop(context, WallpaperPick.theme(_selected)); - } + final pick = switch (_choice) { + _InheritChoice() => const WallpaperPick.inherit(), + _NoneChoice() => const WallpaperPick.none(), + _PresetChoice(:final theme) => WallpaperPick.theme(theme), + _CurrentChoice() => null, + }; + Navigator.pop(context, pick); } Future _openGradientEditor() async { final current = widget.current; + final gradient = current != null && current.isGradient ? current : null; final result = await Navigator.of(context).push( MaterialPageRoute( builder: (_) => CustomGradientEditorScreen( - initialColors: current?.isGradient == true - ? current!.gradientColors - : null, - initialAnimated: current?.isGradient == true - ? current!.gradientAnimated - : false, - initialRotation: current?.isGradient == true - ? current!.gradientRotation - : 0, + initialColors: gradient?.gradientColors, + initialAnimated: gradient?.gradientAnimated ?? false, + initialRotation: gradient?.gradientRotation ?? 0, ), ), ); @@ -156,9 +210,21 @@ class _ChatWallpaperGalleryScreenState ); } + Widget _previewLayer() => switch (_choice) { + _InheritChoice() => _layerFor(widget.inherited), + _NoneChoice() => const SizedBox.shrink(), + _CurrentChoice() => _layerFor(widget.current), + _PresetChoice(:final theme) => ThemeWallpaper(theme: theme), + }; + + Widget _layerFor(ChatWallpaper? wallpaper) => wallpaper == null + ? const SizedBox.shrink() + : ChatWallpaperView(wallpaper: wallpaper); + @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; return Scaffold( backgroundColor: cs.surface, appBar: AppBar( @@ -169,7 +235,7 @@ class _ChatWallpaperGalleryScreenState onPressed: () => Navigator.pop(context), ), title: Text( - AppLocalizations.of(context)!.chatWallpaperSheetTitle, + l10n.chatWallpaperSheetTitle, style: TextStyle( fontSize: 22, fontWeight: FontWeight.w700, @@ -179,109 +245,113 @@ class _ChatWallpaperGalleryScreenState ), body: Column( children: [ - Expanded(child: _preview(cs)), - _panel(cs), + Expanded( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 16), + child: WallpaperPreview( + layer: AnimatedSwitcher( + duration: AppMotion.of(const Duration(milliseconds: 260)), + child: KeyedSubtree( + key: ValueKey(_choice), + child: _previewLayer(), + ), + ), + incoming: l10n.chatWallpaperSheetSampleIncoming, + outgoing: l10n.chatWallpaperSheetSampleOutgoing, + ), + ), + ), + _panel(context), ], ), ); } - Widget _preview(ColorScheme cs) { - final theme = _selected; - final image = _keepsImage ? widget.current : null; - return Padding( - padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), - child: ClipRRect( - borderRadius: BorderRadius.circular(28), - child: Stack( - fit: StackFit.expand, - children: [ - if (theme != null) - theme.buildBackground() - else if (image != null) - ChatWallpaperView(wallpaper: image) - else - ColoredBox(color: cs.surfaceContainerHighest), - const IgnorePointer(child: _PreviewScrim()), - _SampleBubbles(theme: theme), - ], - ), - ), - ); - } - - Widget? _currentImageTile() { - final current = widget.current; - if (current == null || !current.isImage) return null; - return _CurrentImageTile( - wallpaper: current, - selected: _keepsImage, - onTap: () => setState(() { - _keepsImage = true; - _selected = null; - }), - ); - } - - Widget _panel(ColorScheme cs) { - final currentImage = _currentImageTile(); - return Container( + Widget _panel(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final inherited = widget.inherited; + final custom = _ownCustom; + return DecoratedBox( decoration: BoxDecoration( - color: cs.surfaceContainerHigh, - borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), + color: cs.surfaceContainerLow, + borderRadius: const BorderRadius.vertical(top: Radius.circular(28)), ), child: SafeArea( top: false, child: Column( mainAxisSize: MainAxisSize.min, children: [ - const SizedBox(height: 14), + const SizedBox(height: 16), SizedBox( - height: 150, + height: _WallpaperTile.height, child: ListView( scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric(horizontal: 16), children: [ - ?currentImage, - _NoneTile( - selected: _selected == null && !_keepsImage, - onTap: () => setState(() { - _selected = null; - _keepsImage = false; - }), - ), - _CustomGradientTile( - current: widget.current?.isGradient == true - ? widget.current - : null, - onTap: _openGradientEditor, + if (widget.perChat) + _WallpaperTile( + label: l10n.chatWallpaperSheetInherit, + selected: _choice is _InheritChoice, + onTap: () => _select(const _InheritChoice()), + child: inherited == null + ? const _TileIcon(Symbols.forum) + : _TileWallpaper(wallpaper: inherited), + ), + _WallpaperTile( + label: l10n.chatWallpaperSheetNone, + selected: _choice is _NoneChoice, + onTap: () => _select(const _NoneChoice()), + child: const _TileIcon(Symbols.hide_image), ), + if (custom != null) + _WallpaperTile( + label: custom.isImage + ? l10n.chatWallpaperSheetYourPhoto + : l10n.chatWallpaperSheetCurrent, + selected: _choice is _CurrentChoice, + onTap: () => _select(const _CurrentChoice()), + child: _TileWallpaper(wallpaper: custom), + ), for (final theme in kChatWallpaperThemes) - _ThemeTile( - theme: theme, - selected: _selected?.id == theme.id, - onTap: () => setState(() { - _selected = theme; - _keepsImage = false; - }), + _WallpaperTile( + label: _presetName(l10n, theme), + selected: _choice == _PresetChoice(theme), + onTap: () => _select(_PresetChoice(theme)), + child: ThemeWallpaper( + theme: theme, + patternScale: _WallpaperTile.patternScale, + ), ), + _WallpaperTile( + label: l10n.chatWallpaperSheetCustomGradient, + selected: false, + onTap: _openGradientEditor, + child: const _TileIcon(Symbols.gradient), + ), ], ), ), - const SizedBox(height: 12), Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), child: Row( children: [ Expanded( - child: _GalleryButton( - onTap: () => + child: FilledButton.tonalIcon( + style: wallpaperButtonStyle(context), + onPressed: () => Navigator.pop(context, const WallpaperPick.gallery()), + icon: const Icon(Symbols.add_photo_alternate, size: 20), + label: Text(l10n.chatWallpaperSheetFromGallery), ), ), const SizedBox(width: 12), Expanded( - child: _ApplyButton(enabled: _changed, onTap: _apply), + child: FilledButton( + style: wallpaperButtonStyle(context), + onPressed: _choice == _initial ? null : _apply, + child: Text(l10n.chatWallpaperSheetApply), + ), ), ], ), @@ -293,86 +363,121 @@ class _ChatWallpaperGalleryScreenState } } -class _PreviewScrim extends StatelessWidget { - const _PreviewScrim(); - - @override - Widget build(BuildContext context) { - return const DecoratedBox( - decoration: BoxDecoration( - gradient: LinearGradient( - begin: Alignment.topCenter, - end: Alignment.bottomCenter, - colors: [Color(0x14000000), Color(0x00000000), Color(0x1F000000)], - stops: [0.0, 0.5, 1.0], - ), +ButtonStyle wallpaperButtonStyle(BuildContext context) => + FilledButton.styleFrom( + minimumSize: const Size.fromHeight(52), + shape: const StadiumBorder(), + textStyle: Theme.of(context).textTheme.labelLarge?.copyWith( + fontSize: 15, + fontWeight: FontWeight.w600, ), - child: SizedBox.expand(), ); - } -} -class _SampleBubbles extends StatelessWidget { - final ChatWallpaperTheme? theme; +String _presetName(AppLocalizations l10n, ChatWallpaperTheme theme) => + switch (theme.id) { + 'komet' => l10n.chatWallpaperPresetKomet, + 'graphite' => l10n.chatWallpaperPresetGraphite, + 'ink' => l10n.chatWallpaperPresetInk, + 'pine' => l10n.chatWallpaperPresetPine, + 'plum' => l10n.chatWallpaperPresetPlum, + 'umber' => l10n.chatWallpaperPresetUmber, + 'paper' => l10n.chatWallpaperPresetPaper, + 'fog' => l10n.chatWallpaperPresetFog, + 'sage' => l10n.chatWallpaperPresetSage, + 'sand' => l10n.chatWallpaperPresetSand, + 'powder' => l10n.chatWallpaperPresetPowder, + _ => theme.id, + }; + +class WallpaperPreview extends StatelessWidget { + const WallpaperPreview({ + super.key, + required this.layer, + required this.incoming, + required this.outgoing, + }); - const _SampleBubbles({required this.theme}); + final Widget layer; + final String incoming; + final String outgoing; @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; - final l10n = AppLocalizations.of(context)!; - return Align( - alignment: Alignment.bottomCenter, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 16), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _bubble( - context, - text: l10n.chatWallpaperSheetSampleIncoming, - color: cs.surfaceContainerHighest.withValues(alpha: 0.94), - textColor: cs.onSurface, - alignment: Alignment.centerLeft, + return ClipRRect( + borderRadius: BorderRadius.circular(32), + child: Stack( + fit: StackFit.expand, + children: [ + ColoredBox(color: cs.surface), + layer, + DecoratedBox( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(32), + border: Border.all( + color: cs.outlineVariant.withValues(alpha: 0.5), + ), ), - const SizedBox(height: 8), - _bubble( - context, - text: l10n.chatWallpaperSheetSampleOutgoing, - color: cs.primary, - textColor: cs.onPrimary, - alignment: Alignment.centerRight, + ), + Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 0, 14, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + _SampleBubble( + text: incoming, + color: cs.surfaceContainerHighest, + textColor: cs.onSurface, + alignment: Alignment.centerLeft, + ), + const SizedBox(height: 6), + _SampleBubble( + text: outgoing, + color: cs.primaryContainer, + textColor: cs.onPrimaryContainer, + alignment: Alignment.centerRight, + ), + ], + ), ), - ], - ), + ), + ], ), ); } +} + +class _SampleBubble extends StatelessWidget { + const _SampleBubble({ + required this.text, + required this.color, + required this.textColor, + required this.alignment, + }); + + final String text; + final Color color; + final Color textColor; + final Alignment alignment; - Widget _bubble( - BuildContext context, { - required String text, - required Color color, - required Color textColor, - required Alignment alignment, - }) { + @override + Widget build(BuildContext context) { return Align( alignment: alignment, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 260), - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + child: DecoratedBox( decoration: BoxDecoration( color: color, - borderRadius: BorderRadius.circular(18), + borderRadius: BorderRadius.circular(20), ), - child: Text( - text, - style: TextStyle( - color: textColor, - fontSize: 15, - fontFamily: displayFontOf(context), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9), + child: Text( + text, + style: TextStyle(color: textColor, fontSize: 15, height: 1.3), ), ), ), @@ -381,82 +486,121 @@ class _SampleBubbles extends StatelessWidget { } } -class _TileFrame extends StatelessWidget { - final bool selected; - final VoidCallback onTap; - final Widget child; - final String label; - - const _TileFrame({ +class _WallpaperTile extends StatelessWidget { + const _WallpaperTile({ + required this.label, required this.selected, required this.onTap, required this.child, - required this.label, }); + static const double width = 76; + static const double patternScale = 0.6; + static const double frameHeight = 104; + static const double height = frameHeight + 30; + static const double _ringGap = 3; + + final String label; + final bool selected; + final VoidCallback onTap; + final Widget child; + @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + final duration = AppMotion.of(const Duration(milliseconds: 220)); + final outer = selected ? 26.0 : 18.0; return Padding( - padding: const EdgeInsets.only(right: 12), - child: GestureDetector( - onTap: onTap, - child: SizedBox( - width: 96, - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - AnimatedContainer( - duration: const Duration(milliseconds: 160), - height: 116, - padding: const EdgeInsets.all(3), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(20), - border: Border.all( - color: selected ? cs.primary : Colors.transparent, - width: 2.5, + padding: const EdgeInsets.only(right: 10), + child: Semantics( + button: true, + selected: selected, + label: label, + excludeSemantics: true, + child: GestureDetector( + onTap: onTap, + behavior: HitTestBehavior.opaque, + child: SizedBox( + width: width, + child: Column( + children: [ + AnimatedContainer( + duration: duration, + curve: Curves.easeOutCubic, + height: frameHeight, + padding: const EdgeInsets.all(_ringGap), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(outer), + border: Border.all( + color: selected ? cs.primary : Colors.transparent, + width: 2.5, + ), ), - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(15), - child: Stack( - fit: StackFit.expand, - children: [ - child, - if (selected) - Align( - alignment: Alignment.bottomRight, - child: Container( - margin: const EdgeInsets.all(6), - padding: const EdgeInsets.all(3), + child: TweenAnimationBuilder( + tween: Tween(end: outer - _ringGap), + duration: duration, + curve: Curves.easeOutCubic, + builder: (context, radius, _) => ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: Stack( + fit: StackFit.expand, + children: [ + DecoratedBox( decoration: BoxDecoration( - color: cs.primary, - shape: BoxShape.circle, + color: cs.surfaceContainerHighest, ), - child: Icon( - Symbols.check, - size: 16, - color: cs.onPrimary, + child: child, + ), + AnimatedScale( + scale: selected ? 1 : 0, + duration: duration, + curve: Curves.easeOutBack, + alignment: Alignment.topRight, + child: Align( + alignment: Alignment.topRight, + child: Padding( + padding: const EdgeInsets.all(6), + child: DecoratedBox( + decoration: BoxDecoration( + color: cs.primary, + shape: BoxShape.circle, + ), + child: Padding( + padding: const EdgeInsets.all(2), + child: Icon( + Symbols.check, + size: 14, + weight: 600, + color: cs.onPrimary, + ), + ), + ), + ), ), ), - ), - ], + ], + ), + ), ), ), - ), - const SizedBox(height: 6), - Text( - label, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - color: selected ? cs.primary : cs.onSurfaceVariant, - fontSize: 12, - fontWeight: FontWeight.w600, - fontFamily: displayFontOf(context), + const SizedBox(height: 8), + AnimatedDefaultTextStyle( + duration: duration, + style: DefaultTextStyle.of(context).style.merge( + TextStyle( + color: selected ? cs.onSurface : cs.onSurfaceVariant, + fontSize: 12, + fontWeight: selected ? FontWeight.w600 : FontWeight.w500, + ), + ), + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), ), - ), - ], + ], + ), ), ), ), @@ -464,193 +608,50 @@ class _TileFrame extends StatelessWidget { } } -class _NoneTile extends StatelessWidget { - final bool selected; - final VoidCallback onTap; +class _TileIcon extends StatelessWidget { + const _TileIcon(this.icon); - const _NoneTile({required this.selected, required this.onTap}); + final IconData icon; @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - return _TileFrame( - selected: selected, - onTap: onTap, - label: AppLocalizations.of(context)!.chatWallpaperSheetNone, - child: ColoredBox( - color: cs.surfaceContainerHighest, - child: const Center( - child: Icon(Symbols.block, color: kDangerRed, size: 34), - ), - ), - ); - } + Widget build(BuildContext context) => Center( + child: Icon( + icon, + size: 26, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ); } -class _CurrentImageTile extends StatelessWidget { - final ChatWallpaper wallpaper; - final bool selected; - final VoidCallback onTap; +class _TileWallpaper extends StatelessWidget { + const _TileWallpaper({required this.wallpaper}); - const _CurrentImageTile({ - required this.wallpaper, - required this.selected, - required this.onTap, - }); + final ChatWallpaper wallpaper; @override Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; final path = wallpaper.imagePath; - return _TileFrame( - selected: selected, - onTap: onTap, - label: AppLocalizations.of(context)!.chatWallpaperSheetYourPhoto, - child: path == null - ? ColoredBox(color: cs.surfaceContainerHighest) - : Image.file(File(path), fit: BoxFit.cover), - ); - } -} - -class _CustomGradientTile extends StatelessWidget { - final ChatWallpaper? current; - final VoidCallback onTap; - - const _CustomGradientTile({required this.current, required this.onTap}); - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - final colors = current?.gradientColors; - return _TileFrame( - selected: false, - onTap: onTap, - label: AppLocalizations.of(context)!.themeSettingsCustomTitle, - child: colors != null && colors.isNotEmpty - ? MeshGradientBackground( - colors: colors, - animate: false, - rotation: current?.gradientRotation ?? 0, - ) - : ColoredBox( - color: cs.surfaceContainerHighest, - child: Center( - child: Icon(Symbols.palette, color: cs.onSurface, size: 30), - ), - ), - ); - } -} - -class _ThemeTile extends StatelessWidget { - final ChatWallpaperTheme theme; - final bool selected; - final VoidCallback onTap; - - const _ThemeTile({ - required this.theme, - required this.selected, - required this.onTap, - }); - - String _name(AppLocalizations l10n) => switch (theme.id) { - 'ocean' => l10n.chatWallpaperThemeOcean, - 'sunset' => l10n.chatWallpaperThemeSunset, - 'lavender' => l10n.chatWallpaperThemeLavender, - 'mint' => l10n.chatWallpaperThemeMint, - 'graphite' => l10n.chatWallpaperThemeGraphite, - 'sky' => l10n.chatWallpaperThemeSky, - 'peach' => l10n.chatWallpaperThemePeach, - 'forest' => l10n.chatWallpaperThemeForest, - 'grape' => l10n.chatWallpaperThemeGrape, - 'night' => l10n.chatWallpaperThemeNight, - 'rose' => l10n.chatWallpaperThemeRose, - 'amber' => l10n.chatWallpaperThemeAmber, - _ => theme.id, - }; - - @override - Widget build(BuildContext context) { - return _TileFrame( - selected: selected, - onTap: onTap, - label: _name(AppLocalizations.of(context)!), - child: theme.buildPreview(), - ); - } -} - -class _GalleryButton extends StatelessWidget { - final VoidCallback onTap; - - const _GalleryButton({required this.onTap}); - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - return GestureDetector( - onTap: onTap, - child: Container( - height: 52, - decoration: BoxDecoration( - color: cs.surfaceContainerHighest, - borderRadius: BorderRadius.circular(16), - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Symbols.image, color: cs.onSurface, size: 22), - const SizedBox(width: 8), - Text( - AppLocalizations.of(context)!.chatWallpaperSheetFromGallery, - style: TextStyle( - color: cs.onSurface, - fontSize: 16, - fontWeight: FontWeight.w600, - fontFamily: displayFontOf(context), - ), - ), - ], - ), - ), - ); - } -} - -class _ApplyButton extends StatelessWidget { - final bool enabled; - final VoidCallback onTap; - - const _ApplyButton({required this.enabled, required this.onTap}); - - @override - Widget build(BuildContext context) { - final cs = Theme.of(context).colorScheme; - return GestureDetector( - onTap: enabled ? onTap : null, - child: AnimatedOpacity( - duration: const Duration(milliseconds: 140), - opacity: enabled ? 1 : 0.4, - child: Container( - height: 52, - decoration: BoxDecoration( - color: cs.primary, - borderRadius: BorderRadius.circular(16), - ), - child: Center( - child: Text( - AppLocalizations.of(context)!.spoofButtonApply, - style: TextStyle( - color: cs.onPrimary, - fontSize: 16, - fontWeight: FontWeight.w700, - fontFamily: displayFontOf(context), - ), - ), - ), - ), - ), + if (wallpaper.isImage && path != null) { + return Image.file( + File(path), + fit: BoxFit.cover, + cacheWidth: 240, + errorBuilder: (_, _, _) => const _TileIcon(Symbols.image), + ); + } + final colors = wallpaper.gradientColors; + if (wallpaper.isGradient && colors != null && colors.isNotEmpty) { + return MeshGradientBackground( + colors: colors, + animate: false, + rotation: wallpaper.gradientRotation, + ); + } + final theme = chatWallpaperThemeById(wallpaper.themeId); + if (theme == null) return const _TileIcon(Symbols.wallpaper); + return ThemeWallpaper( + theme: theme, + patternScale: _WallpaperTile.patternScale, ); } } diff --git a/lib/frontend/widgets/chat_wallpaper_view.dart b/lib/frontend/widgets/chat_wallpaper_view.dart index 8e6665d5..550ce895 100644 --- a/lib/frontend/widgets/chat_wallpaper_view.dart +++ b/lib/frontend/widgets/chat_wallpaper_view.dart @@ -8,6 +8,7 @@ import 'package:sensors_plus/sensors_plus.dart'; import 'package:komet/core/config/chat_wallpaper_themes.dart'; import 'package:komet/core/storage/chat_wallpaper_store.dart'; import 'package:komet/frontend/widgets/mesh_gradient_background.dart'; +import 'theme_wallpaper.dart'; class WallpaperImages { WallpaperImages._(); @@ -89,7 +90,7 @@ class ChatWallpaperView extends StatelessWidget { } final theme = chatWallpaperThemeById(wallpaper.themeId); if (theme == null) return const SizedBox.shrink(); - return theme.buildBackground(); + return ThemeWallpaper(theme: theme, pinned: true); } } diff --git a/lib/frontend/widgets/compact_bottom_navigation_bar.dart b/lib/frontend/widgets/compact_bottom_navigation_bar.dart index 1a93a347..ada9230f 100644 --- a/lib/frontend/widgets/compact_bottom_navigation_bar.dart +++ b/lib/frontend/widgets/compact_bottom_navigation_bar.dart @@ -41,14 +41,18 @@ class CompactBottomNavigationBar extends StatelessWidget { children: [ for (var index = 0; index < items.length; index++) Expanded( - child: _CompactTab( - item: items[index], - selected: index == currentIndex, - onTap: () => onTap(index), - onLongPress: - items[index].longPressable && onItemLongPress != null - ? (position) => onItemLongPress!(index, position) - : null, + child: items[index].spotlit( + BorderRadius.circular(14), + () => onTap(index), + _CompactTab( + item: items[index], + selected: index == currentIndex, + onTap: () => onTap(index), + onLongPress: + items[index].longPressable && onItemLongPress != null + ? (position) => onItemLongPress!(index, position) + : null, + ), ), ), ], diff --git a/lib/frontend/widgets/custom_notification.dart b/lib/frontend/widgets/custom_notification.dart index 8f04f584..3822123a 100644 --- a/lib/frontend/widgets/custom_notification.dart +++ b/lib/frontend/widgets/custom_notification.dart @@ -3,19 +3,24 @@ import 'package:flutter/material.dart'; import 'toast_placement.dart'; const Duration _defaultNotificationDuration = Duration(milliseconds: 2600); +const Duration _actionNotificationDuration = Duration(milliseconds: 4000); const double _bottomGap = 72; OverlayEntry? _activeNotification; +typedef NotificationAction = ({String label, VoidCallback onTap}); + void showCustomNotification( BuildContext context, String message, { Duration? duration, + NotificationAction? action, }) { showCustomNotificationOnOverlay( Overlay.of(context), message, duration: duration, + action: action, ); } @@ -23,11 +28,29 @@ void showCustomNotificationOnOverlay( OverlayState overlay, String message, { Duration? duration, + NotificationAction? action, }) { - final total = duration ?? _defaultNotificationDuration; + final total = + duration ?? + (action == null + ? _defaultNotificationDuration + : _actionNotificationDuration); _removeNotification(_activeNotification); - final entry = OverlayEntry( - builder: (context) => CustomNotification(message: message, duration: total), + late final OverlayEntry entry; + entry = OverlayEntry( + builder: (context) => CustomNotification( + message: message, + duration: total, + action: action == null + ? null + : ( + label: action.label, + onTap: () { + _removeNotification(entry); + action.onTap(); + }, + ), + ), ); _activeNotification = entry; overlay.insert(entry); @@ -46,9 +69,11 @@ void _removeNotification(OverlayEntry? entry) { class CustomNotification extends StatefulWidget { final String message; final Duration duration; + final NotificationAction? action; const CustomNotification({ required this.message, this.duration = _defaultNotificationDuration, + this.action, super.key, }); @@ -89,6 +114,16 @@ class _CustomNotificationState extends State @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; + final action = widget.action; + final text = Text( + widget.message, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurface, + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ); return ToastBottomPositioned( left: 12, right: 12, @@ -96,8 +131,9 @@ class _CustomNotificationState extends State bandHeight: 48, minWidth: 160, child: IgnorePointer( + ignoring: action == null, child: Material( - color: Colors.transparent, + type: MaterialType.transparency, child: Center( child: FadeTransition( opacity: _opacity, @@ -110,15 +146,27 @@ class _CustomNotificationState extends State color: cs.surfaceContainerHighest, borderRadius: BorderRadius.circular(50), ), - child: Text( - widget.message, - textAlign: TextAlign.center, - style: TextStyle( - color: cs.onSurface, - fontSize: 14, - fontWeight: FontWeight.w500, - ), - ), + child: action == null + ? text + : Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: text), + const SizedBox(width: 14), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: action.onTap, + child: Text( + action.label, + style: TextStyle( + color: cs.primary, + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + ), + ], + ), ), ), ), diff --git a/lib/frontend/widgets/direct_call.dart b/lib/frontend/widgets/direct_call.dart index 6e103ae5..b89c3b6b 100644 --- a/lib/frontend/widgets/direct_call.dart +++ b/lib/frontend/widgets/direct_call.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../backend/modules/calls.dart'; import '../../core/calls/call_controller.dart'; +import '../../core/calls/call_permissions.dart'; import '../../l10n/app_localizations.dart'; import '../screens/calls/call_screen.dart'; import 'custom_notification.dart'; @@ -45,6 +46,11 @@ Future startDirectCall( } on CallPeerIsBotException { if (context.mounted) showCustomNotification(context, l10n.callPeerIsBot); return false; + } on CallMicrophonePermissionException { + if (context.mounted) { + showCustomNotification(context, l10n.callMicrophonePermissionDenied); + } + return false; } catch (_) { if (context.mounted) { showCustomNotification(context, l10n.chatInfoCallFailed); diff --git a/lib/frontend/widgets/e2ee_banner.dart b/lib/frontend/widgets/e2ee_banner.dart index 2a54cd44..23c57d7a 100644 --- a/lib/frontend/widgets/e2ee_banner.dart +++ b/lib/frontend/widgets/e2ee_banner.dart @@ -40,7 +40,9 @@ class E2eeBanner extends StatelessWidget { margin: const EdgeInsets.fromLTRB(12, 8, 12, 4), padding: const EdgeInsets.fromLTRB(14, 12, 10, 10), decoration: BoxDecoration( - color: keyChanged ? cs.errorContainer : cs.primaryContainer, + color: keyChanged + ? cs.surfaceContainerHighest + : cs.primaryContainer, borderRadius: BorderRadius.circular(16), ), child: Column( @@ -52,9 +54,7 @@ class E2eeBanner extends StatelessWidget { Icon( keyChanged ? Symbols.warning : Symbols.lock, size: 20, - color: keyChanged - ? cs.onErrorContainer - : cs.onPrimaryContainer, + color: keyChanged ? cs.error : cs.onPrimaryContainer, ), const SizedBox(width: 10), Expanded( @@ -66,7 +66,7 @@ class E2eeBanner extends StatelessWidget { : l10n.e2eeBannerPending(peerName), style: TextStyle( color: keyChanged - ? cs.onErrorContainer + ? cs.onSurface : cs.onPrimaryContainer, fontSize: 14, height: 1.3, diff --git a/lib/frontend/widgets/format_selection_toolbar.dart b/lib/frontend/widgets/format_selection_toolbar.dart new file mode 100644 index 00000000..7a3d9905 --- /dev/null +++ b/lib/frontend/widgets/format_selection_toolbar.dart @@ -0,0 +1,233 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/config/app_unchecked_links.dart'; +import '../../core/media/clipboard/clipboard_media.dart'; +import '../../core/utils/haptics.dart'; +import '../../core/utils/text_format.dart'; +import '../../l10n/app_localizations.dart'; +import 'custom_notification.dart'; +import 'link_text.dart'; +import 'prompt_dialog.dart'; +import 'rich_message_controller.dart'; +import 'selection_toolbar.dart'; + +class FormatSelectionToolbar extends StatefulWidget { + const FormatSelectionToolbar({ + super.key, + required this.controller, + required this.editableState, + this.onPasteMedia, + }); + + final RichMessageController controller; + final EditableTextState editableState; + final VoidCallback? onPasteMedia; + + @override + State createState() => _FormatSelectionToolbarState(); +} + +class _FormatSelectionToolbarState extends State { + static final Expando _formattedRange = Expando(); + + static const Set _clipboardActions = { + ContextMenuButtonType.cut, + ContextMenuButtonType.copy, + ContextMenuButtonType.paste, + }; + + bool _formatting = false; + bool _clipboardHasMedia = false; + + bool get _canFormat { + final selection = widget.controller.selection; + return selection.isValid && !selection.isCollapsed; + } + + bool get _resumesFormatting { + final kept = _formattedRange[widget.controller]; + if (kept == null || !_canFormat) return false; + final selection = widget.controller.selection; + return selection.start < kept.end && selection.end > kept.start; + } + + @override + void initState() { + super.initState(); + _formatting = _resumesFormatting; + widget.controller.addListener(_onControllerChanged); + if (widget.onPasteMedia != null) unawaited(_probeClipboard()); + } + + @override + void didUpdateWidget(FormatSelectionToolbar oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller == widget.controller) return; + oldWidget.controller.removeListener(_onControllerChanged); + widget.controller.addListener(_onControllerChanged); + } + + @override + void dispose() { + widget.controller.removeListener(_onControllerChanged); + _formattedRange[widget.controller] = _formatting && _canFormat + ? widget.controller.selection + : null; + super.dispose(); + } + + void _onControllerChanged() { + setState(() { + if (!_canFormat) _formatting = false; + }); + } + + Future _probeClipboard() async { + final hasMedia = await ClipboardMedia.hasMedia(); + if (!mounted || !hasMedia) return; + setState(() => _clipboardHasMedia = true); + } + + void _setFormatting(bool value) { + if (_formatting == value) return; + setState(() => _formatting = value); + } + + void _pasteMedia() { + widget.editableState.hideToolbar(); + widget.onPasteMedia?.call(); + } + + void _applyFormat(TextFormat format) { + final controller = widget.controller; + final selection = controller.selection; + if (format != TextFormat.link) { + Haptics.selection(); + controller.toggleFormat(format); + } else if (controller.isFormatActive(format)) { + Haptics.selection(); + controller.setLink(selection, null); + } else { + final editable = widget.editableState; + editable.hideToolbar(); + unawaited(_promptLink(editable.context, controller, selection)); + } + } + + List _textActions(AppLocalizations l10n) { + final actions = [...widget.editableState.contextMenuButtonItems]; + if (widget.onPasteMedia != null && _clipboardHasMedia) { + final index = actions.indexWhere( + (action) => !_clipboardActions.contains(action.type), + ); + actions.insert( + index == -1 ? actions.length : index, + ContextMenuButtonItem( + label: l10n.composerPasteAttachment, + onPressed: _pasteMedia, + ), + ); + } + return actions; + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final formatting = _formatting && _canFormat; + return SelectionToolbar( + anchors: widget.editableState.contextMenuAnchors, + floor: SelectionToolbarFloor.topOf(widget.editableState.context), + depth: formatting ? 1 : 0, + onBack: formatting ? () => _setFormatting(false) : null, + items: formatting ? _formatItems(l10n) : _actionItems(context, l10n), + ); + } + + List _actionItems( + BuildContext context, + AppLocalizations l10n, + ) { + return [ + if (_canFormat) + SelectionToolbarItem( + icon: Symbols.text_format, + tint: Theme.of(context).colorScheme.primary, + label: l10n.chatScreenFormatMenu, + onPressed: () => _setFormatting(true), + ), + for (final action in _textActions(l10n)) + if (action.onPressed case final onPressed?) + if (AdaptiveTextSelectionToolbar.getButtonLabel(context, action) + case final label when label.isNotEmpty) + SelectionToolbarItem(label: label, onPressed: onPressed), + ]; + } + + List _formatItems(AppLocalizations l10n) { + final controller = widget.controller; + return [ + for (final format in composerFormats) + SelectionToolbarItem( + icon: _formatIcon(format), + tint: format == TextFormat.code ? codeTextColor : null, + label: _formatLabel(l10n, format), + selected: controller.isFormatActive(format), + onPressed: () => _applyFormat(format), + ), + ]; + } +} + +Future _promptLink( + BuildContext context, + RichMessageController controller, + TextRange range, +) async { + final l10n = AppLocalizations.of(context)!; + final raw = await showTextInputDialog( + context, + title: l10n.chatScreenFormatLinkTitle, + hint: l10n.chatScreenFormatLinkHint, + keyboardType: TextInputType.url, + ); + if (raw == null || !context.mounted) return; + final url = AppUncheckedLinks.current.value ? raw : linkFromInput(raw); + if (url == null) { + showCustomNotification(context, l10n.chatScreenFormatLinkInvalid); + return; + } + controller.setLink(range, url); +} + +IconData _formatIcon(TextFormat format) => switch (format) { + TextFormat.strong => Symbols.format_bold, + TextFormat.emphasized => Symbols.format_italic, + TextFormat.underline => Symbols.format_underlined, + TextFormat.strikethrough => Symbols.format_strikethrough, + TextFormat.monospaced => Symbols.code, + TextFormat.code => Symbols.format_color_text, + TextFormat.heading => Symbols.format_h1, + TextFormat.quote => Symbols.format_quote, + TextFormat.link => Symbols.link, + TextFormat.animoji => Symbols.mood, + TextFormat.userMention => Symbols.alternate_email, +}; + +String _formatLabel(AppLocalizations l10n, TextFormat format) => + switch (format) { + TextFormat.heading => l10n.chatScreenFormatHeading, + TextFormat.strong => l10n.chatScreenFormatBold, + TextFormat.emphasized => l10n.chatScreenFormatItalic, + TextFormat.underline => l10n.chatScreenFormatUnderline, + TextFormat.strikethrough => l10n.chatScreenFormatStrikethrough, + TextFormat.monospaced => l10n.chatScreenFormatMonospace, + TextFormat.code => l10n.chatScreenFormatRed, + TextFormat.quote => l10n.chatScreenFormatQuote, + TextFormat.link => l10n.chatScreenFormatLink, + TextFormat.animoji => 'Animoji', + TextFormat.userMention => l10n.chatScreenFormatMention, + }; diff --git a/lib/frontend/widgets/formatted_message_text.dart b/lib/frontend/widgets/formatted_message_text.dart index e9f3a952..9b3d6cff 100644 --- a/lib/frontend/widgets/formatted_message_text.dart +++ b/lib/frontend/widgets/formatted_message_text.dart @@ -113,20 +113,27 @@ class FormattedMessageText extends StatefulWidget { State createState() => _FormattedMessageTextState(); } +typedef _LinkText = ({int start, int end, String text}); + class _ParsedText { const _ParsedText({ required this.entities, required this.segments, - required this.hiddenLinks, + required this.links, }); final List entities; final List segments; - final List hiddenLinks; + final List<_LinkText> links; - bool hidesLink(FormatSegment segment) => hiddenLinks.any( - (link) => link.start <= segment.start && link.end >= segment.end, - ); + String? linkTextOf(FormatSegment segment) { + for (final link in links) { + if (link.start <= segment.start && link.end >= segment.end) { + return link.text; + } + } + return null; + } } class _FormattedMessageTextState extends State { @@ -160,24 +167,21 @@ class _FormattedMessageTextState extends State { return _ParsedText( entities: detectTextEntities(widget.text, skip: _claimedRanges(ranges)), segments: segmentizeFormats(widget.text, ranges), - hiddenLinks: _hiddenLinks(ranges), + links: _linkTexts(ranges), ); } - List _hiddenLinks(List ranges) { + List<_LinkText> _linkTexts(List ranges) { final text = widget.text; - final hidden = []; + final links = <_LinkText>[]; for (final range in ranges) { - final url = range.url; - if (range.format != TextFormat.link || url == null) continue; + if (range.format != TextFormat.link || range.url == null) continue; final start = range.start.clamp(0, text.length); final end = range.end.clamp(0, text.length); if (end <= start) continue; - if (!linkShowsItsTarget(text.substring(start, end), url)) { - hidden.add((start: start, end: end)); - } + links.add((start: start, end: end, text: text.substring(start, end))); } - return hidden; + return links; } @override @@ -428,14 +432,15 @@ class _FormattedMessageTextState extends State { if (segment.url != null) { final url = segment.url!; - final hidden = _parsed.hidesLink(segment); + final shownText = _parsed.linkTextOf(segment); spans.add( TextSpan( text: content, style: style, recognizer: _track( TapGestureRecognizer() - ..onTap = () => openMessageLink(context, url, hidden: hidden), + ..onTap = () => + openMessageLink(context, url, shownText: shownText), ), ), ); diff --git a/lib/frontend/widgets/glossy_pill.dart b/lib/frontend/widgets/glossy_pill.dart index 6c687a0c..e884494a 100644 --- a/lib/frontend/widgets/glossy_pill.dart +++ b/lib/frontend/widgets/glossy_pill.dart @@ -203,63 +203,77 @@ class GlossyPill extends StatelessWidget { final base = color ?? cs.surfaceContainerHigh; final content = Padding(padding: padding, child: child); final sigma = _sigmaFor(base); + final fill = DecoratedBox( + decoration: BoxDecoration( + color: gradient ? null : base, + gradient: gradient ? GlossyDecor.fillGradient(base) : null, + ), + ); return RepaintBoundary( child: DecoratedBox( decoration: BoxDecoration( borderRadius: borderRadius, - color: gradient ? null : base, - gradient: gradient ? GlossyDecor.fillGradient(base) : null, - border: borderSide != null - ? Border.fromBorderSide(borderSide!) - : GlossyDecor.rimBorder(base), boxShadow: [GlossyDecor.dropShadow(base, depth)], ), - child: ClipRRect( - borderRadius: borderRadius, - child: Stack( - fit: StackFit.passthrough, - children: [ - if (sigma != null) + child: DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + borderRadius: borderRadius, + border: borderSide != null + ? Border.fromBorderSide(borderSide!) + : GlossyDecor.rimBorder(base), + ), + child: ClipRRect( + borderRadius: borderRadius, + child: Stack( + fit: StackFit.passthrough, + children: [ Positioned.fill( - child: BackdropFilter( - filter: ui.ImageFilter.blur(sigmaX: sigma, sigmaY: sigma), - backdropGroupKey: backdropKey, - child: const SizedBox.expand(), - ), + child: sigma == null + ? fill + : BackdropFilter( + filter: ui.ImageFilter.blur( + sigmaX: sigma, + sigmaY: sigma, + ), + backdropGroupKey: backdropKey, + child: fill, + ), ), - if (gradient) ...[ - Positioned.fill( - child: IgnorePointer( - child: DecoratedBox( - decoration: BoxDecoration( - gradient: GlossyDecor.topSheen(base), + if (gradient) ...[ + Positioned.fill( + child: IgnorePointer( + child: DecoratedBox( + decoration: BoxDecoration( + gradient: GlossyDecor.topSheen(base), + ), ), ), ), - ), - Positioned.fill( - child: IgnorePointer( - child: DecoratedBox( - decoration: BoxDecoration( - gradient: GlossyDecor.bottomShade(base), + Positioned.fill( + child: IgnorePointer( + child: DecoratedBox( + decoration: BoxDecoration( + gradient: GlossyDecor.bottomShade(base), + ), ), ), ), - ), - ], - if (_inert) - content - else - Material( - type: MaterialType.transparency, - child: InkWell( - onTap: onTap, - onLongPress: onLongPress, - child: content, + ], + if (_inert) + content + else + Material( + type: MaterialType.transparency, + child: InkWell( + onTap: onTap, + onLongPress: onLongPress, + child: content, + ), ), - ), - ], + ], + ), ), ), ), diff --git a/lib/frontend/widgets/info_action_sheet.dart b/lib/frontend/widgets/info_action_sheet.dart index 8089d55a..dd5a44cc 100644 --- a/lib/frontend/widgets/info_action_sheet.dart +++ b/lib/frontend/widgets/info_action_sheet.dart @@ -32,6 +32,7 @@ Future showInfoActionSheet( required String title, String? subtitle, List items = const [], + String? footnote, String? confirmLabel, Duration confirmDelay = Duration.zero, String? seenKey, @@ -61,6 +62,7 @@ Future showInfoActionSheet( title: title, subtitle: subtitle, items: items, + footnote: footnote, confirmLabel: confirmLabel ?? AppLocalizations.of(ctx)!.photoEditorOk, confirmDelay: confirmDelay, ), @@ -81,6 +83,7 @@ class _InfoActionSheet extends StatefulWidget { final String title; final String? subtitle; final List items; + final String? footnote; final String confirmLabel; final Duration confirmDelay; @@ -91,6 +94,7 @@ class _InfoActionSheet extends StatefulWidget { required this.title, this.subtitle, this.items = const [], + this.footnote, required this.confirmLabel, required this.confirmDelay, }); @@ -182,6 +186,19 @@ class _InfoActionSheetState extends State<_InfoActionSheet> { const SizedBox(height: 18), ], ], + if (widget.footnote != null) ...[ + const SizedBox(height: 24), + Text( + widget.footnote!, + textAlign: TextAlign.center, + style: TextStyle( + color: cs.onSurfaceVariant.withValues(alpha: 0.8), + fontSize: 12.5, + fontWeight: FontWeight.w400, + height: 1.35, + ), + ), + ], ], ), ), diff --git a/lib/frontend/widgets/informer_banner_tile.dart b/lib/frontend/widgets/informer_banner_tile.dart index ffd5eb13..0d39ee43 100644 --- a/lib/frontend/widgets/informer_banner_tile.dart +++ b/lib/frontend/widgets/informer_banner_tile.dart @@ -13,6 +13,7 @@ class InformerBannerTile extends StatefulWidget { final ValueChanged? onPresented; final VoidCallback? onTap; final VoidCallback? onClose; + final String? note; const InformerBannerTile({ super.key, @@ -21,6 +22,7 @@ class InformerBannerTile extends StatefulWidget { this.onPresented, this.onTap, this.onClose, + this.note, }); @override @@ -148,6 +150,21 @@ class _InformerBannerTileState extends State height: 1.2, ), ), + if (widget.note case final note?) ...[ + const SizedBox(height: 3), + Text( + note, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: cs.onSurfaceVariant.withValues( + alpha: 0.75, + ), + fontSize: 11.5, + height: 1.2, + ), + ), + ], ], ), ), diff --git a/lib/frontend/widgets/link_confirm_sheet.dart b/lib/frontend/widgets/link_confirm_sheet.dart index 890f52ca..5bd79aa2 100644 --- a/lib/frontend/widgets/link_confirm_sheet.dart +++ b/lib/frontend/widgets/link_confirm_sheet.dart @@ -5,57 +5,113 @@ import 'package:material_symbols_icons/symbols.dart'; import '../../core/config/app_fonts.dart'; import '../../core/config/app_shape.dart'; +import '../../core/links/link_inspector.dart'; import '../../core/links/visited_link_sites.dart'; import '../../core/utils/link_opener.dart'; import '../../l10n/app_localizations.dart'; +import 'alert_note.dart'; import 'sheet_helpers.dart'; -bool linkShowsItsTarget(String text, String url) { - String bare(String value) => value - .trim() - .toLowerCase() - .replaceFirst(RegExp(r'^[a-z][a-z0-9+.-]*://'), '') - .replaceFirst(RegExp(r'^www\.'), '') - .replaceFirst(RegExp(r'/+$'), ''); - return bare(text) == bare(url); -} - Future openMessageLink( BuildContext context, String url, { - required bool hidden, + String? shownText, }) async { - final external = !linkStaysInApp(url); - if (external && hidden && !await VisitedLinkSites.contains(url)) { + final target = linkWithScheme(url); + if (linkStaysInApp(target)) { + await openExternalUrl(context, target); + return; + } + final inspection = inspectLink(target, shownText: shownText); + if (inspection.suspicious || !await VisitedLinkSites.contains(target)) { if (!context.mounted) return; - if (!await showLinkConfirmSheet(context, url)) return; + if (!await _showLinkConfirmSheet(context, inspection)) return; } if (!context.mounted) return; - if (external) unawaited(VisitedLinkSites.remember(url)); - await openExternalUrl(context, url); + if (!inspection.suspicious) unawaited(VisitedLinkSites.remember(target)); + await openExternalUrl(context, target); } -Future showLinkConfirmSheet(BuildContext context, String url) async { +Future previewLinkCheck(BuildContext context, String url) => + _showLinkConfirmSheet(context, inspectLink(url)); + +Future _showLinkConfirmSheet( + BuildContext context, + LinkInspection inspection, +) async { final cs = Theme.of(context).colorScheme; final confirmed = await showModalBottomSheet( context: context, isScrollControlled: true, backgroundColor: cs.surfaceContainerHigh, shape: kSheetShape, - builder: (_) => _LinkConfirmSheet(url: url), + builder: (_) => _LinkConfirmSheet(inspection: inspection), ); return confirmed == true; } +String _warningText( + AppLocalizations l10n, + LinkWarning warning, + LinkInspection inspection, +) { + switch (warning.kind) { + case LinkWarningKind.textMismatch: + return l10n.linkWarningTextMismatch(warning.value, inspection.host); + case LinkWarningKind.userInfo: + return l10n.linkWarningUserInfo(warning.value); + case LinkWarningKind.mixedScripts: + return l10n.linkWarningMixedScripts(_letters(l10n, warning.letters)); + case LinkWarningKind.lookalikeScript: + return l10n.linkWarningLookalike( + _scriptName(l10n, warning.letters.first.script), + ); + case LinkWarningKind.invisibleCharacters: + return l10n.linkWarningInvisible; + case LinkWarningKind.ipAddress: + return l10n.linkWarningIpAddress; + case LinkWarningKind.unusualScheme: + return l10n.linkWarningScheme(warning.value); + } +} + +String _letters(AppLocalizations l10n, List letters) { + final byScript = >{}; + for (final letter in letters) { + (byScript[letter.script] ??= []).add(l10n.linkWarningLetter(letter.letter)); + } + return [ + for (final entry in byScript.entries) + l10n.linkWarningLetters( + entry.value.join(', '), + _scriptName(l10n, entry.key), + ), + ].join('; '); +} + +String _scriptName(AppLocalizations l10n, LinkScript script) { + switch (script) { + case LinkScript.latin: + return l10n.linkScriptLatin; + case LinkScript.cyrillic: + return l10n.linkScriptCyrillic; + case LinkScript.greek: + return l10n.linkScriptGreek; + case LinkScript.armenian: + return l10n.linkScriptArmenian; + } +} + class _LinkConfirmSheet extends StatelessWidget { - const _LinkConfirmSheet({required this.url}); + const _LinkConfirmSheet({required this.inspection}); - final String url; + final LinkInspection inspection; @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; final l10n = AppLocalizations.of(context)!; + final suspicious = inspection.suspicious; return SafeArea( child: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(20, 0, 20, 16), @@ -66,9 +122,11 @@ class _LinkConfirmSheet extends StatelessWidget { const Align(alignment: Alignment.center, child: SheetGrabber()), const SizedBox(height: 6), Text( - l10n.linkConfirmTitle, + suspicious + ? l10n.linkConfirmSuspiciousTitle + : l10n.linkConfirmTitle, style: TextStyle( - color: cs.onSurface, + color: suspicious ? cs.error : cs.onSurface, fontSize: 18, fontWeight: FontWeight.w600, fontFamily: displayFontOf(context), @@ -84,40 +142,69 @@ class _LinkConfirmSheet extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Icon(Symbols.link, color: cs.primary, size: 20), + Icon( + suspicious ? Symbols.gpp_maybe : Symbols.link, + color: suspicious ? cs.error : cs.primary, + size: 20, + ), const SizedBox(width: 10), - Expanded(child: _LinkAddress(url: url)), + Expanded(child: _LinkAddress(inspection: inspection)), ], ), ), const SizedBox(height: 12), - Text( - l10n.linkConfirmBody, - style: TextStyle( - color: cs.onSurfaceVariant, - fontSize: 13.5, - height: 1.35, + if (suspicious) + AlertNote.all([ + for (final warning in inspection.warnings) + _warningText(l10n, warning, inspection), + ], icon: Symbols.warning) + else + Text( + l10n.linkConfirmBody, + style: TextStyle( + color: cs.onSurfaceVariant, + fontSize: 13.5, + height: 1.35, + ), ), - ), const SizedBox(height: 18), Row( - children: [ - Expanded( - child: SheetButton( - label: l10n.linkConfirmCancel, - filled: false, - onTap: () => Navigator.of(context).pop(false), - ), - ), - const SizedBox(width: 12), - Expanded( - child: SheetButton( - label: l10n.linkConfirmOpen, - filled: true, - onTap: () => Navigator.of(context).pop(true), - ), - ), - ], + children: suspicious + ? [ + Expanded( + child: SheetButton( + label: l10n.linkConfirmOpenAnyway, + filled: false, + color: cs.error, + onTap: () => Navigator.of(context).pop(true), + ), + ), + const SizedBox(width: 12), + Expanded( + child: SheetButton( + label: l10n.linkConfirmDontOpen, + filled: true, + onTap: () => Navigator.of(context).pop(false), + ), + ), + ] + : [ + Expanded( + child: SheetButton( + label: l10n.linkConfirmCancel, + filled: false, + onTap: () => Navigator.of(context).pop(false), + ), + ), + const SizedBox(width: 12), + Expanded( + child: SheetButton( + label: l10n.linkConfirmOpen, + filled: true, + onTap: () => Navigator.of(context).pop(true), + ), + ), + ], ), ], ), @@ -126,52 +213,56 @@ class _LinkConfirmSheet extends StatelessWidget { } } +enum _AddressPart { plain, host, flagged } + class _LinkAddress extends StatelessWidget { - const _LinkAddress({required this.url}); + const _LinkAddress({required this.inspection}); - final String url; + final LinkInspection inspection; - int _hostStart(String host) { - final schemeEnd = url.indexOf('://'); - final authorityStart = schemeEnd < 0 ? 0 : schemeEnd + 3; - final at = url.indexOf('@', authorityStart); - final slash = url.indexOf('/', authorityStart); - final from = at >= 0 && (slash < 0 || at < slash) ? at + 1 : authorityStart; - return url.toLowerCase().indexOf(host, from); + _AddressPart _partAt(int index) { + if (inspection.flagged.contains(index)) return _AddressPart.flagged; + if (index >= inspection.hostStart && index < inspection.hostEnd) { + return _AddressPart.host; + } + return _AddressPart.plain; } @override Widget build(BuildContext context) { final cs = Theme.of(context).colorScheme; - final muted = TextStyle( - color: cs.onSurfaceVariant, - fontSize: 14.5, - height: 1.3, - ); - final host = Uri.tryParse(url)?.host.toLowerCase() ?? ''; - final start = host.isEmpty ? -1 : _hostStart(host); - if (start < 0) { - return Text( - url, - maxLines: 4, - overflow: TextOverflow.ellipsis, - style: muted.copyWith(color: cs.onSurface), + final styles = { + _AddressPart.plain: TextStyle(color: cs.onSurfaceVariant), + _AddressPart.host: TextStyle( + color: cs.onSurface, + fontWeight: FontWeight.w600, + ), + _AddressPart.flagged: TextStyle( + color: cs.error, + fontWeight: FontWeight.w700, + backgroundColor: cs.error.withValues(alpha: 0.16), + ), + }; + final address = inspection.address; + final spans = []; + var start = 0; + while (start < address.length) { + final part = _partAt(start); + var end = start + 1; + while (end < address.length && _partAt(end) == part) { + end++; + } + spans.add( + TextSpan(text: address.substring(start, end), style: styles[part]), ); + start = end; } - final end = start + host.length; return Text.rich( TextSpan( - style: muted, - children: [ - TextSpan(text: url.substring(0, start)), - TextSpan( - text: url.substring(start, end), - style: TextStyle(color: cs.onSurface, fontWeight: FontWeight.w600), - ), - TextSpan(text: url.substring(end)), - ], + style: const TextStyle(fontSize: 14.5, height: 1.3), + children: spans, ), - maxLines: 4, + maxLines: inspection.suspicious ? 6 : 4, overflow: TextOverflow.ellipsis, ); } diff --git a/lib/frontend/widgets/max_link_handler.dart b/lib/frontend/widgets/max_link_handler.dart index 16e1e6c1..aa17baea 100644 --- a/lib/frontend/widgets/max_link_handler.dart +++ b/lib/frontend/widgets/max_link_handler.dart @@ -252,7 +252,9 @@ Future _openResolvedChat( final myId = await currentAccountId(); var isMember = myId != 0 && await AppDatabase.isChatInList(myId, id); - await chats.cacheServerChat(chat, myId, inList: isMember); + if (!isMember || chats.cachedChat(myId, id) == null) { + await chats.cacheServerChat(chat, myId, inList: isMember); + } if (!context.mounted) return; if (link.kind == MaxContentKind.invite && @@ -293,6 +295,7 @@ Future _openResolvedChat( } final target = _messageTarget(link, resolved.message); + if (target == null && ChatScreen.revealOpenChat(id)) return; pushSwipeable( context, (_) => ChatScreen( diff --git a/lib/frontend/widgets/max_route_handler.dart b/lib/frontend/widgets/max_route_handler.dart index 1b97b09d..6fa88f37 100644 --- a/lib/frontend/widgets/max_route_handler.dart +++ b/lib/frontend/widgets/max_route_handler.dart @@ -14,6 +14,7 @@ import '../screens/profile/edit_profile_screen.dart'; import '../screens/profile/info_screen.dart'; import '../screens/profile/notifications_screen.dart'; import '../screens/profile/security_screen.dart'; +import '../screens/profile/storage_screen.dart'; import '../screens/profile/web_qr_scan_screen.dart'; import 'custom_notification.dart'; import 'max_link_nav.dart'; @@ -125,6 +126,8 @@ Future openMaxRoute( return _push(context, const NotificationsScreen()); case ':settings/devices': return _push(context, const DevicesScreen()); + case ':settings/storage': + return _push(context, const StorageScreen()); case ':settings/aboutapp': return _push(context, const InfoScreen()); case ':settings/privacy': diff --git a/lib/frontend/widgets/media_playback_pill.dart b/lib/frontend/widgets/media_playback_pill.dart index fd5fd842..008f9d7a 100644 --- a/lib/frontend/widgets/media_playback_pill.dart +++ b/lib/frontend/widgets/media_playback_pill.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:flutter/material.dart'; import 'package:material_symbols_icons/symbols.dart'; @@ -8,7 +10,9 @@ import '../../core/media/media_playback.dart'; import '../../core/utils/format.dart'; import '../../core/utils/haptics.dart'; import '../../l10n/app_localizations.dart'; +import '../screens/downloads_screen.dart'; import 'max_link_nav.dart'; +import 'swipe_route.dart'; class MediaPlaybackPill extends StatelessWidget { const MediaPlaybackPill({ @@ -102,9 +106,18 @@ class _AudioFilePill extends StatelessWidget { : 0.0; }, label: source.isEmpty ? track.name : '${track.name} · $source', + artwork: _audioArtwork(track.thumbnailUrl), onToggle: audio.toggle, onClose: MediaPlayback.instance.closeAudioFile, onOpen: () { + if (track.origin == AudioFileOrigin.downloads) { + pushSwipeable( + context, + (_) => DownloadsScreen(highlightCacheName: track.cacheName), + settings: const RouteSettings(name: DownloadsScreen.routeName), + ); + return; + } final chatId = track.chatId; final messageId = track.messageId; final messageTime = track.messageTime; @@ -118,6 +131,17 @@ class _AudioFilePill extends StatelessWidget { }, ); } + + ImageProvider? _audioArtwork(String? value) { + if (value == null || value.isEmpty) return null; + final uri = Uri.tryParse(value); + if (uri == null) return null; + if (uri.scheme == 'file') return FileImage(File.fromUri(uri)); + if (uri.scheme == 'http' || uri.scheme == 'https') { + return NetworkImage(value); + } + return null; + } } class _VoicePill extends StatelessWidget { @@ -235,6 +259,7 @@ class _PillSurface extends StatelessWidget { this.isMe, this.time, required this.label, + this.artwork, required this.onToggle, this.onSpeed, required this.onClose, @@ -251,6 +276,7 @@ class _PillSurface extends StatelessWidget { final bool? isMe; final int? time; final String? label; + final ImageProvider? artwork; final VoidCallback onToggle; final VoidCallback? onSpeed; final VoidCallback onClose; @@ -302,6 +328,21 @@ class _PillSurface extends StatelessWidget { onTap: onToggle, ), ), + if (artwork != null) + Padding( + padding: const EdgeInsets.only(right: 7), + child: ClipRRect( + borderRadius: BorderRadius.circular(5), + child: Image( + image: artwork!, + width: 22, + height: 22, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => + const SizedBox(width: 22, height: 22), + ), + ), + ), Expanded( child: Text( label ?? '$author ${l10n.playbackPillAt} $clock', diff --git a/lib/frontend/widgets/message_actions_overlay.dart b/lib/frontend/widgets/message_actions_overlay.dart index f2cb30f4..f05f63be 100644 --- a/lib/frontend/widgets/message_actions_overlay.dart +++ b/lib/frontend/widgets/message_actions_overlay.dart @@ -95,7 +95,7 @@ void showMessageActions({ ui.Image? snapshot, required Rect originRect, required Offset tapPoint, - required bool isMe, + required bool outgoing, double bottomReservedSpace = 0, required String? messageText, required String? copyText, @@ -112,6 +112,7 @@ void showMessageActions({ bool allowDelete = true, bool allowCopy = true, VoidCallback? onEdit, + VoidCallback? onRetry, VoidCallback? onReply, VoidCallback? onForward, VoidCallback? onMarkUnread, @@ -147,7 +148,7 @@ void showMessageActions({ snapshot: snapshot, originRect: originRect, tapPoint: tapPoint, - isMe: isMe, + outgoing: outgoing, bottomReservedSpace: bottomReservedSpace, messageText: messageText, copyText: copyText, @@ -164,6 +165,7 @@ void showMessageActions({ allowDelete: allowDelete, allowCopy: allowCopy, onEdit: onEdit, + onRetry: onRetry, onReply: onReply, onForward: onForward, onMarkUnread: onMarkUnread, @@ -194,7 +196,7 @@ class _MessageActionsLayer extends StatefulWidget { final ui.Image? snapshot; final Rect originRect; final Offset tapPoint; - final bool isMe; + final bool outgoing; // #***! высота панели композера, которая не входит в MediaQuery.viewInsets // (она видна и без клавиатуры) — без этого меню/реакции могли вылезать // за неё или за нижний край экрана @@ -215,6 +217,7 @@ class _MessageActionsLayer extends StatefulWidget { final bool allowDelete; final bool allowCopy; final VoidCallback? onEdit; + final VoidCallback? onRetry; final VoidCallback? onReply; final VoidCallback? onForward; final VoidCallback? onMarkUnread; @@ -235,7 +238,7 @@ class _MessageActionsLayer extends StatefulWidget { required this.snapshot, required this.originRect, required this.tapPoint, - required this.isMe, + required this.outgoing, this.bottomReservedSpace = 0, required this.messageText, required this.copyText, @@ -253,6 +256,7 @@ class _MessageActionsLayer extends StatefulWidget { this.allowDelete = true, this.allowCopy = true, this.onEdit, + this.onRetry, this.onReply, this.onForward, this.onMarkUnread, @@ -414,7 +418,7 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> final spaceLeft = (rect.left - 16) - _hMargin; final rightFits = spaceRight >= reach; final leftFits = spaceLeft >= reach; - if (widget.isMe) { + if (widget.outgoing) { side = (leftFits || !rightFits) ? _RadialSide.left : _RadialSide.right; } else { side = (rightFits || !leftFits) ? _RadialSide.right : _RadialSide.left; @@ -518,7 +522,7 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> ? widget.originRect.bottom + 10 : widget.originRect.top - 10 - menuHeight; menuY = rawY.clamp(8.0, maxMenuY).toDouble(); - final rawX = widget.isMe + final rawX = widget.outgoing ? widget.originRect.right - menuWidth : widget.originRect.left; menuX = rawX.clamp(8.0, screenSize.width - menuWidth - 8.0).toDouble(); @@ -549,6 +553,8 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> final copyText = widget.copyText; final canCopy = widget.allowCopy && copyText != null && copyText.isNotEmpty; return <_Action>[ + if (widget.onRetry != null) + _Action(Symbols.refresh, l10n.msgActionsRetry, _retry), if (widget.onReply != null) _Action(Symbols.reply, l10n.msgActionsReply, _reply), if (widget.onForward != null) @@ -560,7 +566,7 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> _Action(Symbols.download, l10n.msgActionsSave, _save), if (widget.onSaveAs != null) _Action(Symbols.save_as, l10n.photoViewerSaveAs, _saveAs), - if (widget.isMe && widget.onEdit != null) + if (widget.onEdit != null) _Action(Symbols.edit, l10n.msgActionsEdit, _edit), if (widget.onPin != null) _Action( @@ -737,6 +743,12 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> onEdit?.call(); } + Future _retry() async { + final onRetry = widget.onRetry; + await _close(); + onRetry?.call(); + } + Future _reply() async { final onReply = widget.onReply; await _close(); @@ -1227,7 +1239,7 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> left = _menuRect.left; top = _menuRect.top; } else { - left = widget.isMe + left = widget.outgoing ? widget.originRect.right - panelWidth : widget.originRect.left; top = _showBelow @@ -1584,7 +1596,10 @@ class _MessageActionsLayerState extends State<_MessageActionsLayer> scale: scale, alignment: tapAnchored ? Alignment(-1.0, _showBelow ? -1.0 : 1.0) - : Alignment(widget.isMe ? 1.0 : -1.0, _showBelow ? -1.0 : 1.0), + : Alignment( + widget.outgoing ? 1.0 : -1.0, + _showBelow ? -1.0 : 1.0, + ), child: Material( color: cs.surfaceContainerHigh, borderRadius: BorderRadius.circular(16), diff --git a/lib/frontend/widgets/message_bubble.dart b/lib/frontend/widgets/message_bubble.dart index ed5f4837..ebcb7289 100644 --- a/lib/frontend/widgets/message_bubble.dart +++ b/lib/frontend/widgets/message_bubble.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'story_reply_quote.dart'; import 'dart:math' as math; import 'package:cached_network_image/cached_network_image.dart'; @@ -16,18 +17,17 @@ import '../../core/crypto/message_decryption_cache.dart'; import 'decrypted_text.dart'; import '../../core/utils/bubble_radius.dart'; import '../../core/utils/emoji_keyword_index.dart'; -import '../../core/utils/link_opener.dart'; import '../../core/utils/text_format.dart'; import '../../core/utils/webview_support.dart'; import '../../core/config/app_link_preview.dart'; import '../../l10n/app_localizations.dart'; import 'custom_notification.dart'; import 'hint_bubble.dart'; +import 'link_confirm_sheet.dart'; import 'formatted_message_text.dart'; import 'reply_preview.dart'; import 'sender_badge.dart'; import 'text_entity_actions.dart'; -import 'sending_clock_icon.dart'; import 'photo_viewer.dart'; import 'selectable_message_text.dart'; import '../../models/attachment.dart'; @@ -52,6 +52,7 @@ import 'message_animoji.dart'; import 'bubble_geometry.dart'; import 'text_with_meta.dart'; import 'official_name.dart'; +import 'sending_clock_icon.dart'; final Expando _contentTypeCache = Expando(); final Expando> _contentAttachmentsCache = @@ -978,6 +979,8 @@ class MessageBubble extends StatelessWidget { final CachedMessage message; final bool isMe; + final bool channelPost; + final ValueListenable? views; final int myId; final CachedMessage? prevMessage; final CachedMessage? nextMessage; @@ -1016,6 +1019,8 @@ class MessageBubble extends StatelessWidget { super.key, required this.message, required this.isMe, + this.channelPost = false, + this.views, required this.myId, this.prevMessage, this.nextMessage, @@ -1075,10 +1080,19 @@ class MessageBubble extends StatelessWidget { List get _renderableAttachments => message.attachments - ?.where((a) => a is! InlineKeyboardAttachment) + ?.where( + (a) => a is! InlineKeyboardAttachment && a is! StoryReplyAttachment, + ) .toList() ?? const []; + StoryReplyAttachment? get _storyReply { + for (final a in message.attachments ?? const []) { + if (a is StoryReplyAttachment) return a; + } + return null; + } + List get _contentAttachments => _contentAttachmentsCache[message] ??= _computeContentAttachments(); @@ -1106,8 +1120,17 @@ class MessageBubble extends StatelessWidget { return forwarded == null ? message.text : forwarded.originalText; } + bool get _outgoing => isMe && !channelPost; + + bool get _showsStatus { + if (!isMe) return false; + if (!channelPost) return true; + final status = overrideStatus ?? message.status; + return isSendingStatus(status) || status == 'error'; + } + bool get _showsSenderName => - !isMe && chatType == "CHAT" && !_groupedWithPrev; + !_outgoing && (chatType == "CHAT" || channelPost) && !_groupedWithPrev; bool get _stretchesTextRow => message.replyInfo != null || _showsSenderName; @@ -1131,12 +1154,12 @@ class MessageBubble extends StatelessWidget { bool get _groupedWithNext => !separatedBelow && _sameGroup(message, nextMessage); - static bool _sameGroup(CachedMessage? a, CachedMessage? b) => + bool _sameGroup(CachedMessage? a, CachedMessage? b) => a != null && b != null && !a.isControl && !b.isControl && - a.senderId == b.senderId && + (channelPost || a.senderId == b.senderId) && (b.time - a.time).abs() < _groupWindowMs; BubbleShape _computeShape() { @@ -1268,7 +1291,7 @@ class MessageBubble extends StatelessWidget { final isBottom = shape == BubbleShape.singleBottom || shape == BubbleShape.singleMiddle; return computeBubbleRadius( - isMe: isMe, + isMe: _outgoing, isTop: isTop, isBottom: isBottom, style: bubbleStyle, @@ -1295,7 +1318,9 @@ class MessageBubble extends StatelessWidget { _senderPalette[id.abs() % _senderPalette.length]; Widget _buildSenderHeader(ColorScheme cs, bool needsInset) { - final name = senderNameOverride ?? ContactCache.get(message.senderId); + final name = + senderNameOverride ?? + (channelPost ? peerName : ContactCache.get(message.senderId)); if (name == null || name.isEmpty) return const SizedBox.shrink(); final header = Padding( padding: needsInset @@ -1310,18 +1335,20 @@ class MessageBubble extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( - color: _senderColor(message.senderId), - fontSize: 13, + color: channelPost + ? cs.onSurface + : _senderColor(message.senderId), + fontSize: channelPost ? 14 : 13, fontWeight: FontWeight.w600, ), ), ), - SenderBadge(senderId: message.senderId, size: 13), + if (!channelPost) SenderBadge(senderId: message.senderId, size: 13), ], ), ); - final cb = onAvatarTap; + final cb = channelPost ? null : onAvatarTap; if (cb == null) return header; return GestureDetector( behavior: HitTestBehavior.opaque, @@ -1457,7 +1484,7 @@ class MessageBubble extends StatelessWidget { ? EdgeInsets.zero : _paddingFor(contentType, shape); - final showAvatarSlot = !isMe; + final showAvatarSlot = !_outgoing; final showAvatar = showAvatarSlot && chatType == "CHAT" && @@ -1475,7 +1502,7 @@ class MessageBubble extends StatelessWidget { isVideoNote || _isSticker || jumboAnimoji != null; final bubbleColor = noBubbleBackground || BubbleChrome.hiddenOf(context) ? Colors.transparent - : (isMe ? cs.primaryContainer : cs.surfaceContainerHighest); + : (_outgoing ? cs.primaryContainer : cs.surfaceContainerHighest); BubbleContext makeCtx({bool metaInFooter = false}) => BubbleContext( context: context, @@ -1488,7 +1515,8 @@ class MessageBubble extends StatelessWidget { hasPhotoWithCaption: hasPhotoCap, hasMultiplePhotosNoCaption: hasMultiPhotos, message: message, - isMe: isMe, + isMe: _outgoing, + showsStatus: _showsStatus, myId: myId, chatType: chatType, chatId: chatId, @@ -1502,12 +1530,25 @@ class MessageBubble extends StatelessWidget { onStickerTap: onStickerTap, onForwardedSourceTap: onForwardedSourceTap, reactionInfo: _resolveReactionInfo(), + views: views, selectable: _wrapSelectable, ); final reactionsInside = contentType != MessageType.text; final reply = _resolvedReply(message.replyInfo); + final storyReply = reply == null ? _storyReply : null; + final Widget? quote = reply != null + ? _buildReplyQuote(context, cs, textColor, reply, maxBubbleWidth) + : storyReply != null + ? StoryReplyQuote( + reply: storyReply, + myId: myId, + accent: _senderColor(storyReply.ownerId), + textColor: textColor, + tappable: onReplyTap != null, + ) + : null; final bool hasCommentsFooter = onCommentsTap != null; final EdgeInsets containerPadding = hasCommentsFooter @@ -1533,7 +1574,7 @@ class MessageBubble extends StatelessWidget { ? _buildSenderHeader(cs, padding == EdgeInsets.zero) : null; - final Widget? replyHeader = reply == null + final Widget? replyHeader = quote == null ? null : Padding( padding: EdgeInsets.only( @@ -1541,13 +1582,7 @@ class MessageBubble extends StatelessWidget { right: padding == EdgeInsets.zero ? 8 : 0, bottom: 4, ), - child: _buildReplyQuote( - context, - cs, - textColor, - reply, - maxBubbleWidth, - ), + child: quote, ); final Widget innerContent = @@ -1563,16 +1598,10 @@ class MessageBubble extends StatelessWidget { alignment: AlignmentDirectional.centerStart, child: senderHeader, ), - if (reply != null) ...[ + if (quote != null) ...[ _CapIntrinsicWidth( cap: maxBubbleWidth * _replyWidthShare, - child: _buildReplyQuote( - context, - cs, - textColor, - reply, - maxBubbleWidth, - ), + child: quote, ), const SizedBox(height: 4), ], @@ -1652,7 +1681,7 @@ class MessageBubble extends StatelessWidget { ), child: Align( child: Row( - mainAxisAlignment: isMe + mainAxisAlignment: _outgoing ? MainAxisAlignment.end : MainAxisAlignment.start, spacing: 8, @@ -1663,7 +1692,7 @@ class MessageBubble extends StatelessWidget { else if (showAvatarSlot && chatType == "CHAT") const SizedBox(width: _groupAvatarSize), Column( - crossAxisAlignment: isMe + crossAxisAlignment: _outgoing ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: [ @@ -1685,7 +1714,7 @@ class MessageBubble extends StatelessWidget { Widget _buildCommentsFooter(BuildContext context, ColorScheme cs) { final label = commentsLabel ?? AppLocalizations.of(context)!.commentsTitle; - final accent = isMe ? cs.onPrimaryContainer : cs.primary; + final accent = _outgoing ? cs.onPrimaryContainer : cs.primary; return Material( color: Colors.transparent, child: InkWell( @@ -1871,7 +1900,7 @@ class MessageBubble extends StatelessWidget { case 'LINK': final url = button.url; if (url != null && url.isNotEmpty) { - await openExternalUrl(context, url); + await openMessageLink(context, url, shownText: button.text); } return; case 'OPEN_APP': @@ -1904,7 +1933,7 @@ class MessageBubble extends StatelessWidget { if (!context.mounted) return; final url = answer?['url']?.toString(); if (url != null && url.isNotEmpty) { - await openExternalUrl(context, url); + await openMessageLink(context, url); return; } final text = answer?['text']?.toString(); @@ -2110,8 +2139,6 @@ class MessageBubble extends StatelessWidget { } Widget _buildJumboAnimojiMeta(BubbleContext ctx) { - final status = ctx.overrideStatus ?? ctx.message.status; - final statusVisual = messageStatusVisual(status, dimColor: Colors.white); return Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), decoration: BoxDecoration( @@ -2130,12 +2157,9 @@ class MessageBubble extends StatelessWidget { fontWeight: FontWeight.w500, ), ), - if (ctx.isMe) ...[ + if (ctx.showsStatus) ...[ const SizedBox(width: 3), - if (isSendingStatus(status)) - SendingClockIcon(color: statusVisual.color, size: 13) - else - Icon(statusVisual.icon, size: 13, color: statusVisual.color), + ctx.statusIcon(color: Colors.white, size: 13), ], if (ctx.message.deleted) ...[ const SizedBox(width: 3), @@ -2349,9 +2373,9 @@ class MessageBubble extends StatelessWidget { Icon(Symbols.lock, size: 11, weight: 700, fill: 1, color: ctx.dim), const SizedBox(width: 3), ], - ...ctx.metaMarks(ctx.dim), + ...ctx.metaMarks(ctx.dim, fontSize: 10), Text(ctx.timeLabel, style: TextStyle(color: ctx.dim, fontSize: 10)), - if (isMe) ...[const SizedBox(width: 4), ctx.statusIcon()], + if (ctx.showsStatus) ...[const SizedBox(width: 4), ctx.statusIcon()], if (message.deleted) ...[const SizedBox(width: 4), ctx.deletedIcon()], ], ); @@ -2781,7 +2805,9 @@ class MessageBubble extends StatelessWidget { duration: duration, url: url, textColor: ctx.text, - isMe: isMe, + isMe: ctx.isMe, + showsStatus: ctx.showsStatus, + views: ctx.views, deleted: message.deleted, status: overrideStatus ?? message.status, otherReadTime: otherReadTime, diff --git a/lib/frontend/widgets/paste_media_toolbar.dart b/lib/frontend/widgets/paste_media_toolbar.dart deleted file mode 100644 index c26f2d4f..00000000 --- a/lib/frontend/widgets/paste_media_toolbar.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; - -import 'package:komet/core/media/clipboard/clipboard_media.dart'; - -class PasteMediaToolbar extends StatefulWidget { - const PasteMediaToolbar({ - super.key, - required this.anchors, - required this.buttonItems, - required this.pasteItem, - }); - - final TextSelectionToolbarAnchors anchors; - final List buttonItems; - final ContextMenuButtonItem pasteItem; - - @override - State createState() => _PasteMediaToolbarState(); -} - -class _PasteMediaToolbarState extends State { - bool _hasMedia = false; - - @override - void initState() { - super.initState(); - unawaited(_probeClipboard()); - } - - Future _probeClipboard() async { - final hasMedia = await ClipboardMedia.hasMedia(); - if (!mounted || !hasMedia) return; - setState(() => _hasMedia = true); - } - - @override - Widget build(BuildContext context) { - return AdaptiveTextSelectionToolbar.buttonItems( - anchors: widget.anchors, - buttonItems: _hasMedia - ? widget.buttonItems - : widget.buttonItems - .where((item) => item != widget.pasteItem) - .toList(growable: false), - ); - } -} diff --git a/lib/frontend/widgets/photo_viewer.dart b/lib/frontend/widgets/photo_viewer.dart index f7927dcd..19aaf838 100644 --- a/lib/frontend/widgets/photo_viewer.dart +++ b/lib/frontend/widgets/photo_viewer.dart @@ -13,6 +13,8 @@ import '../../backend/modules/messages.dart'; import '../../backend/modules/shared_content.dart'; import '../../core/cache/info_cache.dart'; import '../../core/config/app_frost.dart'; +import '../../core/config/app_motion.dart'; +import '../../core/media/preview_image.dart'; import '../../core/utils/download_history.dart'; import '../../core/utils/format.dart'; import '../../core/utils/image_format.dart'; @@ -82,6 +84,7 @@ class PhotoViewerRoute extends PageRouteBuilder { PhotoViewerRoute({required WidgetBuilder builder}) : super( opaque: false, + allowSnapshotting: false, transitionDuration: const Duration(milliseconds: 220), reverseTransitionDuration: const Duration(milliseconds: 200), pageBuilder: (context, animation, secondaryAnimation) => @@ -1221,7 +1224,10 @@ class _PhotoViewerScreenState extends State child: Center( child: RotatedBox( quarterTurns: _quarterTurns[item.id] ?? 0, - child: _buildImage(item.photo!), + child: _ViewerPhoto( + photo: item.photo!, + preview: isHero ? widget.hero?.image.value : null, + ), ), ), ), @@ -1511,34 +1517,145 @@ class _PhotoViewerScreenState extends State : l10n.photoViewerSentOn(sender, formatDateWords(l10n, sentAt), time); } - Widget _buildImage(PhotoAttachment photo) { - final localPath = photo.localPath; +} + +class _ViewerPhoto extends StatelessWidget { + const _ViewerPhoto({required this.photo, this.preview, this.local = true}); + + final PhotoAttachment photo; + final ImageProvider? preview; + final bool local; + + @override + Widget build(BuildContext context) { + final placeholder = preview ?? dataUriImage(photo, photo.previewData); + final localPath = local ? photo.localPath : null; if (localPath != null) { - return Image.file( - File(localPath), - fit: BoxFit.contain, - errorBuilder: (_, _, _) => _buildRemoteImage(photo), + return _ProgressivePhoto( + image: FileImage(File(localPath)), + placeholder: placeholder, + fallback: _ViewerPhoto(photo: photo, preview: preview, local: false), ); } - return _buildRemoteImage(photo); + final url = photo.baseUrl ?? ''; + if (url.isEmpty) return const _BrokenPhoto(); + return _ProgressivePhoto( + image: CachedNetworkImageProvider(url), + placeholder: placeholder, + fallback: const _BrokenPhoto(), + ); } +} - Widget _buildRemoteImage(PhotoAttachment photo) { - final url = photo.baseUrl ?? ''; - if (url.isEmpty) return _broken(); +class _ProgressivePhoto extends StatefulWidget { + const _ProgressivePhoto({ + required this.image, + required this.placeholder, + required this.fallback, + }); - return CachedNetworkImage( - imageUrl: url, - fit: BoxFit.contain, - fadeInDuration: const Duration(milliseconds: 120), - placeholder: (_, _) => - const Center(child: SmallSpinner(size: 36, color: Colors.white)), - errorWidget: (_, _, _) => _broken(), + final ImageProvider image; + final ImageProvider? placeholder; + final Widget fallback; + + @override + State<_ProgressivePhoto> createState() => _ProgressivePhotoState(); +} + +class _ProgressivePhotoState extends State<_ProgressivePhoto> { + static const Duration _reveal = Duration(milliseconds: 160); + + bool _revealed = false; + + @override + void didUpdateWidget(_ProgressivePhoto oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.image != widget.image) _revealed = false; + } + + @override + Widget build(BuildContext context) { + return SizedBox.expand( + child: Image( + image: widget.image, + fit: BoxFit.contain, + gaplessPlayback: true, + errorBuilder: (_, _, _) => widget.fallback, + frameBuilder: (context, child, frame, synchronous) { + if (synchronous || _revealed) return child; + final loaded = frame != null; + final placeholder = widget.placeholder; + return Stack( + fit: StackFit.expand, + children: [ + if (placeholder != null) + Image( + image: placeholder, + fit: BoxFit.contain, + gaplessPlayback: true, + ), + AnimatedOpacity( + opacity: loaded ? 1 : 0, + duration: AppMotion.of(_reveal), + curve: Curves.easeOut, + onEnd: () { + if (loaded && mounted) setState(() => _revealed = true); + }, + child: child, + ), + if (!loaded) const _PendingSpinner(), + ], + ); + }, + ), ); } +} + +class _PendingSpinner extends StatefulWidget { + const _PendingSpinner(); + + @override + State<_PendingSpinner> createState() => _PendingSpinnerState(); +} + +class _PendingSpinnerState extends State<_PendingSpinner> { + static const Duration _delay = Duration(milliseconds: 500); + + late final Timer _timer; + bool _visible = false; + + @override + void initState() { + super.initState(); + _timer = Timer(_delay, () => setState(() => _visible = true)); + } - Widget _broken() => - const Icon(Symbols.broken_image, color: Colors.white54, size: 64); + @override + void dispose() { + _timer.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Center( + child: AnimatedOpacity( + opacity: _visible ? 1 : 0, + duration: AppMotion.of(const Duration(milliseconds: 200)), + child: const SmallSpinner(size: 36, color: Colors.white), + ), + ); + } +} + +class _BrokenPhoto extends StatelessWidget { + const _BrokenPhoto(); + + @override + Widget build(BuildContext context) => const Center( + child: Icon(Symbols.broken_image, color: Colors.white54, size: 64), + ); } class _VideoPlaybackSession extends ChangeNotifier { diff --git a/lib/frontend/widgets/reply_preview.dart b/lib/frontend/widgets/reply_preview.dart index 8fe5e6b7..3283c78b 100644 --- a/lib/frontend/widgets/reply_preview.dart +++ b/lib/frontend/widgets/reply_preview.dart @@ -147,6 +147,7 @@ class ReplyPreview { AttachmentType.call => Symbols.call, AttachmentType.share => Symbols.link, AttachmentType.forward => Symbols.forward, + AttachmentType.storyReply => Symbols.history_toggle_off, AttachmentType.unknown => Symbols.attach_file, AttachmentType.control || AttachmentType.inlineKeyboard => null, }; diff --git a/lib/frontend/widgets/seasonal_snow.dart b/lib/frontend/widgets/seasonal_snow.dart new file mode 100644 index 00000000..d14409b4 --- /dev/null +++ b/lib/frontend/widgets/seasonal_snow.dart @@ -0,0 +1,226 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart' show ValueListenable; +import 'package:flutter/material.dart'; + +import '../../core/config/komet_settings.dart'; + +bool isSeasonalSnowDate(DateTime date) => + (date.month == DateTime.december && date.day >= 1) || + (date.month == DateTime.january && date.day <= 3); + +/// Decorative snow shown automatically from December 1 through January 3. +/// [KometSettings.debugSnow] can force it on outside that period. +class SeasonalSnowLayer extends StatefulWidget { + const SeasonalSnowLayer({ + super.key, + this.flakeCount = 24, + this.seed = 2027, + this.opacity = 1, + }); + + final int flakeCount; + final int seed; + final double opacity; + + @override + State createState() => _SeasonalSnowLayerState(); +} + +class _SeasonalSnowLayerState extends State + with WidgetsBindingObserver { + static const _targetFps = 24; + static const _frameInterval = Duration( + microseconds: Duration.microsecondsPerSecond ~/ _targetFps, + ); + + final ValueNotifier _elapsedSeconds = ValueNotifier(0); + final Stopwatch _clock = Stopwatch(); + late List<_Snowflake> _flakes; + Timer? _frameTimer; + Timer? _dateTimer; + bool _enabled = false; + bool _tickerMode = true; + bool _appActive = true; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _flakes = _makeFlakes(); + KometSettings.debugSnow.addListener(_refreshEnabled); + _refreshEnabled(notify: false); + _scheduleDateRefresh(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final tickerMode = TickerMode.valuesOf(context).enabled; + if (_tickerMode == tickerMode) return; + _tickerMode = tickerMode; + _syncAnimation(); + } + + @override + void didUpdateWidget(SeasonalSnowLayer oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.seed != widget.seed || + oldWidget.flakeCount != widget.flakeCount) { + _flakes = _makeFlakes(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + final active = state == AppLifecycleState.resumed; + if (_appActive == active) return; + _appActive = active; + _syncAnimation(); + } + + List<_Snowflake> _makeFlakes() { + final random = math.Random(widget.seed); + return List.generate( + widget.flakeCount, + (_) => _Snowflake( + x: random.nextDouble(), + y: random.nextDouble(), + radius: 1.0 + random.nextDouble() * 1.8, + speed: 0.018 + random.nextDouble() * 0.014, + drift: 0.01 + random.nextDouble() * 0.03, + swaySpeed: 0.28 + random.nextDouble() * 0.3, + phase: random.nextDouble() * math.pi * 2, + alpha: 0.42 + random.nextDouble() * 0.38, + ), + growable: false, + ); + } + + void _refreshEnabled({bool notify = true}) { + final enabled = + KometSettings.debugSnow.value || isSeasonalSnowDate(DateTime.now()); + if (_enabled == enabled) return; + _enabled = enabled; + _syncAnimation(); + if (notify && mounted) setState(() {}); + } + + void _syncAnimation() { + final shouldRun = _enabled && _tickerMode && _appActive; + if (shouldRun) { + if (_frameTimer != null) return; + _clock.start(); + _frameTimer = Timer.periodic(_frameInterval, (_) { + _elapsedSeconds.value = _clock.elapsedMilliseconds / 1000; + }); + return; + } + _frameTimer?.cancel(); + _frameTimer = null; + _clock.stop(); + if (!_enabled) { + _clock.reset(); + _elapsedSeconds.value = 0; + } + } + + void _scheduleDateRefresh() { + _dateTimer?.cancel(); + final now = DateTime.now(); + final nextDay = DateTime(now.year, now.month, now.day + 1); + _dateTimer = Timer( + nextDay.difference(now) + const Duration(seconds: 1), + () { + _refreshEnabled(); + _scheduleDateRefresh(); + }, + ); + } + + @override + void dispose() { + _dateTimer?.cancel(); + _frameTimer?.cancel(); + KometSettings.debugSnow.removeListener(_refreshEnabled); + WidgetsBinding.instance.removeObserver(this); + _elapsedSeconds.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (!_enabled || widget.flakeCount <= 0) return const SizedBox.shrink(); + return IgnorePointer( + child: ExcludeSemantics( + child: Opacity( + opacity: widget.opacity.clamp(0.0, 1.0), + child: RepaintBoundary( + child: SizedBox.expand( + child: CustomPaint( + painter: _SnowPainter( + elapsedSeconds: _elapsedSeconds, + flakes: _flakes, + ), + ), + ), + ), + ), + ), + ); + } +} + +class _Snowflake { + const _Snowflake({ + required this.x, + required this.y, + required this.radius, + required this.speed, + required this.drift, + required this.swaySpeed, + required this.phase, + required this.alpha, + }); + + final double x; + final double y; + final double radius; + final double speed; + final double drift; + final double swaySpeed; + final double phase; + final double alpha; +} + +class _SnowPainter extends CustomPainter { + _SnowPainter({required this.elapsedSeconds, required this.flakes}) + : super(repaint: elapsedSeconds); + + final ValueListenable elapsedSeconds; + final List<_Snowflake> flakes; + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + final elapsed = elapsedSeconds.value; + final shadow = Paint(); + final snow = Paint(); + + for (final flake in flakes) { + final travel = (flake.y + elapsed * flake.speed) % 1.0; + final wave = math.sin(elapsed * flake.swaySpeed + flake.phase); + final x = ((flake.x + wave * flake.drift) % 1.0) * size.width; + final y = (travel * 1.1 - 0.06) * size.height; + shadow.color = Colors.black.withValues(alpha: flake.alpha * 0.14); + snow.color = Colors.white.withValues(alpha: flake.alpha); + canvas.drawCircle(Offset(x + 0.7, y + 1), flake.radius + 0.3, shadow); + canvas.drawCircle(Offset(x, y), flake.radius, snow); + } + } + + @override + bool shouldRepaint(covariant _SnowPainter oldDelegate) => + oldDelegate.flakes != flakes; +} diff --git a/lib/frontend/widgets/selectable_message_text.dart b/lib/frontend/widgets/selectable_message_text.dart index 55d15871..73d11499 100644 --- a/lib/frontend/widgets/selectable_message_text.dart +++ b/lib/frontend/widgets/selectable_message_text.dart @@ -10,6 +10,7 @@ import 'package:flutter/services.dart'; import '../../core/utils/haptics.dart'; import '../../l10n/app_localizations.dart'; import 'custom_notification.dart'; +import 'selection_toolbar.dart'; void _collectParagraphs(RenderObject ro, List out) { if (ro is RenderParagraph) { @@ -521,7 +522,7 @@ class _SelectableMessageTextState extends State final rootOrigin = _rootBox?.localToGlobal(Offset.zero) ?? Offset.zero; final safeTop = media.padding.top + 8; final safeBottom = size.height - media.padding.bottom - 8; - const height = 48.0; + const height = SelectionToolbarStyle.height; const gap = 10.0; double top = rootOrigin.dy + first.top - gap - height; @@ -552,42 +553,21 @@ class _SelectableMessageTextState extends State } Widget _pill(BuildContext ctx) { - final cs = Theme.of(ctx).colorScheme; final l10n = AppLocalizations.of(ctx)!; - return Material( - color: cs.surfaceContainerHigh, - borderRadius: BorderRadius.circular(14), - elevation: 8, - shadowColor: Colors.black.withValues(alpha: 0.4), - clipBehavior: Clip.antiAlias, + return SelectionToolbarSurface( child: Row( mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - _toolbarButton(cs, l10n.msgActionsCopy, _copy), - Container( - width: 1, - height: 24, - color: cs.outlineVariant.withValues(alpha: 0.4), + SelectionToolbarTextButton( + label: l10n.msgActionsCopy, + onPressed: _copy, ), - _toolbarButton(cs, l10n.msgActionsSelectAll, _selectAll), - ], - ), - ); - } - - Widget _toolbarButton(ColorScheme cs, String label, VoidCallback onTap) { - return InkWell( - onTap: onTap, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 13), - child: Text( - label, - style: TextStyle( - color: cs.onSurface, - fontSize: 15, - fontWeight: FontWeight.w500, + SelectionToolbarTextButton( + label: l10n.msgActionsSelectAll, + onPressed: _selectAll, ), - ), + ], ), ); } diff --git a/lib/frontend/widgets/selection_toolbar.dart b/lib/frontend/widgets/selection_toolbar.dart new file mode 100644 index 00000000..f8380223 --- /dev/null +++ b/lib/frontend/widgets/selection_toolbar.dart @@ -0,0 +1,553 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/config/app_motion.dart'; + +class SelectionToolbarStyle { + static const double height = 44; + static const double radius = 14; + static const double screenMargin = 8; + static const double gapAbove = 8; + static const double gapBelow = + TextSelectionToolbar.kToolbarContentDistanceBelow; + static const double labelPadding = 12; + static const double iconCellWidth = 42; + static const double minIconCellWidth = 36; + static const double navCellWidth = 34; + static const double iconSize = 22; + static const double navIconSize = 20; + static const double enterScale = 0.9; + static const double pageShift = 0.2; + static const Duration enterDuration = Duration(milliseconds: 200); + static const Duration pageDuration = Duration(milliseconds: 240); + static const Duration stateDuration = Duration(milliseconds: 160); + + static TextStyle labelStyle(BuildContext context) { + final style = DefaultTextStyle.of(context).style.merge( + TextStyle( + color: Theme.of(context).colorScheme.onSurface, + fontSize: 14, + fontWeight: FontWeight.w500, + height: 1.2, + ), + ); + return MediaQuery.boldTextOf(context) + ? style.merge(const TextStyle(fontWeight: FontWeight.bold)) + : style; + } + + static double labelCellWidth(BuildContext context, String label) { + final painter = TextPainter( + text: TextSpan(text: label, style: labelStyle(context)), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final width = painter.width; + painter.dispose(); + return width.ceilToDouble() + 1 + labelPadding * 2; + } +} + +class SelectionToolbarFloor extends InheritedWidget { + const SelectionToolbarFloor({super.key, required super.child}); + + static double? topOf(BuildContext context) { + final floor = context + .getElementForInheritedWidgetOfExactType() + ?.renderObject; + if (floor is! RenderBox || !floor.attached || !floor.hasSize) return null; + return floor.localToGlobal(Offset.zero).dy; + } + + @override + bool updateShouldNotify(SelectionToolbarFloor oldWidget) => false; +} + +@immutable +class SelectionToolbarItem { + const SelectionToolbarItem({ + required this.label, + required this.onPressed, + this.icon, + this.tint, + this.selected, + }); + + final String label; + final VoidCallback onPressed; + final IconData? icon; + final Color? tint; + final bool? selected; +} + +class SelectionToolbarSurface extends StatelessWidget { + const SelectionToolbarSurface({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) { + return Material( + color: Theme.of(context).colorScheme.surfaceContainerHigh, + borderRadius: const BorderRadius.all( + Radius.circular(SelectionToolbarStyle.radius), + ), + elevation: 8, + shadowColor: Colors.black.withValues(alpha: 0.4), + clipBehavior: Clip.antiAlias, + child: SizedBox(height: SelectionToolbarStyle.height, child: child), + ); + } +} + +class SelectionToolbarTextButton extends StatelessWidget { + const SelectionToolbarTextButton({ + super.key, + required this.label, + required this.onPressed, + }); + + final String label; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onPressed, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: SelectionToolbarStyle.labelPadding, + ), + child: Center( + widthFactor: 1, + child: Text( + label, + maxLines: 1, + softWrap: false, + style: SelectionToolbarStyle.labelStyle(context), + ), + ), + ), + ); + } +} + +class SelectionToolbar extends StatefulWidget { + const SelectionToolbar({ + super.key, + required this.anchors, + required this.items, + this.depth = 0, + this.onBack, + this.floor, + }); + + final TextSelectionToolbarAnchors anchors; + final List items; + final int depth; + final VoidCallback? onBack; + final double? floor; + + @override + State createState() => _SelectionToolbarState(); +} + +class _SelectionToolbarState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _entrance = AnimationController( + vsync: this, + duration: AppMotion.of(SelectionToolbarStyle.enterDuration), + ); + late final CurvedAnimation _entranceCurve = CurvedAnimation( + parent: _entrance, + curve: Curves.easeOutCubic, + ); + late final Animation _entranceScale = _entranceCurve.drive( + Tween(begin: SelectionToolbarStyle.enterScale, end: 1), + ); + + int _page = 0; + bool _forward = true; + + @override + void initState() { + super.initState(); + _entrance.forward(); + } + + @override + void didUpdateWidget(SelectionToolbar oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.depth == widget.depth) return; + _forward = widget.depth > oldWidget.depth; + _page = 0; + } + + @override + void dispose() { + _entranceCurve.dispose(); + _entrance.dispose(); + super.dispose(); + } + + void _turn(int from, int to) { + setState(() { + _forward = to > from; + _page = to; + }); + } + + @override + Widget build(BuildContext context) { + if (widget.items.isEmpty && widget.onBack == null) { + return const SizedBox.shrink(); + } + final padding = MediaQuery.paddingOf(context); + final keyboard = MediaQuery.viewInsetsOf(context).bottom; + final screenHeight = MediaQuery.sizeOf(context).height; + final floor = widget.floor; + final covered = floor == null + ? padding.bottom + keyboard + : math.max(padding.bottom + keyboard, screenHeight - floor); + const margin = SelectionToolbarStyle.screenMargin; + final insets = EdgeInsets.fromLTRB( + padding.left + margin, + padding.top + margin, + padding.right + margin, + covered + margin, + ); + final anchorAbove = widget.anchors.primaryAnchor; + final anchorBelow = widget.anchors.secondaryAnchor ?? anchorAbove; + final placeAbove = _fitsAbove( + anchorAbove, + anchorBelow, + insets, + screenHeight, + ); + return CustomSingleChildLayout( + delegate: _SelectionToolbarLayout( + anchorAbove: anchorAbove, + anchorBelow: anchorBelow, + insets: insets, + placeAbove: placeAbove, + ), + child: FadeTransition( + opacity: _entranceCurve, + child: ScaleTransition( + scale: _entranceScale, + alignment: placeAbove ? Alignment.bottomCenter : Alignment.topCenter, + child: SelectionToolbarSurface( + child: LayoutBuilder( + builder: (context, constraints) => + _pages(context, constraints.maxWidth), + ), + ), + ), + ), + ); + } + + static bool _fitsAbove( + Offset anchorAbove, + Offset anchorBelow, + EdgeInsets insets, + double screenHeight, + ) { + const height = SelectionToolbarStyle.height; + final roomAbove = + anchorAbove.dy - SelectionToolbarStyle.gapAbove - insets.top; + if (roomAbove >= height) return true; + final roomBelow = + screenHeight - + insets.bottom - + anchorBelow.dy - + SelectionToolbarStyle.gapBelow; + if (roomBelow >= height) return false; + return roomAbove >= roomBelow; + } + + Widget _pages(BuildContext context, double maxWidth) { + final items = widget.items; + final layout = _ToolbarPagination.of( + [ + for (final item in items) + item.icon == null + ? SelectionToolbarStyle.labelCellWidth(context, item.label) + : null, + ], + maxWidth, + leadingBack: widget.onBack != null, + ); + final pages = layout.pages; + final page = math.min(_page, pages.length - 1); + final (start, end) = pages[page]; + final onBack = widget.onBack; + final localizations = MaterialLocalizations.of(context); + final contentKey = ValueKey((widget.depth, page)); + final duration = AppMotion.of(SelectionToolbarStyle.pageDuration); + + final row = Row( + key: contentKey, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (page > 0) + _ToolbarIconCell( + icon: Symbols.chevron_left, + label: localizations.backButtonTooltip, + width: SelectionToolbarStyle.navCellWidth, + size: SelectionToolbarStyle.navIconSize, + onPressed: () => _turn(page, page - 1), + ) + else if (onBack != null) + _ToolbarIconCell( + icon: Symbols.chevron_left, + label: localizations.backButtonTooltip, + width: SelectionToolbarStyle.navCellWidth, + size: SelectionToolbarStyle.navIconSize, + onPressed: onBack, + ), + for (final item in items.sublist(start, end)) + if (item.icon case final icon?) + _ToolbarIconCell( + icon: icon, + label: item.label, + width: layout.iconWidth, + tint: item.tint, + selected: item.selected, + onPressed: item.onPressed, + ) + else + SelectionToolbarTextButton( + label: item.label, + onPressed: item.onPressed, + ), + if (page < pages.length - 1) + _ToolbarIconCell( + icon: Symbols.chevron_right, + label: localizations.moreButtonTooltip, + width: SelectionToolbarStyle.navCellWidth, + size: SelectionToolbarStyle.navIconSize, + onPressed: () => _turn(page, page + 1), + ), + ], + ); + + return AnimatedSize( + duration: duration, + curve: Curves.easeOutCubic, + child: AnimatedSwitcher( + duration: duration, + layoutBuilder: _stackPages, + transitionBuilder: (child, animation) => + _slidePage(child, animation, incoming: child.key == contentKey), + child: row, + ), + ); + } + + Widget _slidePage( + Widget child, + Animation animation, { + required bool incoming, + }) { + final shift = incoming == _forward + ? SelectionToolbarStyle.pageShift + : -SelectionToolbarStyle.pageShift; + return FadeTransition( + opacity: animation.drive( + CurveTween(curve: incoming ? _fadeInInterval : _fadeOutInterval), + ), + child: SlideTransition( + position: animation.drive( + Tween(begin: Offset(shift, 0), end: Offset.zero).chain( + CurveTween( + curve: incoming ? Curves.easeOutCubic : Curves.easeInCubic, + ), + ), + ), + child: child, + ), + ); + } + + static const _fadeInInterval = Interval(0.3, 1, curve: Curves.easeOut); + static const _fadeOutInterval = Interval(0.7, 1, curve: Curves.easeIn); + + static Widget _stackPages(Widget? current, List previous) { + return Stack( + alignment: Alignment.center, + clipBehavior: Clip.none, + children: [ + for (final child in previous) + Positioned(top: 0, bottom: 0, child: child), + ?current, + ], + ); + } +} + +class _ToolbarPagination { + const _ToolbarPagination(this.pages, this.iconWidth); + + final List<(int, int)> pages; + final double iconWidth; + + factory _ToolbarPagination.of( + List labelWidths, + double maxWidth, { + required bool leadingBack, + }) { + const nav = SelectionToolbarStyle.navCellWidth; + const preferred = SelectionToolbarStyle.iconCellWidth; + final count = labelWidths.length; + final icons = labelWidths.where((width) => width == null).length; + final labels = labelWidths.fold(0.0, (sum, width) => sum + (width ?? 0)); + final room = maxWidth - (leadingBack ? nav : 0) - labels; + if (icons == 0 && room >= 0) { + return _ToolbarPagination([(0, count)], preferred); + } + if (icons > 0 && room / icons >= SelectionToolbarStyle.minIconCellWidth) { + final iconWidth = math.min(preferred, (room / icons).floorToDouble()); + return _ToolbarPagination([(0, count)], iconWidth); + } + + final widths = [for (final width in labelWidths) width ?? preferred]; + final pages = <(int, int)>[]; + var start = 0; + while (start < count) { + final leading = pages.isNotEmpty || leadingBack ? nav : 0.0; + final rest = widths.skip(start).fold(0.0, (sum, width) => sum + width); + if (leading + rest <= maxWidth) { + pages.add((start, count)); + break; + } + var used = leading + nav; + var end = start; + while (end < count && used + widths[end] <= maxWidth) { + used += widths[end]; + end++; + } + if (end == start) end++; + pages.add((start, end)); + start = end; + } + return _ToolbarPagination(pages.isEmpty ? [(0, 0)] : pages, preferred); + } +} + +class _ToolbarIconCell extends StatelessWidget { + const _ToolbarIconCell({ + required this.icon, + required this.label, + required this.width, + required this.onPressed, + this.size = SelectionToolbarStyle.iconSize, + this.tint, + this.selected, + }); + + final IconData icon; + final String label; + final double width; + final double size; + final Color? tint; + final bool? selected; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final active = selected ?? false; + final duration = AppMotion.of(SelectionToolbarStyle.stateDuration); + final color = active ? cs.primary : (tint ?? cs.onSurface); + return Semantics( + toggled: selected, + child: Tooltip( + message: label, + child: InkWell( + onTap: onPressed, + child: SizedBox( + width: width, + child: Center( + child: AnimatedContainer( + duration: duration, + curve: Curves.easeOutCubic, + width: math.max(0, width - 6), + height: 32, + decoration: BoxDecoration( + color: cs.primary.withValues(alpha: active ? 0.16 : 0), + borderRadius: const BorderRadius.all(Radius.circular(10)), + ), + child: TweenAnimationBuilder( + tween: ColorTween(end: color), + duration: duration, + builder: (context, value, _) => + Icon(icon, size: size, weight: 450, color: value), + ), + ), + ), + ), + ), + ), + ); + } +} + +class _SelectionToolbarLayout extends SingleChildLayoutDelegate { + const _SelectionToolbarLayout({ + required this.anchorAbove, + required this.anchorBelow, + required this.insets, + required this.placeAbove, + }); + + final Offset anchorAbove; + final Offset anchorBelow; + final EdgeInsets insets; + final bool placeAbove; + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + return BoxConstraints.loose( + Size( + math.max(0, constraints.maxWidth - insets.horizontal), + SelectionToolbarStyle.height, + ), + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + final anchor = placeAbove ? anchorAbove : anchorBelow; + final minLeft = insets.left; + final maxLeft = math.max( + minLeft, + size.width - insets.right - childSize.width, + ); + final minTop = insets.top; + final maxTop = math.max( + minTop, + size.height - insets.bottom - childSize.height, + ); + final top = placeAbove + ? anchorAbove.dy - SelectionToolbarStyle.gapAbove - childSize.height + : anchorBelow.dy + SelectionToolbarStyle.gapBelow; + return Offset( + (anchor.dx - childSize.width / 2).clamp(minLeft, maxLeft), + top.clamp(minTop, maxTop), + ); + } + + @override + bool shouldRelayout(_SelectionToolbarLayout oldDelegate) { + return oldDelegate.anchorAbove != anchorAbove || + oldDelegate.anchorBelow != anchorBelow || + oldDelegate.insets != insets || + oldDelegate.placeAbove != placeAbove; + } +} diff --git a/lib/frontend/widgets/sliding_pill_nav.dart b/lib/frontend/widgets/sliding_pill_nav.dart index f4d6e911..2e30cf3b 100644 --- a/lib/frontend/widgets/sliding_pill_nav.dart +++ b/lib/frontend/widgets/sliding_pill_nav.dart @@ -10,19 +10,37 @@ import '../../core/config/app_visual_style.dart'; import 'animated_lottie_icon.dart'; import 'glossy_pill.dart'; import 'liquid_glass.dart'; +import 'spotlight.dart'; class PillNavItem { final IconData icon; final String label; final bool longPressable; final String? animationAsset; + final String? spotlightId; const PillNavItem({ required this.icon, required this.label, this.longPressable = false, this.animationAsset, + this.spotlightId, }); + + Widget spotlit( + BorderRadius borderRadius, + VoidCallback onActivate, + Widget child, + ) { + final id = spotlightId; + if (id == null) return child; + return SpotlightTarget( + id: id, + borderRadius: borderRadius, + onActivate: onActivate, + child: child, + ); + } } class PillNavGeometry { @@ -133,18 +151,24 @@ class SlidingPillNav extends StatelessWidget { final base = liquid ? (translucent ? backgroundColor! : AppLiquidGlass.navTint(cs)) : (backgroundColor ?? - (frost ? AppFrost.glassTint(cs) : cs.surfaceContainerHigh)); + (frost ? AppFrost.controlTint(cs) : cs.surfaceContainerHigh)); final useGradient = glossy && gradient && !liquid; final frosted = frost && !liquid && base.a < 1; + final fill = BoxDecoration( + color: useGradient || liquid ? null : base, + gradient: useGradient ? GlossyDecor.fillGradient(base) : null, + ); - return Container( + final bar = Container( height: height, padding: const EdgeInsets.symmetric(horizontal: 2), decoration: BoxDecoration( - color: useGradient || liquid ? null : base, - gradient: useGradient ? GlossyDecor.fillGradient(base) : null, + color: frosted ? null : fill.color, + gradient: frosted ? null : fill.gradient, borderRadius: BorderRadius.circular(34), - border: glossy + border: frosted + ? Border.fromBorderSide(AppFrost.hairline(cs)) + : glossy ? GlossyDecor.rimBorder(base) : (borderColor != null ? Border.all(color: borderColor!, width: 0.5) @@ -184,22 +208,6 @@ class SlidingPillNav extends StatelessWidget { ), ), ), - if (frosted) - Positioned.fill( - child: IgnorePointer( - child: ClipRRect( - borderRadius: BorderRadius.circular(34), - child: BackdropFilter( - filter: ui.ImageFilter.blur( - sigmaX: AppFrost.sigma, - sigmaY: AppFrost.sigma, - ), - backdropGroupKey: backdropKey, - child: const SizedBox.expand(), - ), - ), - ), - ), if (useGradient) Positioned.fill( child: IgnorePointer( @@ -235,23 +243,27 @@ class SlidingPillNav extends StatelessWidget { duration: animationDuration, curve: Curves.easeOutCubic, width: _interpWidth(i, layout), - child: ClipRRect( - borderRadius: BorderRadius.circular(26), - child: _PillNavCell( - key: ValueKey('pill-nav-item-$i'), - item: items[i], - selected: i == visualSel, - cs: cs, - animationDuration: animationDuration, - iconSize: iconSize, - labelGap: labelGap, - iconsOnly: iconsOnly, - onTap: () => onTap(i), - onLongPress: - (onItemLongPress == null || - !items[i].longPressable) - ? null - : (pos) => onItemLongPress!(i, pos), + child: items[i].spotlit( + BorderRadius.circular(26), + () => onTap(i), + ClipRRect( + borderRadius: BorderRadius.circular(26), + child: _PillNavCell( + key: ValueKey('pill-nav-item-$i'), + item: items[i], + selected: i == visualSel, + cs: cs, + animationDuration: animationDuration, + iconSize: iconSize, + labelGap: labelGap, + iconsOnly: iconsOnly, + onTap: () => onTap(i), + onLongPress: + (onItemLongPress == null || + !items[i].longPressable) + ? null + : (pos) => onItemLongPress!(i, pos), + ), ), ), ); @@ -263,6 +275,27 @@ class SlidingPillNav extends StatelessWidget { }, ), ); + if (!frosted) return bar; + return Stack( + children: [ + Positioned.fill( + child: IgnorePointer( + child: ClipRRect( + borderRadius: BorderRadius.circular(34), + child: BackdropFilter( + filter: ui.ImageFilter.blur( + sigmaX: AppFrost.sigma, + sigmaY: AppFrost.sigma, + ), + backdropGroupKey: backdropKey, + child: DecoratedBox(decoration: fill), + ), + ), + ), + ), + bar, + ], + ); } } diff --git a/lib/frontend/widgets/spotlight.dart b/lib/frontend/widgets/spotlight.dart new file mode 100644 index 00000000..4d48e9f9 --- /dev/null +++ b/lib/frontend/widgets/spotlight.dart @@ -0,0 +1,373 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; + +import 'route_probe.dart'; + +abstract final class Spotlight { + static const Duration _pulse = Duration(milliseconds: 1400); + static const Duration _reveal = Duration(milliseconds: 420); + static const Duration _press = Duration(milliseconds: 650); + static const Duration _mountWait = Duration(milliseconds: 700); + static const Duration _probeWait = Duration(milliseconds: 90); + static const Duration _probeStep = Duration(milliseconds: 180); + static const Duration _settleLimit = Duration(milliseconds: 600); + static const int _probeLimit = 14; + static const int _steadyFrames = 2; + static const int _steadyLimit = 60; + + static final Map> _targets = {}; + static final Map>> _waiters = {}; + + static void _register(String id, SpotlightTargetState state) { + _targets.putIfAbsent(id, () => []).add(state); + final waiters = _waiters.remove(id); + if (waiters == null) return; + for (final waiter in waiters) { + if (!waiter.isCompleted) waiter.complete(); + } + } + + static void _unregister(String id, SpotlightTargetState state) { + final states = _targets[id]; + if (states == null) return; + states.remove(state); + if (states.isEmpty) _targets.remove(id); + } + + static SpotlightTargetState? _visible(String id) { + final states = _targets[id]; + if (states == null) return null; + for (final state in states.reversed) { + if (state.mounted && state._onCurrentRoute) return state; + } + return null; + } + + static Future _await( + String id, + Duration within, + ) async { + final visible = _visible(id); + if (visible != null) return visible; + final waiter = Completer(); + _waiters.putIfAbsent(id, () => []).add(waiter); + try { + await waiter.future.timeout(within); + } on TimeoutException { + final waiters = _waiters[id]; + waiters?.remove(waiter); + if (waiters != null && waiters.isEmpty) _waiters.remove(id); + } + return _visible(id); + } + + static Future find(String id) async { + var state = await _await(id, _mountWait); + if (state == null) { + final position = _scrollerFor(id); + for ( + var i = 0; + state == null && position != null && i < _probeLimit; + i++ + ) { + if (position.pixels >= position.maxScrollExtent) break; + await position.animateTo( + math.min( + position.pixels + position.viewportDimension * 0.8, + position.maxScrollExtent, + ), + duration: _probeStep, + curve: Curves.easeOut, + ); + state = await _await(id, _probeWait); + } + } + if (state == null) return null; + await state._settled(); + await state._steady(); + return state.mounted ? state : null; + } + + static Future reveal(String id) async { + final state = await find(id); + if (state == null) return null; + await state._reveal(); + return state.mounted ? state.context : null; + } + + static Future highlight(String id) async { + final state = await find(id); + if (state == null) return false; + await state._reveal(); + if (state.mounted) unawaited(state._pulse()); + return true; + } + + static Future tap(String id) async { + final state = await find(id); + if (state == null || state.widget.onActivate == null) return false; + await state._reveal(); + if (!state.mounted) return false; + return state._press(); + } + + static Future settle() async { + final binding = SchedulerBinding.instance; + Duration? start; + var quiet = 0; + while (quiet < 2) { + await binding.endOfFrame; + final now = binding.currentSystemFrameTimeStamp; + start ??= now; + if (now - start > _settleLimit) return; + quiet = binding.hasScheduledFrame ? 0 : quiet + 1; + } + } + + static String _screenOf(String id) { + final dot = id.indexOf('.'); + return dot < 0 ? id : id.substring(0, dot); + } + + static ScrollPosition? _scrollerFor(String id) { + final screen = _screenOf(id); + for (final MapEntry(key: other, value: states) in _targets.entries) { + if (_screenOf(other) != screen) continue; + for (final state in states) { + if (!state.mounted || !state._onCurrentRoute) continue; + final position = state._verticalScroller()?.position; + if (position != null && position.hasContentDimensions) return position; + } + } + return mainScrollPosition(); + } + + static ScrollPosition? mainScrollPosition() { + final binding = WidgetsBinding.instance; + final view = + binding.platformDispatcher.implicitView ?? + binding.platformDispatcher.views.firstOrNull; + if (view == null) return null; + final size = view.physicalSize / view.devicePixelRatio; + final result = HitTestResult(); + binding.hitTestInView( + result, + Offset(size.width / 2, size.height * 0.55), + view.viewId, + ); + for (final entry in result.path) { + final target = entry.target; + if (target is RenderViewportBase && target.axis == Axis.vertical) { + final offset = target.offset; + if (offset is ScrollPosition && offset.hasContentDimensions) { + return offset; + } + } + } + return null; + } +} + +class SpotlightTarget extends StatefulWidget { + const SpotlightTarget({ + super.key, + required this.id, + this.borderRadius = const BorderRadius.all(Radius.circular(16)), + this.onActivate, + required this.child, + }); + + final String id; + final BorderRadius borderRadius; + final VoidCallback? onActivate; + final Widget child; + + @override + State createState() => SpotlightTargetState(); +} + +class SpotlightTargetState extends State + with SingleTickerProviderStateMixin { + AnimationController? _controller; + ModalRoute? _route; + bool _lit = false; + + bool get _onCurrentRoute => _route?.isCurrent ?? true; + + AnimationController get _pulseController => _controller ??= + AnimationController(vsync: this, duration: Spotlight._pulse); + + @override + void initState() { + super.initState(); + Spotlight._register(widget.id, this); + } + + @override + void didUpdateWidget(SpotlightTarget oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.id == widget.id) return; + Spotlight._unregister(oldWidget.id, this); + Spotlight._register(widget.id, this); + } + + @override + void dispose() { + Spotlight._unregister(widget.id, this); + _controller?.dispose(); + super.dispose(); + } + + ScrollableState? _verticalScroller() { + var scrollable = context.findAncestorStateOfType(); + while (scrollable != null && + axisDirectionToAxis(scrollable.axisDirection) != Axis.vertical) { + scrollable = scrollable.context + .findAncestorStateOfType(); + } + return scrollable; + } + + Rect? _globalRect() { + final box = context.findRenderObject(); + if (box is! RenderBox || !box.attached || !box.hasSize) return null; + return box.localToGlobal(Offset.zero) & box.size; + } + + Future _settled() async { + final animation = _route?.animation; + if (animation == null || animation.isCompleted) return; + final done = Completer(); + void listener(AnimationStatus status) { + if (status.isCompleted && !done.isCompleted) done.complete(); + } + + animation.addStatusListener(listener); + await done.future.timeout(const Duration(seconds: 1), onTimeout: () {}); + animation.removeStatusListener(listener); + } + + Future _steady() async { + Rect? last; + var still = 0; + for ( + var frame = 0; + frame < Spotlight._steadyLimit && still < Spotlight._steadyFrames; + frame++ + ) { + await SchedulerBinding.instance.endOfFrame; + if (!mounted) return; + final rect = _globalRect(); + still = rect != null && rect == last ? still + 1 : 0; + last = rect; + } + } + + Future _reveal() async { + if (!mounted) return; + final still = MediaQuery.disableAnimationsOf(context); + await Scrollable.ensureVisible( + context, + alignment: 0.35, + duration: still ? Duration.zero : Spotlight._reveal, + curve: Curves.easeOutCubic, + ); + } + + Future _pulse() async { + setState(() => _lit = true); + try { + await _pulseController.forward(from: 0).orCancel; + } on TickerCanceled { + return; + } + if (mounted) setState(() => _lit = false); + } + + Future _press() async { + setState(() => _lit = true); + try { + await _pulseController + .animateTo(0.5, duration: Spotlight._press) + .orCancel; + } on TickerCanceled { + return false; + } + if (!mounted) return false; + _pulseController.value = 0; + setState(() => _lit = false); + widget.onActivate?.call(); + return true; + } + + @override + Widget build(BuildContext context) { + final controller = _controller; + return RouteProbe( + onRoute: (route) => _route = route, + child: CustomPaint( + foregroundPainter: _lit && controller != null + ? _PulsePainter( + progress: controller, + color: Theme.of(context).colorScheme.primary, + borderRadius: widget.borderRadius, + steady: MediaQuery.disableAnimationsOf(context), + ) + : null, + child: widget.child, + ), + ); + } +} + +class _PulsePainter extends CustomPainter { + _PulsePainter({ + required this.progress, + required this.color, + required this.borderRadius, + required this.steady, + }) : super(repaint: progress); + + static const int _pulses = 2; + + final Animation progress; + final Color color; + final BorderRadius borderRadius; + final bool steady; + + double get _strength { + final t = progress.value; + if (t <= 0 || t >= 1) return 0; + if (steady) return 1; + return math.sin((t * _pulses % 1) * math.pi); + } + + @override + void paint(Canvas canvas, Size size) { + final strength = _strength; + if (strength <= 0) return; + final rect = borderRadius.toRRect(Offset.zero & size); + canvas.drawRRect( + rect, + Paint()..color = color.withValues(alpha: 0.16 * strength), + ); + canvas.drawRRect( + rect.deflate(1), + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..color = color.withValues(alpha: 0.85 * strength), + ); + } + + @override + bool shouldRepaint(_PulsePainter oldDelegate) => + oldDelegate.color != color || + oldDelegate.borderRadius != borderRadius || + oldDelegate.steady != steady || + !identical(oldDelegate.progress, progress); +} diff --git a/lib/frontend/widgets/story_reply_quote.dart b/lib/frontend/widgets/story_reply_quote.dart new file mode 100644 index 00000000..f8140254 --- /dev/null +++ b/lib/frontend/widgets/story_reply_quote.dart @@ -0,0 +1,137 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../backend/modules/messages.dart' show ContactCache; +import '../../l10n/app_localizations.dart'; +import '../../main.dart' show storiesModule; +import '../../models/attachment.dart'; +import '../../models/story.dart'; +import '../screens/stories/story_viewer_screen.dart'; +import 'custom_notification.dart'; + +Future openStoryReply( + BuildContext context, + StoryReplyAttachment reply, +) async { + final l10n = AppLocalizations.of(context)!; + final now = DateTime.now().millisecondsSinceEpoch; + if (reply.goneAt(now)) { + showCustomNotification(context, l10n.storyReplyUnavailable); + return; + } + final owner = StoryOwner.fromMap({ + 'ownerId': reply.ownerId, + 'type': reply.ownerType, + }); + final story = owner == null + ? null + : await storiesModule.storyById(owner, reply.storyId); + if (!context.mounted) return; + if (owner == null || story == null || story.expiredAt(now)) { + showCustomNotification(context, l10n.storyReplyUnavailable); + return; + } + await openStoryViewer( + context, + previews: [StoryPreview(owner: owner, totalCount: 1, readCount: 1)], + initialStories: { + owner.ownerId: [story], + }, + ); +} + +class StoryReplyQuote extends StatelessWidget { + const StoryReplyQuote({ + super.key, + required this.reply, + required this.myId, + required this.accent, + required this.textColor, + this.tappable = true, + }); + + final StoryReplyAttachment reply; + final int myId; + final Color accent; + final Color textColor; + final bool tappable; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final gone = reply.goneAt(DateTime.now().millisecondsSinceEpoch); + final owner = reply.ownerId == myId + ? l10n.callParticipantYou + : (ContactCache.get(reply.ownerId) ?? l10n.storyReplyLabel); + final preview = reply.previewUrl; + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: tappable ? () => openStoryReply(context, reply) : null, + child: Container( + padding: const EdgeInsets.fromLTRB(6, 4, 8, 4), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(6), + color: accent.withValues(alpha: 0.10), + border: Border(left: BorderSide(color: accent, width: 3)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: SizedBox( + width: 30, + height: 40, + child: gone || preview == null + ? ColoredBox( + color: accent.withValues(alpha: 0.18), + child: Icon( + Symbols.history_toggle_off, + size: 18, + color: accent, + ), + ) + : CachedNetworkImage( + imageUrl: preview, + fit: BoxFit.cover, + memCacheWidth: 90, + errorWidget: (_, _, _) => + ColoredBox(color: accent.withValues(alpha: 0.18)), + ), + ), + ), + const SizedBox(width: 8), + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + owner, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: accent, + fontSize: 12.5, + fontWeight: FontWeight.w600, + ), + ), + Text( + gone ? l10n.storyReplyGone : l10n.storyReplyLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: textColor.withValues(alpha: 0.85), + fontSize: 13, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/frontend/widgets/swipe_route.dart b/lib/frontend/widgets/swipe_route.dart index b930061f..97cb3b4a 100644 --- a/lib/frontend/widgets/swipe_route.dart +++ b/lib/frontend/widgets/swipe_route.dart @@ -3,6 +3,7 @@ import 'dart:ui'; import 'package:flutter/cupertino.dart'; +import '../../core/config/app_motion.dart'; import 'directional_drag_recognizer.dart'; import 'first_frame_clock.dart'; @@ -26,10 +27,12 @@ class SwipeRoute extends PageRoute with FirstFrameClock { String? get barrierLabel => null; @override - Duration get transitionDuration => const Duration(milliseconds: 400); + Duration get transitionDuration => + AppMotion.of(const Duration(milliseconds: 400)); @override - Duration get reverseTransitionDuration => const Duration(milliseconds: 400); + Duration get reverseTransitionDuration => + AppMotion.of(const Duration(milliseconds: 400)); @override bool canTransitionTo(TransitionRoute nextRoute) { diff --git a/lib/frontend/widgets/theme_wallpaper.dart b/lib/frontend/widgets/theme_wallpaper.dart new file mode 100644 index 00000000..cb4bb758 --- /dev/null +++ b/lib/frontend/widgets/theme_wallpaper.dart @@ -0,0 +1,293 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../../core/config/app_motion.dart'; +import '../../core/config/chat_wallpaper_themes.dart'; +import '../../core/storage/chat_wallpaper_store.dart'; + +void precacheWallpaperPattern(ChatWallpaper? wallpaper) { + final themeId = wallpaper?.themeId; + if (themeId != null) precacheWallpaperTheme(themeId); +} + +void precacheWallpaperTheme(String themeId) { + final asset = chatWallpaperThemeById(themeId)?.pattern?.asset; + if (asset == null) return; + unawaited(WallpaperPatternLayer.load(asset).then((_) {}, onError: (_) {})); +} + +class ThemeWallpaper extends StatelessWidget { + const ThemeWallpaper({ + super.key, + required this.theme, + this.patternScale = 1, + this.pinned = false, + }); + + final ChatWallpaperTheme theme; + final double patternScale; + final bool pinned; + + @override + Widget build(BuildContext context) { + final pattern = theme.pattern; + final background = DecoratedBox( + decoration: BoxDecoration(gradient: theme.gradient), + child: const SizedBox.expand(), + ); + final layer = pattern == null + ? background + : Stack( + fit: StackFit.expand, + children: [ + background, + WallpaperPatternLayer(pattern: pattern, scale: patternScale), + ], + ); + if (!pinned) return layer; + final screen = MediaQuery.sizeOf(context); + return ClipRect( + child: OverflowBox( + alignment: Alignment.topCenter, + minWidth: screen.width, + maxWidth: screen.width, + minHeight: screen.height, + maxHeight: screen.height, + child: RepaintBoundary(child: layer), + ), + ); + } +} + +class WallpaperPatternLayer extends StatefulWidget { + const WallpaperPatternLayer({ + super.key, + required this.pattern, + this.scale = 1, + }); + + final WallpaperPattern pattern; + final double scale; + + static final Map _tiles = {}; + static final Map> _loading = {}; + + static Future load(String asset) { + final ready = _tiles[asset]; + if (ready != null) return Future.value(ready); + return _loading.putIfAbsent(asset, () async { + try { + final info = await vg.loadPicture(SvgAssetLoader(asset), null); + _tiles[asset] = info; + return info; + } finally { + _loading.remove(asset); + } + }); + } + + @override + State createState() => _WallpaperPatternLayerState(); +} + +class _WallpaperPatternLayerState extends State { + PictureInfo? _tile; + ui.Image? _image; + String? _imageKey; + + @override + void initState() { + super.initState(); + _resolveTile(); + } + + @override + void didUpdateWidget(WallpaperPatternLayer oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.pattern.asset != widget.pattern.asset) _resolveTile(); + } + + @override + void dispose() { + _image?.dispose(); + super.dispose(); + } + + void _resolveTile() { + final asset = widget.pattern.asset; + _tile = WallpaperPatternLayer._tiles[asset]; + if (_tile != null) return; + WallpaperPatternLayer.load(asset).then((info) { + if (!mounted || widget.pattern.asset != asset) return; + setState(() => _tile = info); + }, onError: (Object _) {}); + } + + _PatternRaster _rasterFor(PictureInfo tile, Size size, double ratio) => + _PatternRaster( + tile: tile, + pattern: widget.pattern, + size: _PatternRaster.bucketOf(size), + devicePixelRatio: ratio, + scale: widget.scale, + ); + + ui.Image _imageFor(_PatternRaster raster) { + final image = _image; + if (image != null && _imageKey == raster.key) return image; + image?.dispose(); + _imageKey = raster.key; + return _image = raster.image(); + } + + @override + Widget build(BuildContext context) { + final tile = _tile; + final devicePixelRatio = MediaQuery.devicePixelRatioOf(context); + return AnimatedOpacity( + opacity: tile == null ? 0 : 1, + duration: AppMotion.of(const Duration(milliseconds: 220)), + child: tile == null + ? const SizedBox.expand() + : LayoutBuilder( + builder: (context, constraints) { + final size = constraints.biggest; + if (!size.isFinite || size.isEmpty) { + return const SizedBox.shrink(); + } + final raster = _rasterFor(tile, size, devicePixelRatio); + return RawImage( + image: _imageFor(raster), + width: size.width, + height: size.height, + scale: raster.ratio, + fit: BoxFit.none, + alignment: Alignment.topCenter, + ); + }, + ), + ); + } +} + +class _PatternRaster { + _PatternRaster({ + required this.tile, + required this.pattern, + required this.size, + required double devicePixelRatio, + required this.scale, + }) : ratio = math.min(devicePixelRatio, _maxSide / size.longestSide); + + static const double _maxSide = 3200; + static const double _bucket = 128; + static const int _budgetBytes = 24 * 1024 * 1024; + static const Alignment _glowCenter = Alignment(0.8, -0.72); + static final LinkedHashMap _cache = LinkedHashMap(); + static int _bytes = 0; + static _RasterMemoryObserver? _observer; + + static int _sizeOf(ui.Image image) => image.width * image.height * 4; + + static Size bucketOf(Size size) => Size( + (size.width / _bucket).ceil() * _bucket, + (size.height / _bucket).ceil() * _bucket, + ); + + static void clear() { + for (final image in _cache.values) { + image.dispose(); + } + _cache.clear(); + _bytes = 0; + } + + static void _remember(String key, ui.Image image) { + _observer ??= _RasterMemoryObserver()..attach(); + _cache[key] = image; + _bytes += _sizeOf(image); + while (_bytes > _budgetBytes && _cache.length > 1) { + final oldest = _cache.remove(_cache.keys.first)!; + _bytes -= _sizeOf(oldest); + oldest.dispose(); + } + } + + final PictureInfo tile; + final WallpaperPattern pattern; + final Size size; + final double scale; + final double ratio; + + int get _width => (size.width * ratio).ceil(); + int get _height => (size.height * ratio).ceil(); + + String get key => + '${pattern.asset}|$_width|$_height|$scale|' + '${pattern.inkStart.toARGB32()}|${pattern.inkEnd.toARGB32()}|' + '${pattern.glow.toARGB32()}'; + + ui.Image image() { + final cached = _cache.remove(key); + if (cached != null) { + _cache[key] = cached; + return cached.clone(); + } + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder)..scale(ratio); + _paint(canvas); + final picture = recorder.endRecording(); + final image = picture.toImageSync(_width, _height); + picture.dispose(); + _remember(key, image); + return image.clone(); + } + + void _paint(Canvas canvas) { + final rect = Offset.zero & size; + final ink = Paint() + ..shader = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [pattern.inkStart, pattern.inkEnd], + ).createShader(rect); + final glow = Paint() + ..shader = RadialGradient( + center: _glowCenter, + radius: 0.95, + colors: [pattern.glow, pattern.glow.withValues(alpha: 0)], + ).createShader(rect); + + canvas.saveLayer(rect, Paint()); + canvas.drawRect(rect, ink); + canvas.drawRect(rect, glow); + canvas.saveLayer(rect, Paint()..blendMode = BlendMode.dstIn); + final width = tile.size.width * scale; + final height = tile.size.height * scale; + final originX = (size.width - width) / 2; + final startX = originX - (originX / width).ceil() * width; + for (var y = 0.0; y < size.height; y += height) { + for (var x = startX; x < size.width; x += width) { + canvas.save(); + canvas.translate(x, y); + canvas.scale(scale); + canvas.drawPicture(tile.picture); + canvas.restore(); + } + } + canvas.restore(); + canvas.restore(); + } +} + +class _RasterMemoryObserver with WidgetsBindingObserver { + void attach() => WidgetsBinding.instance.addObserver(this); + + @override + void didHaveMemoryPressure() => _PatternRaster.clear(); +} diff --git a/lib/frontend/widgets/whats_new_runner.dart b/lib/frontend/widgets/whats_new_runner.dart new file mode 100644 index 00000000..effafb69 --- /dev/null +++ b/lib/frontend/widgets/whats_new_runner.dart @@ -0,0 +1,153 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../core/utils/link_opener.dart'; +import '../../core/utils/logger.dart'; +import '../../core/whats_new/whats_new_document.dart'; +import '../../main.dart' show KometApp; +import 'custom_notification.dart'; +import 'hint_bubble.dart'; +import 'link_confirm_sheet.dart'; +import 'max_link_nav.dart'; +import 'spotlight.dart'; + +class WhatsNewRunner { + WhatsNewRunner(this.document, {Future Function()? closeSheet}) + : _closeSheet = closeSheet; + + static const int _maxDepth = 6; + static const Duration _scroll = Duration(milliseconds: 420); + + final WhatsNewDocument document; + Future Function()? _closeSheet; + + BuildContext? get _context => KometApp.overlayContext; + + Future run(WhatsNewTarget target) async { + final scenario = target.scenario; + if (scenario != null) return _scenario(scenario, 0); + await _leaveSheet(); + await _open(target.link!); + } + + Future _scenario(String name, int depth) async { + final steps = document.scenarios[name]; + if (steps == null || depth > _maxDepth) return; + for (final step in steps) { + try { + await _step(step, depth); + } catch (e) { + logger.w('[whats-new] #$name, ${step.command.name}: $e'); + return; + } + } + } + + Future _step(WhatsNewStep step, int depth) async { + final args = step.args; + switch (step.command) { + case WhatsNewCommand.close: + await _leaveSheet(); + case WhatsNewCommand.tab: + await _leaveSheet(); + final context = _context; + if (context == null || !context.mounted) return; + await openRootTab(context, WhatsNewTab.values.byName(args.first).index); + await Spotlight.settle(); + case WhatsNewCommand.open: + await _leaveSheet(); + await _open(args.first); + case WhatsNewCommand.check: + await _leaveSheet(); + final context = _context; + if (context != null && context.mounted) { + await previewLinkCheck(context, args.first); + } + case WhatsNewCommand.back: + await _leaveSheet(); + final context = _context; + if (context != null && context.mounted) { + await Navigator.of(context).maybePop(); + await Spotlight.settle(); + } + case WhatsNewCommand.scroll: + await _leaveSheet(); + await _scrollTo(args.first); + case WhatsNewCommand.tap: + await _leaveSheet(); + if (await Spotlight.tap(args.first)) { + await Spotlight.settle(); + } else { + _missing(args.first); + } + case WhatsNewCommand.highlight: + await _leaveSheet(); + if (!await Spotlight.highlight(args.first)) _missing(args.first); + case WhatsNewCommand.hint: + await _leaveSheet(); + final anchor = await Spotlight.reveal(args.first); + if (anchor == null) { + _missing(args.first); + _notify(args[1]); + } else if (anchor.mounted) { + showHintBubble(anchor, args[1]); + } + case WhatsNewCommand.notify: + final target = args.length == 3 ? WhatsNewTarget.parse(args[2]) : null; + _notify( + args.first, + action: target == null + ? null + : (label: args[1], onTap: () => unawaited(run(target))), + ); + case WhatsNewCommand.wait: + await Future.delayed( + Duration(milliseconds: int.parse(args.first)), + ); + case WhatsNewCommand.run: + await _scenario(args.first.substring(1), depth + 1); + } + } + + Future _leaveSheet() async { + final close = _closeSheet; + if (close == null) return; + _closeSheet = null; + await close(); + } + + Future _open(String link) async { + final context = _context; + if (context == null) return; + unawaited( + openExternalUrl(context, link).catchError((Object error) { + logger.w('[whats-new] не открылось $link: $error'); + }), + ); + await WidgetsBinding.instance.endOfFrame; + await Spotlight.settle(); + } + + Future _scrollTo(String where) async { + if (where != 'top' && where != 'bottom') { + if (await Spotlight.reveal(where) == null) _missing(where); + return; + } + final position = Spotlight.mainScrollPosition(); + if (position == null) return; + await position.animateTo( + where == 'top' ? position.minScrollExtent : position.maxScrollExtent, + duration: _scroll, + curve: Curves.easeOutCubic, + ); + } + + void _notify(String text, {NotificationAction? action}) { + final context = _context; + if (context != null) showCustomNotification(context, text, action: action); + } + + void _missing(String id) => + logger.w('[whats-new] элемент «$id» не нашёлся на экране'); +} diff --git a/lib/frontend/widgets/whats_new_sheet.dart b/lib/frontend/widgets/whats_new_sheet.dart new file mode 100644 index 00000000..f8e11d32 --- /dev/null +++ b/lib/frontend/widgets/whats_new_sheet.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +import '../../core/config/app_fonts.dart'; +import '../../core/config/whats_new.dart'; +import '../../core/utils/haptics.dart'; +import '../../core/whats_new/whats_new_document.dart'; +import '../../l10n/app_localizations.dart'; +import 'sheet_helpers.dart'; +import 'whats_new_runner.dart'; + +Future showWhatsNewSheet(BuildContext context, String version) async { + final cs = Theme.of(context).colorScheme; + final document = await WhatsNew.document( + Localizations.localeOf(context).languageCode, + ); + if (!context.mounted) return; + await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: cs.surfaceContainerHigh, + shape: kSheetShape, + builder: (_) => _WhatsNewSheet(version: version, document: document), + ); +} + +class _WhatsNewSheet extends StatefulWidget { + const _WhatsNewSheet({required this.version, required this.document}); + + final String version; + final WhatsNewDocument document; + + @override + State<_WhatsNewSheet> createState() => _WhatsNewSheetState(); +} + +class _WhatsNewSheetState extends State<_WhatsNewSheet> { + static const double _rowInset = 12; + + late final WhatsNewRunner _runner = WhatsNewRunner( + widget.document, + closeSheet: _close, + ); + final Map _recognizers = {}; + ModalRoute? _route; + + @override + void initState() { + super.initState(); + for (final note in widget.document.notes) { + for (final span in note.spans.whereType()) { + _recognizers[span] = TapGestureRecognizer() + ..onTap = () => _run(span.target); + } + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _route = ModalRoute.of(context); + } + + @override + void dispose() { + for (final recognizer in _recognizers.values) { + recognizer.dispose(); + } + super.dispose(); + } + + void _run(WhatsNewTarget target) { + Haptics.tap(); + unawaited(_runner.run(target)); + } + + Future _close() async { + if (!mounted) return; + final animation = _route?.animation; + Navigator.of(context).pop(); + if (animation == null || animation.isDismissed) return; + final dismissed = Completer(); + void listener(AnimationStatus status) { + if (status.isDismissed && !dismissed.isCompleted) dismissed.complete(); + } + + animation.addStatusListener(listener); + await dismissed.future.timeout( + const Duration(milliseconds: 600), + onTimeout: () {}, + ); + animation.removeStatusListener(listener); + } + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final l10n = AppLocalizations.of(context)!; + final notes = widget.document.notes; + return SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.8, + ), + child: Padding( + padding: const EdgeInsets.fromLTRB( + 20 - _rowInset, + 0, + 20 - _rowInset, + 16, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Align(alignment: Alignment.center, child: SheetGrabber()), + const SizedBox(height: 6), + Padding( + padding: const EdgeInsets.symmetric(horizontal: _rowInset), + child: Text( + l10n.whatsNewSheetTitle(widget.version), + style: TextStyle( + color: cs.onSurface, + fontSize: 18, + fontWeight: FontWeight.w600, + fontFamily: displayFontOf(context), + ), + ), + ), + const SizedBox(height: 12), + Flexible( + child: SingleChildScrollView( + child: notes.isEmpty + ? Padding( + padding: const EdgeInsets.symmetric( + horizontal: _rowInset, + ), + child: Text( + l10n.whatsNewNoNotes, + style: _bodyStyle(cs), + ), + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final note in notes) _buildNote(cs, note), + ], + ), + ), + ), + const SizedBox(height: 18), + Padding( + padding: const EdgeInsets.symmetric(horizontal: _rowInset), + child: SheetButton( + label: l10n.whatsNewDone, + filled: true, + onTap: () => Navigator.of(context).pop(), + ), + ), + ], + ), + ), + ), + ); + } + + TextStyle _bodyStyle(ColorScheme cs) => + TextStyle(color: cs.onSurfaceVariant, fontSize: 14, height: 1.45); + + Widget _buildNote(ColorScheme cs, WhatsNewNote note) { + final text = Text.rich( + TextSpan( + style: _bodyStyle(cs), + children: [ + for (final span in note.spans) + switch (span) { + WhatsNewPlainSpan() => TextSpan(text: span.text), + WhatsNewLinkSpan() => TextSpan( + text: span.text, + recognizer: _recognizers[span], + style: TextStyle( + color: cs.primary, + fontWeight: FontWeight.w600, + ), + ), + }, + ], + ), + ); + + final target = note.target; + if (target == null) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: _rowInset, vertical: 4), + child: text, + ); + } + return Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Material( + color: cs.primary.withValues(alpha: 0.07), + borderRadius: BorderRadius.circular(14), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => _run(target), + child: Padding( + padding: const EdgeInsets.fromLTRB(_rowInset, 8, 6, 8), + child: Row( + children: [ + Expanded(child: text), + const SizedBox(width: 6), + Icon(Symbols.chevron_right, size: 20, color: cs.primary), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7404c8b5..f203b86c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -53,7 +53,7 @@ } } }, - "codeResendSms": "Resend code via SMS", + "codeResendSms": "Resend code", "codeError2faMissing": "Error: missing data for 2FA", "codeErrorInvalid": "Invalid code", "codeConfirmation2faWarning": "MAX may require 2FA on your account to sign in. If you didn't receive the code, set up 2FA from a client where you're already signed in.", @@ -243,6 +243,8 @@ "msgActionsReadByUnknownUser": "User", "msgActionsReport": "Report", "msgActionsDelete": "Delete", + "msgActionsRetry": "Send again", + "chatRetryFileMissing": "The file is no longer on this device", "msgActionsCopied": "Copied", "msgActionsLoadReasonsFailed": "Failed to load reasons", "msgActionsCurrentVersion": "current version", @@ -505,6 +507,7 @@ "callMute": "Mute", "callEndButton": "End", "callCameraUnavailable": "Camera unavailable: {error}", + "callMicrophonePermissionDenied": "Allow Komet to access the microphone in device settings to make calls", "callTooltipMicrophone": "Microphone", "callMicrophoneTitle": "Microphone", "callMicrophoneSystem": "System default", @@ -995,10 +998,8 @@ } } }, - "cloudStorageStartUploadHint": "Start an upload to see the progress bar", "cloudStorageEmptyTitle": "No cloud files yet...", "cloudStorageEmptySubtitle": "Add one?", - "cloudStorageUpload": "Upload", "cloudStorageFromFile": "From file", "cloudStorageById": "By ID", "cloudStorageFileIdLabel": "File ID", @@ -1017,6 +1018,9 @@ "cloudStorageSendError": "Send error", "cloudStorageSendByIdTitle": "Send by ID", "cloudStorageSend": "Send", + "cloudStorageDeleteFile": "Delete file", + "cloudStorageFileDeleted": "File deleted", + "cloudStorageDeleteFailed": "Couldn't delete the file", "cloudStorageAboutTooltip": "How storage works", "cloudStorageAboutTitle": "How cloud storage works", "cloudStorageAboutSubtitle": "There is no separate server: everything lives in your MAX account", @@ -1456,6 +1460,44 @@ "authLimitsSignupMoreTitle": "Other limits are possible", "authLimitsSignupMoreBody": "The server doesn't announce the full list — if something doesn't work, try again later.", "authLimitsConfirm": "Got it", + "authLimitsServerNote": "These limits come from the MAX server. Komet has no control over them.", + "storageTitle": "Storage", + "storageTotalCaption": "Komet takes up on this device", + "storageCategoryPhotos": "Photos and images", + "storageCategoryVideos": "Videos", + "storageCategoryFiles": "Files", + "storageCategoryVoice": "Voice messages", + "storageCategoryStickers": "Stickers", + "storageCategoryKept": "Deleted media", + "storageCategoryKeptHint": "Already erased on the server, can't be downloaded again", + "storageCategoryDatabase": "Messages and chats", + "storageCategoryDatabaseHint": "Your chat history, never cleared", + "storageScanning": "Calculating…", + "storageScanFailed": "Couldn't calculate the used space", + "storageEmpty": "The cache is empty", + "storageClear": "Clear {size}", + "@storageClear": { + "placeholders": { + "size": { + "type": "String" + } + } + }, + "storageNothingSelected": "Choose what to clear", + "storageCleared": "Freed {size}", + "@storageCleared": { + "placeholders": { + "size": { + "type": "String" + } + } + }, + "storageClearFailed": "Couldn't clear the cache", + "storageClearKeptMessage": "Deleted media can't be downloaded again: the server has already erased it. Clear it too?", + "storageClearKeptConfirm": "Clear", + "storageLimitTitle": "Maximum cache size", + "storageLimitUnlimited": "No limit", + "storageLimitHint": "When the cache outgrows the limit, Komet removes what you haven't opened for the longest. Deleted media and messages are never removed by the limit.", "e2eeTitle": "End-to-end encryption", "e2eeStatusNone": "Off", "e2eeStatusOffered": "Waiting for {name} to accept", @@ -1872,6 +1914,14 @@ "@chatScreenMembersCount": {"placeholders": {"count": {"type": "int"}}}, "chatScreenSubscribersCount": "{count, plural, =1{1 subscriber} other{{count} subscribers}}", "@chatScreenSubscribersCount": {"placeholders": {"count": {"type": "int"}}}, + "channelRecommendationsTitle": "Recommended channels", + "channelRecommendationsHide": "Hide recommendations", + "channelRecommendationsHidden": "Recommendations are hidden in this channel", + "channelRecommendationsHideEverywhere": "Hide everywhere", + "channelPostViews": "Views", + "kometSettingsHideRecommendations": "Hide recommended channels", + "kometSettingsHideRecommendationsSubtitle": "Don't show similar channels at the bottom of a channel", + "chatScreenFormatMenu": "Formatting", "chatScreenFormatHeading": "Heading", "chatScreenFormatBold": "Bold", "chatScreenFormatItalic": "Italic", @@ -1886,9 +1936,32 @@ "chatScreenFormatLinkHint": "https://example.com", "chatScreenFormatLinkInvalid": "That doesn't look like a link", "linkConfirmTitle": "Open this link?", - "linkConfirmBody": "The link text doesn't match its address, and you haven't visited this site before. Check the address above before you continue.", + "linkConfirmBody": "You haven't visited this site before. Check the address above before you continue.", "linkConfirmOpen": "Open", "linkConfirmCancel": "Cancel", + "linkConfirmSuspiciousTitle": "Suspicious link", + "linkConfirmOpenAnyway": "Open anyway", + "linkConfirmDontOpen": "Don't open", + "linkWarningTextMismatch": "The text shows {shown}, but it leads to {host}", + "@linkWarningTextMismatch": {"placeholders": {"shown": {"type": "String"}, "host": {"type": "String"}}}, + "linkWarningUserInfo": "Actually leads to {host}", + "@linkWarningUserInfo": {"placeholders": {"host": {"type": "String"}}}, + "linkWarningMixedScripts": "Mixed alphabets: {letters}", + "@linkWarningMixedScripts": {"placeholders": {"letters": {"type": "String"}}}, + "linkWarningLookalike": "Only looks Latin: the letters are {script}", + "@linkWarningLookalike": {"placeholders": {"script": {"type": "String"}}}, + "linkWarningInvisible": "The address hides invisible characters", + "linkWarningIpAddress": "Leads to an IP address, not a site", + "linkWarningScheme": "Opens through {scheme}:, not in a browser", + "@linkWarningScheme": {"placeholders": {"scheme": {"type": "String"}}}, + "linkWarningLetter": "“{letter}”", + "@linkWarningLetter": {"placeholders": {"letter": {"type": "String"}}}, + "linkWarningLetters": "{letters} from {script}", + "@linkWarningLetters": {"placeholders": {"letters": {"type": "String"}, "script": {"type": "String"}}}, + "linkScriptLatin": "Latin", + "linkScriptCyrillic": "Cyrillic", + "linkScriptGreek": "Greek", + "linkScriptArmenian": "Armenian", "chatScreenMessageTooLong": "The message is too long. Split it into several", "chatScreenEncryptionKeyMissing": "No encryption key is set", "chatScreenPluginFilesEncryptUnsupported": "Plugin files can't be encrypted yet", @@ -1931,6 +2004,21 @@ "chatWallpaperSheetTitle": "Wallpaper", "chatWallpaperSheetSampleIncoming": "How about a new wallpaper for this chat?", "chatWallpaperSheetSampleOutgoing": "Looks great 🔥", + "chatWallpaperSheetInherit": "Default", + "chatWallpaperSheetCurrent": "Current", + "chatWallpaperSheetCustomGradient": "Gradient", + "chatWallpaperSheetApply": "Apply", + "chatWallpaperPresetKomet": "Comet", + "chatWallpaperPresetGraphite": "Graphite", + "chatWallpaperPresetInk": "Ink", + "chatWallpaperPresetPine": "Pine", + "chatWallpaperPresetPlum": "Plum", + "chatWallpaperPresetUmber": "Umber", + "chatWallpaperPresetPaper": "Paper", + "chatWallpaperPresetFog": "Fog", + "chatWallpaperPresetSage": "Sage", + "chatWallpaperPresetSand": "Sand", + "chatWallpaperPresetPowder": "Powder", "chatWallpaperSheetNone": "No wallpaper", "chatWallpaperSheetYourPhoto": "Your photo", "chatWallpaperSheetFromGallery": "From gallery", @@ -1964,6 +2052,7 @@ "appearanceMessageActionsSubtitle": "How the menu appears when you long-press a message", "videoNoteBubbleTranscriptionFailed": "Couldn't transcribe", "webAppScreenCloseConfirm": "Close the mini app?", + "webAppUnsupportedPlatform": "Mini apps aren't available in the Linux version yet", "voiceRecordUnsupported": "Voice messages aren't available on this platform", "voiceRecordNoMicAccess": "No access to the microphone", "voiceRecordStartFailed": "Couldn't start recording", @@ -2087,6 +2176,22 @@ "codeConfirmationNewCodeSent": "We sent a new code", "codeConfirmationSmsNoToken": "SMS sign-in: the server didn't return a token", "codeConfirmationCodeExpired": "The code expired — we sent a new one", + "codeConfirmationIncomingCall": "We're calling your number. Enter the last 6 digits of the incoming number. If there's no call, check SMS and the “Verification codes” chat in MAX.", + "callOutDescription": "Call the number below from this number to confirm sign-in. Wait for the robot to answer and follow its prompts.", + "callOutWaitingNumber": "Getting a number to call…", + "callOutTapToCopy": "Tap to copy", + "callOutTimer": "Call within {time}", + "@callOutTimer": {"placeholders": {"time": {"type": "String"}}}, + "callOutExpired": "Time to call is up — refresh the number", + "callOutVerified": "Call received, signing in…", + "callOutDial": "Call {number}", + "@callOutDial": {"placeholders": {"number": {"type": "String"}}}, + "callOutDialPending": "Call", + "callOutRefresh": "Refresh number", + "callOutNewNumber": "We got a new number — call it instead", + "callOutRefreshFailed": "Couldn't refresh the number: {error}", + "@callOutRefreshFailed": {"placeholders": {"error": {"type": "String"}}}, + "callOutCommonError": "Couldn't sign in, please try again", "pollViewVoteFailed": "Couldn't vote", "pollViewLoading": "Loading poll…", "pollViewMultipleAnswers": "Multiple answers", @@ -2097,6 +2202,9 @@ "customizationChatBackground": "Chat background", "customizationAppIcon": "App icon", "customizationTitle": "Customization", + "chatFoldersAddTo": "Add to folder", + "chatFoldersUpdateFailed": "Couldn't update the folder “{title}”", + "@chatFoldersUpdateFailed": {"placeholders": {"title": {"type": "String"}}}, "folderActionNewFolder": "New folder", "folderActionDeleteConfirm": "Delete the folder “{title}”? The chats will stay where they are.", "foldersSettingsCreate": "Create folder", @@ -2302,6 +2410,7 @@ "kometSettingsArchiveOnPullSubtitle": "Hide the archive and show it when you pull the chat list down, after stories", "kometSettingsGhostModeSubtitle": "You don't appear online", "kometSettingsAntiReadSubtitle": "Read messages without marking them as read", + "kometSettingsAntiStoryViewSubtitle": "Watch stories without appearing among their viewers. The author still sees your reactions and replies", "kometSettingsSelfOnlineCheckSubtitle": "Checks every ~10 seconds when you were last online. Useful for testing ghost mode", "kometSettingsDebugHeader": "Debugging", "kometSettingsDebugLogsLabel": "Record debug logs", @@ -2633,18 +2742,6 @@ "pluginUpdateNewPermissions": "The update requests new permissions: {permissions}", "@pluginUpdateNewPermissions": {"placeholders": {"permissions": {"type": "String"}}}, "transcriptionNotRecognized": "Couldn't recognize the voice", - "chatWallpaperThemeOcean": "Ocean", - "chatWallpaperThemeSunset": "Sunset", - "chatWallpaperThemeLavender": "Lavender", - "chatWallpaperThemeMint": "Mint", - "chatWallpaperThemeGraphite": "Graphite", - "chatWallpaperThemeSky": "Sky", - "chatWallpaperThemePeach": "Peach", - "chatWallpaperThemeForest": "Forest", - "chatWallpaperThemeGrape": "Grape", - "chatWallpaperThemeNight": "Night", - "chatWallpaperThemeRose": "Rose", - "chatWallpaperThemeAmber": "Amber", "mediaSaveFileNotFound": "file not found", "mediaSaveNoGalleryAccess": "no access to the gallery", "mediaSaveNoStorageAccess": "no access to storage", @@ -2677,6 +2774,8 @@ "callMicMutedByAdmin": "An admin turned off your microphone", "callCameraMutedByAdmin": "An admin turned off your camera", "callScreenMutedByAdmin": "An admin stopped your screen sharing", + "callMicUnavailable": "No microphone access — others can't hear you", + "callMicSettings": "Settings", "callMediaLocked": "An admin has disabled this in the call", "callRecordingBy": "{name} is recording the call", "@callRecordingBy": {"placeholders": {"name": {"type": "String"}}}, @@ -2703,5 +2802,39 @@ "callParticipantsSearchHint": "Search participants", "callShareScreen": "Share screen", "callYouLoweredAllHands": "You lowered everyone's hands", - "callYouLoweredHand": "You lowered the participant's hand" + "callYouLoweredHand": "You lowered the participant's hand", + "whatsNewBannerTitle": "Komet updated to {version}", + "whatsNewBannerSubtitle": "Tap to see what's new", + "whatsNewSheetTitle": "What's new in {version}", + "whatsNewNoNotes": "Bug fixes and stability improvements.", + "whatsNewDone": "Got it", + "appearanceAnimationsTitle": "Animations", + "appearanceAnimationsSubtitle": "Transitions between screens and tabs. Turn off to open everything instantly", + "login2faRequiredTitle": "Set a password on the device you've signed in to MAX on", + "login2faRequiredSteps": "To do so, go to Settings → Security → Sign-in password", + "login2faRequiredThen": "Then you'll be able to sign in here", + "login2faRequiredNotKomet": "This is NOT a Komet error. MAX requires it from everyone.", + "login2faRequiredRetry": "Try signing in again", + "login2faRequiredNoAccess": "I can't access the account", + "login2faRequiredLinkFailed": "Couldn't open go.max.ru/reset-session", + "informerBannerServerNote": "This is an announcement from the MAX server. It isn't related to Komet.", + "storyReplyHint": "Reply", + "storyReplySent": "Message sent", + "storyReplyFailed": "Couldn't send the reply", + "storyReplyEncrypted": "This chat is encrypted, so story replies aren't available", + "storyLikeFailed": "Couldn't react to the story", + "storyReplyLabel": "Story", + "storyReplyGone": "A story was here", + "storyReplyUnavailable": "The story is no longer available", + "storyMenuProfile": "Go to profile", + "storyMenuHide": "Hide author's stories", + "storyMenuSave": "Save to gallery", + "storyMenuReport": "Report", + "storyHiddenNotice": "The author's stories are hidden", + "storyHideFailed": "Couldn't hide the stories", + "storyReplyOpenChat": "View", + "storyHiddenUndo": "Undo", + "storyMenuShow": "Show author's stories", + "storyShownNotice": "The author's stories are visible again", + "storyShowFailed": "Couldn't show the stories" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index ef97842d..32583768 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -371,7 +371,7 @@ abstract class AppLocalizations { /// No description provided for @codeResendSms. /// /// In en, this message translates to: - /// **'Resend code via SMS'** + /// **'Resend code'** String get codeResendSms; /// No description provided for @codeError2faMissing. @@ -1424,6 +1424,18 @@ abstract class AppLocalizations { /// **'Delete'** String get msgActionsDelete; + /// No description provided for @msgActionsRetry. + /// + /// In en, this message translates to: + /// **'Send again'** + String get msgActionsRetry; + + /// No description provided for @chatRetryFileMissing. + /// + /// In en, this message translates to: + /// **'The file is no longer on this device'** + String get chatRetryFileMissing; + /// No description provided for @msgActionsCopied. /// /// In en, this message translates to: @@ -2720,6 +2732,12 @@ abstract class AppLocalizations { /// **'Camera unavailable: {error}'** String callCameraUnavailable(Object error); + /// No description provided for @callMicrophonePermissionDenied. + /// + /// In en, this message translates to: + /// **'Allow Komet to access the microphone in device settings to make calls'** + String get callMicrophonePermissionDenied; + /// No description provided for @callTooltipMicrophone. /// /// In en, this message translates to: @@ -4712,12 +4730,6 @@ abstract class AppLocalizations { /// **'Uploading {percent}%'** String cloudStorageUploadingPercent(String percent); - /// No description provided for @cloudStorageStartUploadHint. - /// - /// In en, this message translates to: - /// **'Start an upload to see the progress bar'** - String get cloudStorageStartUploadHint; - /// No description provided for @cloudStorageEmptyTitle. /// /// In en, this message translates to: @@ -4730,12 +4742,6 @@ abstract class AppLocalizations { /// **'Add one?'** String get cloudStorageEmptySubtitle; - /// No description provided for @cloudStorageUpload. - /// - /// In en, this message translates to: - /// **'Upload'** - String get cloudStorageUpload; - /// No description provided for @cloudStorageFromFile. /// /// In en, this message translates to: @@ -4802,6 +4808,24 @@ abstract class AppLocalizations { /// **'Send'** String get cloudStorageSend; + /// No description provided for @cloudStorageDeleteFile. + /// + /// In en, this message translates to: + /// **'Delete file'** + String get cloudStorageDeleteFile; + + /// No description provided for @cloudStorageFileDeleted. + /// + /// In en, this message translates to: + /// **'File deleted'** + String get cloudStorageFileDeleted; + + /// No description provided for @cloudStorageDeleteFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t delete the file'** + String get cloudStorageDeleteFailed; + /// No description provided for @cloudStorageAboutTooltip. /// /// In en, this message translates to: @@ -6458,6 +6482,150 @@ abstract class AppLocalizations { /// **'Got it'** String get authLimitsConfirm; + /// No description provided for @authLimitsServerNote. + /// + /// In en, this message translates to: + /// **'These limits come from the MAX server. Komet has no control over them.'** + String get authLimitsServerNote; + + /// No description provided for @storageTitle. + /// + /// In en, this message translates to: + /// **'Storage'** + String get storageTitle; + + /// No description provided for @storageTotalCaption. + /// + /// In en, this message translates to: + /// **'Komet takes up on this device'** + String get storageTotalCaption; + + /// No description provided for @storageCategoryPhotos. + /// + /// In en, this message translates to: + /// **'Photos and images'** + String get storageCategoryPhotos; + + /// No description provided for @storageCategoryVideos. + /// + /// In en, this message translates to: + /// **'Videos'** + String get storageCategoryVideos; + + /// No description provided for @storageCategoryFiles. + /// + /// In en, this message translates to: + /// **'Files'** + String get storageCategoryFiles; + + /// No description provided for @storageCategoryVoice. + /// + /// In en, this message translates to: + /// **'Voice messages'** + String get storageCategoryVoice; + + /// No description provided for @storageCategoryStickers. + /// + /// In en, this message translates to: + /// **'Stickers'** + String get storageCategoryStickers; + + /// No description provided for @storageCategoryKept. + /// + /// In en, this message translates to: + /// **'Deleted media'** + String get storageCategoryKept; + + /// No description provided for @storageCategoryKeptHint. + /// + /// In en, this message translates to: + /// **'Already erased on the server, can\'t be downloaded again'** + String get storageCategoryKeptHint; + + /// No description provided for @storageCategoryDatabase. + /// + /// In en, this message translates to: + /// **'Messages and chats'** + String get storageCategoryDatabase; + + /// No description provided for @storageCategoryDatabaseHint. + /// + /// In en, this message translates to: + /// **'Your chat history, never cleared'** + String get storageCategoryDatabaseHint; + + /// No description provided for @storageScanning. + /// + /// In en, this message translates to: + /// **'Calculating…'** + String get storageScanning; + + /// No description provided for @storageScanFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t calculate the used space'** + String get storageScanFailed; + + /// No description provided for @storageEmpty. + /// + /// In en, this message translates to: + /// **'The cache is empty'** + String get storageEmpty; + + /// No description provided for @storageClear. + /// + /// In en, this message translates to: + /// **'Clear {size}'** + String storageClear(String size); + + /// No description provided for @storageNothingSelected. + /// + /// In en, this message translates to: + /// **'Choose what to clear'** + String get storageNothingSelected; + + /// No description provided for @storageCleared. + /// + /// In en, this message translates to: + /// **'Freed {size}'** + String storageCleared(String size); + + /// No description provided for @storageClearFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t clear the cache'** + String get storageClearFailed; + + /// No description provided for @storageClearKeptMessage. + /// + /// In en, this message translates to: + /// **'Deleted media can\'t be downloaded again: the server has already erased it. Clear it too?'** + String get storageClearKeptMessage; + + /// No description provided for @storageClearKeptConfirm. + /// + /// In en, this message translates to: + /// **'Clear'** + String get storageClearKeptConfirm; + + /// No description provided for @storageLimitTitle. + /// + /// In en, this message translates to: + /// **'Maximum cache size'** + String get storageLimitTitle; + + /// No description provided for @storageLimitUnlimited. + /// + /// In en, this message translates to: + /// **'No limit'** + String get storageLimitUnlimited; + + /// No description provided for @storageLimitHint. + /// + /// In en, this message translates to: + /// **'When the cache outgrows the limit, Komet removes what you haven\'t opened for the longest. Deleted media and messages are never removed by the limit.'** + String get storageLimitHint; + /// No description provided for @e2eeTitle. /// /// In en, this message translates to: @@ -8348,6 +8516,54 @@ abstract class AppLocalizations { /// **'{count, plural, =1{1 subscriber} other{{count} subscribers}}'** String chatScreenSubscribersCount(int count); + /// No description provided for @channelRecommendationsTitle. + /// + /// In en, this message translates to: + /// **'Recommended channels'** + String get channelRecommendationsTitle; + + /// No description provided for @channelRecommendationsHide. + /// + /// In en, this message translates to: + /// **'Hide recommendations'** + String get channelRecommendationsHide; + + /// No description provided for @channelRecommendationsHidden. + /// + /// In en, this message translates to: + /// **'Recommendations are hidden in this channel'** + String get channelRecommendationsHidden; + + /// No description provided for @channelRecommendationsHideEverywhere. + /// + /// In en, this message translates to: + /// **'Hide everywhere'** + String get channelRecommendationsHideEverywhere; + + /// No description provided for @channelPostViews. + /// + /// In en, this message translates to: + /// **'Views'** + String get channelPostViews; + + /// No description provided for @kometSettingsHideRecommendations. + /// + /// In en, this message translates to: + /// **'Hide recommended channels'** + String get kometSettingsHideRecommendations; + + /// No description provided for @kometSettingsHideRecommendationsSubtitle. + /// + /// In en, this message translates to: + /// **'Don\'t show similar channels at the bottom of a channel'** + String get kometSettingsHideRecommendationsSubtitle; + + /// No description provided for @chatScreenFormatMenu. + /// + /// In en, this message translates to: + /// **'Formatting'** + String get chatScreenFormatMenu; + /// No description provided for @chatScreenFormatHeading. /// /// In en, this message translates to: @@ -8435,7 +8651,7 @@ abstract class AppLocalizations { /// No description provided for @linkConfirmBody. /// /// In en, this message translates to: - /// **'The link text doesn\'t match its address, and you haven\'t visited this site before. Check the address above before you continue.'** + /// **'You haven\'t visited this site before. Check the address above before you continue.'** String get linkConfirmBody; /// No description provided for @linkConfirmOpen. @@ -8450,6 +8666,102 @@ abstract class AppLocalizations { /// **'Cancel'** String get linkConfirmCancel; + /// No description provided for @linkConfirmSuspiciousTitle. + /// + /// In en, this message translates to: + /// **'Suspicious link'** + String get linkConfirmSuspiciousTitle; + + /// No description provided for @linkConfirmOpenAnyway. + /// + /// In en, this message translates to: + /// **'Open anyway'** + String get linkConfirmOpenAnyway; + + /// No description provided for @linkConfirmDontOpen. + /// + /// In en, this message translates to: + /// **'Don\'t open'** + String get linkConfirmDontOpen; + + /// No description provided for @linkWarningTextMismatch. + /// + /// In en, this message translates to: + /// **'The text shows {shown}, but it leads to {host}'** + String linkWarningTextMismatch(String shown, String host); + + /// No description provided for @linkWarningUserInfo. + /// + /// In en, this message translates to: + /// **'Actually leads to {host}'** + String linkWarningUserInfo(String host); + + /// No description provided for @linkWarningMixedScripts. + /// + /// In en, this message translates to: + /// **'Mixed alphabets: {letters}'** + String linkWarningMixedScripts(String letters); + + /// No description provided for @linkWarningLookalike. + /// + /// In en, this message translates to: + /// **'Only looks Latin: the letters are {script}'** + String linkWarningLookalike(String script); + + /// No description provided for @linkWarningInvisible. + /// + /// In en, this message translates to: + /// **'The address hides invisible characters'** + String get linkWarningInvisible; + + /// No description provided for @linkWarningIpAddress. + /// + /// In en, this message translates to: + /// **'Leads to an IP address, not a site'** + String get linkWarningIpAddress; + + /// No description provided for @linkWarningScheme. + /// + /// In en, this message translates to: + /// **'Opens through {scheme}:, not in a browser'** + String linkWarningScheme(String scheme); + + /// No description provided for @linkWarningLetter. + /// + /// In en, this message translates to: + /// **'“{letter}”'** + String linkWarningLetter(String letter); + + /// No description provided for @linkWarningLetters. + /// + /// In en, this message translates to: + /// **'{letters} from {script}'** + String linkWarningLetters(String letters, String script); + + /// No description provided for @linkScriptLatin. + /// + /// In en, this message translates to: + /// **'Latin'** + String get linkScriptLatin; + + /// No description provided for @linkScriptCyrillic. + /// + /// In en, this message translates to: + /// **'Cyrillic'** + String get linkScriptCyrillic; + + /// No description provided for @linkScriptGreek. + /// + /// In en, this message translates to: + /// **'Greek'** + String get linkScriptGreek; + + /// No description provided for @linkScriptArmenian. + /// + /// In en, this message translates to: + /// **'Armenian'** + String get linkScriptArmenian; + /// No description provided for @chatScreenMessageTooLong. /// /// In en, this message translates to: @@ -8660,6 +8972,96 @@ abstract class AppLocalizations { /// **'Looks great 🔥'** String get chatWallpaperSheetSampleOutgoing; + /// No description provided for @chatWallpaperSheetInherit. + /// + /// In en, this message translates to: + /// **'Default'** + String get chatWallpaperSheetInherit; + + /// No description provided for @chatWallpaperSheetCurrent. + /// + /// In en, this message translates to: + /// **'Current'** + String get chatWallpaperSheetCurrent; + + /// No description provided for @chatWallpaperSheetCustomGradient. + /// + /// In en, this message translates to: + /// **'Gradient'** + String get chatWallpaperSheetCustomGradient; + + /// No description provided for @chatWallpaperSheetApply. + /// + /// In en, this message translates to: + /// **'Apply'** + String get chatWallpaperSheetApply; + + /// No description provided for @chatWallpaperPresetKomet. + /// + /// In en, this message translates to: + /// **'Comet'** + String get chatWallpaperPresetKomet; + + /// No description provided for @chatWallpaperPresetGraphite. + /// + /// In en, this message translates to: + /// **'Graphite'** + String get chatWallpaperPresetGraphite; + + /// No description provided for @chatWallpaperPresetInk. + /// + /// In en, this message translates to: + /// **'Ink'** + String get chatWallpaperPresetInk; + + /// No description provided for @chatWallpaperPresetPine. + /// + /// In en, this message translates to: + /// **'Pine'** + String get chatWallpaperPresetPine; + + /// No description provided for @chatWallpaperPresetPlum. + /// + /// In en, this message translates to: + /// **'Plum'** + String get chatWallpaperPresetPlum; + + /// No description provided for @chatWallpaperPresetUmber. + /// + /// In en, this message translates to: + /// **'Umber'** + String get chatWallpaperPresetUmber; + + /// No description provided for @chatWallpaperPresetPaper. + /// + /// In en, this message translates to: + /// **'Paper'** + String get chatWallpaperPresetPaper; + + /// No description provided for @chatWallpaperPresetFog. + /// + /// In en, this message translates to: + /// **'Fog'** + String get chatWallpaperPresetFog; + + /// No description provided for @chatWallpaperPresetSage. + /// + /// In en, this message translates to: + /// **'Sage'** + String get chatWallpaperPresetSage; + + /// No description provided for @chatWallpaperPresetSand. + /// + /// In en, this message translates to: + /// **'Sand'** + String get chatWallpaperPresetSand; + + /// No description provided for @chatWallpaperPresetPowder. + /// + /// In en, this message translates to: + /// **'Powder'** + String get chatWallpaperPresetPowder; + /// No description provided for @chatWallpaperSheetNone. /// /// In en, this message translates to: @@ -8846,6 +9248,12 @@ abstract class AppLocalizations { /// **'Close the mini app?'** String get webAppScreenCloseConfirm; + /// No description provided for @webAppUnsupportedPlatform. + /// + /// In en, this message translates to: + /// **'Mini apps aren\'t available in the Linux version yet'** + String get webAppUnsupportedPlatform; + /// No description provided for @voiceRecordUnsupported. /// /// In en, this message translates to: @@ -9494,6 +9902,84 @@ abstract class AppLocalizations { /// **'The code expired — we sent a new one'** String get codeConfirmationCodeExpired; + /// No description provided for @codeConfirmationIncomingCall. + /// + /// In en, this message translates to: + /// **'We\'re calling your number. Enter the last 6 digits of the incoming number. If there\'s no call, check SMS and the “Verification codes” chat in MAX.'** + String get codeConfirmationIncomingCall; + + /// No description provided for @callOutDescription. + /// + /// In en, this message translates to: + /// **'Call the number below from this number to confirm sign-in. Wait for the robot to answer and follow its prompts.'** + String get callOutDescription; + + /// No description provided for @callOutWaitingNumber. + /// + /// In en, this message translates to: + /// **'Getting a number to call…'** + String get callOutWaitingNumber; + + /// No description provided for @callOutTapToCopy. + /// + /// In en, this message translates to: + /// **'Tap to copy'** + String get callOutTapToCopy; + + /// No description provided for @callOutTimer. + /// + /// In en, this message translates to: + /// **'Call within {time}'** + String callOutTimer(String time); + + /// No description provided for @callOutExpired. + /// + /// In en, this message translates to: + /// **'Time to call is up — refresh the number'** + String get callOutExpired; + + /// No description provided for @callOutVerified. + /// + /// In en, this message translates to: + /// **'Call received, signing in…'** + String get callOutVerified; + + /// No description provided for @callOutDial. + /// + /// In en, this message translates to: + /// **'Call {number}'** + String callOutDial(String number); + + /// No description provided for @callOutDialPending. + /// + /// In en, this message translates to: + /// **'Call'** + String get callOutDialPending; + + /// No description provided for @callOutRefresh. + /// + /// In en, this message translates to: + /// **'Refresh number'** + String get callOutRefresh; + + /// No description provided for @callOutNewNumber. + /// + /// In en, this message translates to: + /// **'We got a new number — call it instead'** + String get callOutNewNumber; + + /// No description provided for @callOutRefreshFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t refresh the number: {error}'** + String callOutRefreshFailed(String error); + + /// No description provided for @callOutCommonError. + /// + /// In en, this message translates to: + /// **'Couldn\'t sign in, please try again'** + String get callOutCommonError; + /// No description provided for @pollViewVoteFailed. /// /// In en, this message translates to: @@ -9548,6 +10034,18 @@ abstract class AppLocalizations { /// **'Customization'** String get customizationTitle; + /// No description provided for @chatFoldersAddTo. + /// + /// In en, this message translates to: + /// **'Add to folder'** + String get chatFoldersAddTo; + + /// No description provided for @chatFoldersUpdateFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t update the folder “{title}”'** + String chatFoldersUpdateFailed(String title); + /// No description provided for @folderActionNewFolder. /// /// In en, this message translates to: @@ -10610,6 +11108,12 @@ abstract class AppLocalizations { /// **'Read messages without marking them as read'** String get kometSettingsAntiReadSubtitle; + /// No description provided for @kometSettingsAntiStoryViewSubtitle. + /// + /// In en, this message translates to: + /// **'Watch stories without appearing among their viewers. The author still sees your reactions and replies'** + String get kometSettingsAntiStoryViewSubtitle; + /// No description provided for @kometSettingsSelfOnlineCheckSubtitle. /// /// In en, this message translates to: @@ -12296,78 +12800,6 @@ abstract class AppLocalizations { /// **'Couldn\'t recognize the voice'** String get transcriptionNotRecognized; - /// No description provided for @chatWallpaperThemeOcean. - /// - /// In en, this message translates to: - /// **'Ocean'** - String get chatWallpaperThemeOcean; - - /// No description provided for @chatWallpaperThemeSunset. - /// - /// In en, this message translates to: - /// **'Sunset'** - String get chatWallpaperThemeSunset; - - /// No description provided for @chatWallpaperThemeLavender. - /// - /// In en, this message translates to: - /// **'Lavender'** - String get chatWallpaperThemeLavender; - - /// No description provided for @chatWallpaperThemeMint. - /// - /// In en, this message translates to: - /// **'Mint'** - String get chatWallpaperThemeMint; - - /// No description provided for @chatWallpaperThemeGraphite. - /// - /// In en, this message translates to: - /// **'Graphite'** - String get chatWallpaperThemeGraphite; - - /// No description provided for @chatWallpaperThemeSky. - /// - /// In en, this message translates to: - /// **'Sky'** - String get chatWallpaperThemeSky; - - /// No description provided for @chatWallpaperThemePeach. - /// - /// In en, this message translates to: - /// **'Peach'** - String get chatWallpaperThemePeach; - - /// No description provided for @chatWallpaperThemeForest. - /// - /// In en, this message translates to: - /// **'Forest'** - String get chatWallpaperThemeForest; - - /// No description provided for @chatWallpaperThemeGrape. - /// - /// In en, this message translates to: - /// **'Grape'** - String get chatWallpaperThemeGrape; - - /// No description provided for @chatWallpaperThemeNight. - /// - /// In en, this message translates to: - /// **'Night'** - String get chatWallpaperThemeNight; - - /// No description provided for @chatWallpaperThemeRose. - /// - /// In en, this message translates to: - /// **'Rose'** - String get chatWallpaperThemeRose; - - /// No description provided for @chatWallpaperThemeAmber. - /// - /// In en, this message translates to: - /// **'Amber'** - String get chatWallpaperThemeAmber; - /// No description provided for @mediaSaveFileNotFound. /// /// In en, this message translates to: @@ -12554,6 +12986,18 @@ abstract class AppLocalizations { /// **'An admin stopped your screen sharing'** String get callScreenMutedByAdmin; + /// No description provided for @callMicUnavailable. + /// + /// In en, this message translates to: + /// **'No microphone access — others can\'t hear you'** + String get callMicUnavailable; + + /// No description provided for @callMicSettings. + /// + /// In en, this message translates to: + /// **'Settings'** + String get callMicSettings; + /// No description provided for @callMediaLocked. /// /// In en, this message translates to: @@ -12697,6 +13141,210 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'You lowered the participant\'s hand'** String get callYouLoweredHand; + + /// No description provided for @whatsNewBannerTitle. + /// + /// In en, this message translates to: + /// **'Komet updated to {version}'** + String whatsNewBannerTitle(Object version); + + /// No description provided for @whatsNewBannerSubtitle. + /// + /// In en, this message translates to: + /// **'Tap to see what\'s new'** + String get whatsNewBannerSubtitle; + + /// No description provided for @whatsNewSheetTitle. + /// + /// In en, this message translates to: + /// **'What\'s new in {version}'** + String whatsNewSheetTitle(Object version); + + /// No description provided for @whatsNewNoNotes. + /// + /// In en, this message translates to: + /// **'Bug fixes and stability improvements.'** + String get whatsNewNoNotes; + + /// No description provided for @whatsNewDone. + /// + /// In en, this message translates to: + /// **'Got it'** + String get whatsNewDone; + + /// No description provided for @appearanceAnimationsTitle. + /// + /// In en, this message translates to: + /// **'Animations'** + String get appearanceAnimationsTitle; + + /// No description provided for @appearanceAnimationsSubtitle. + /// + /// In en, this message translates to: + /// **'Transitions between screens and tabs. Turn off to open everything instantly'** + String get appearanceAnimationsSubtitle; + + /// No description provided for @login2faRequiredTitle. + /// + /// In en, this message translates to: + /// **'Set a password on the device you\'ve signed in to MAX on'** + String get login2faRequiredTitle; + + /// No description provided for @login2faRequiredSteps. + /// + /// In en, this message translates to: + /// **'To do so, go to Settings → Security → Sign-in password'** + String get login2faRequiredSteps; + + /// No description provided for @login2faRequiredThen. + /// + /// In en, this message translates to: + /// **'Then you\'ll be able to sign in here'** + String get login2faRequiredThen; + + /// No description provided for @login2faRequiredNotKomet. + /// + /// In en, this message translates to: + /// **'This is NOT a Komet error. MAX requires it from everyone.'** + String get login2faRequiredNotKomet; + + /// No description provided for @login2faRequiredRetry. + /// + /// In en, this message translates to: + /// **'Try signing in again'** + String get login2faRequiredRetry; + + /// No description provided for @login2faRequiredNoAccess. + /// + /// In en, this message translates to: + /// **'I can\'t access the account'** + String get login2faRequiredNoAccess; + + /// No description provided for @login2faRequiredLinkFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t open go.max.ru/reset-session'** + String get login2faRequiredLinkFailed; + + /// No description provided for @informerBannerServerNote. + /// + /// In en, this message translates to: + /// **'This is an announcement from the MAX server. It isn\'t related to Komet.'** + String get informerBannerServerNote; + + /// No description provided for @storyReplyHint. + /// + /// In en, this message translates to: + /// **'Reply'** + String get storyReplyHint; + + /// No description provided for @storyReplySent. + /// + /// In en, this message translates to: + /// **'Message sent'** + String get storyReplySent; + + /// No description provided for @storyReplyFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t send the reply'** + String get storyReplyFailed; + + /// No description provided for @storyReplyEncrypted. + /// + /// In en, this message translates to: + /// **'This chat is encrypted, so story replies aren\'t available'** + String get storyReplyEncrypted; + + /// No description provided for @storyLikeFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t react to the story'** + String get storyLikeFailed; + + /// No description provided for @storyReplyLabel. + /// + /// In en, this message translates to: + /// **'Story'** + String get storyReplyLabel; + + /// No description provided for @storyReplyGone. + /// + /// In en, this message translates to: + /// **'A story was here'** + String get storyReplyGone; + + /// No description provided for @storyReplyUnavailable. + /// + /// In en, this message translates to: + /// **'The story is no longer available'** + String get storyReplyUnavailable; + + /// No description provided for @storyMenuProfile. + /// + /// In en, this message translates to: + /// **'Go to profile'** + String get storyMenuProfile; + + /// No description provided for @storyMenuHide. + /// + /// In en, this message translates to: + /// **'Hide author\'s stories'** + String get storyMenuHide; + + /// No description provided for @storyMenuSave. + /// + /// In en, this message translates to: + /// **'Save to gallery'** + String get storyMenuSave; + + /// No description provided for @storyMenuReport. + /// + /// In en, this message translates to: + /// **'Report'** + String get storyMenuReport; + + /// No description provided for @storyHiddenNotice. + /// + /// In en, this message translates to: + /// **'The author\'s stories are hidden'** + String get storyHiddenNotice; + + /// No description provided for @storyHideFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t hide the stories'** + String get storyHideFailed; + + /// No description provided for @storyReplyOpenChat. + /// + /// In en, this message translates to: + /// **'View'** + String get storyReplyOpenChat; + + /// No description provided for @storyHiddenUndo. + /// + /// In en, this message translates to: + /// **'Undo'** + String get storyHiddenUndo; + + /// No description provided for @storyMenuShow. + /// + /// In en, this message translates to: + /// **'Show author\'s stories'** + String get storyMenuShow; + + /// No description provided for @storyShownNotice. + /// + /// In en, this message translates to: + /// **'The author\'s stories are visible again'** + String get storyShownNotice; + + /// No description provided for @storyShowFailed. + /// + /// In en, this message translates to: + /// **'Couldn\'t show the stories'** + String get storyShowFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index de6381aa..9d3e75b9 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -156,7 +156,7 @@ class AppLocalizationsEn extends AppLocalizations { } @override - String get codeResendSms => 'Resend code via SMS'; + String get codeResendSms => 'Resend code'; @override String get codeError2faMissing => 'Error: missing data for 2FA'; @@ -702,6 +702,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get msgActionsDelete => 'Delete'; + @override + String get msgActionsRetry => 'Send again'; + + @override + String get chatRetryFileMissing => 'The file is no longer on this device'; + @override String get msgActionsCopied => 'Copied'; @@ -1400,6 +1406,10 @@ class AppLocalizationsEn extends AppLocalizations { return 'Camera unavailable: $error'; } + @override + String get callMicrophonePermissionDenied => + 'Allow Komet to access the microphone in device settings to make calls'; + @override String get callTooltipMicrophone => 'Microphone'; @@ -2463,19 +2473,12 @@ class AppLocalizationsEn extends AppLocalizations { return 'Uploading $percent%'; } - @override - String get cloudStorageStartUploadHint => - 'Start an upload to see the progress bar'; - @override String get cloudStorageEmptyTitle => 'No cloud files yet...'; @override String get cloudStorageEmptySubtitle => 'Add one?'; - @override - String get cloudStorageUpload => 'Upload'; - @override String get cloudStorageFromFile => 'From file'; @@ -2511,6 +2514,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get cloudStorageSend => 'Send'; + @override + String get cloudStorageDeleteFile => 'Delete file'; + + @override + String get cloudStorageFileDeleted => 'File deleted'; + + @override + String get cloudStorageDeleteFailed => 'Couldn\'t delete the file'; + @override String get cloudStorageAboutTooltip => 'How storage works'; @@ -3442,6 +3454,86 @@ class AppLocalizationsEn extends AppLocalizations { @override String get authLimitsConfirm => 'Got it'; + @override + String get authLimitsServerNote => + 'These limits come from the MAX server. Komet has no control over them.'; + + @override + String get storageTitle => 'Storage'; + + @override + String get storageTotalCaption => 'Komet takes up on this device'; + + @override + String get storageCategoryPhotos => 'Photos and images'; + + @override + String get storageCategoryVideos => 'Videos'; + + @override + String get storageCategoryFiles => 'Files'; + + @override + String get storageCategoryVoice => 'Voice messages'; + + @override + String get storageCategoryStickers => 'Stickers'; + + @override + String get storageCategoryKept => 'Deleted media'; + + @override + String get storageCategoryKeptHint => + 'Already erased on the server, can\'t be downloaded again'; + + @override + String get storageCategoryDatabase => 'Messages and chats'; + + @override + String get storageCategoryDatabaseHint => 'Your chat history, never cleared'; + + @override + String get storageScanning => 'Calculating…'; + + @override + String get storageScanFailed => 'Couldn\'t calculate the used space'; + + @override + String get storageEmpty => 'The cache is empty'; + + @override + String storageClear(String size) { + return 'Clear $size'; + } + + @override + String get storageNothingSelected => 'Choose what to clear'; + + @override + String storageCleared(String size) { + return 'Freed $size'; + } + + @override + String get storageClearFailed => 'Couldn\'t clear the cache'; + + @override + String get storageClearKeptMessage => + 'Deleted media can\'t be downloaded again: the server has already erased it. Clear it too?'; + + @override + String get storageClearKeptConfirm => 'Clear'; + + @override + String get storageLimitTitle => 'Maximum cache size'; + + @override + String get storageLimitUnlimited => 'No limit'; + + @override + String get storageLimitHint => + 'When the cache outgrows the limit, Komet removes what you haven\'t opened for the longest. Deleted media and messages are never removed by the limit.'; + @override String get e2eeTitle => 'End-to-end encryption'; @@ -4572,6 +4664,32 @@ class AppLocalizationsEn extends AppLocalizations { return '$_temp0'; } + @override + String get channelRecommendationsTitle => 'Recommended channels'; + + @override + String get channelRecommendationsHide => 'Hide recommendations'; + + @override + String get channelRecommendationsHidden => + 'Recommendations are hidden in this channel'; + + @override + String get channelRecommendationsHideEverywhere => 'Hide everywhere'; + + @override + String get channelPostViews => 'Views'; + + @override + String get kometSettingsHideRecommendations => 'Hide recommended channels'; + + @override + String get kometSettingsHideRecommendationsSubtitle => + 'Don\'t show similar channels at the bottom of a channel'; + + @override + String get chatScreenFormatMenu => 'Formatting'; + @override String get chatScreenFormatHeading => 'Heading'; @@ -4616,7 +4734,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get linkConfirmBody => - 'The link text doesn\'t match its address, and you haven\'t visited this site before. Check the address above before you continue.'; + 'You haven\'t visited this site before. Check the address above before you continue.'; @override String get linkConfirmOpen => 'Open'; @@ -4624,6 +4742,68 @@ class AppLocalizationsEn extends AppLocalizations { @override String get linkConfirmCancel => 'Cancel'; + @override + String get linkConfirmSuspiciousTitle => 'Suspicious link'; + + @override + String get linkConfirmOpenAnyway => 'Open anyway'; + + @override + String get linkConfirmDontOpen => 'Don\'t open'; + + @override + String linkWarningTextMismatch(String shown, String host) { + return 'The text shows $shown, but it leads to $host'; + } + + @override + String linkWarningUserInfo(String host) { + return 'Actually leads to $host'; + } + + @override + String linkWarningMixedScripts(String letters) { + return 'Mixed alphabets: $letters'; + } + + @override + String linkWarningLookalike(String script) { + return 'Only looks Latin: the letters are $script'; + } + + @override + String get linkWarningInvisible => 'The address hides invisible characters'; + + @override + String get linkWarningIpAddress => 'Leads to an IP address, not a site'; + + @override + String linkWarningScheme(String scheme) { + return 'Opens through $scheme:, not in a browser'; + } + + @override + String linkWarningLetter(String letter) { + return '“$letter”'; + } + + @override + String linkWarningLetters(String letters, String script) { + return '$letters from $script'; + } + + @override + String get linkScriptLatin => 'Latin'; + + @override + String get linkScriptCyrillic => 'Cyrillic'; + + @override + String get linkScriptGreek => 'Greek'; + + @override + String get linkScriptArmenian => 'Armenian'; + @override String get chatScreenMessageTooLong => 'The message is too long. Split it into several'; @@ -4756,6 +4936,51 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chatWallpaperSheetSampleOutgoing => 'Looks great 🔥'; + @override + String get chatWallpaperSheetInherit => 'Default'; + + @override + String get chatWallpaperSheetCurrent => 'Current'; + + @override + String get chatWallpaperSheetCustomGradient => 'Gradient'; + + @override + String get chatWallpaperSheetApply => 'Apply'; + + @override + String get chatWallpaperPresetKomet => 'Comet'; + + @override + String get chatWallpaperPresetGraphite => 'Graphite'; + + @override + String get chatWallpaperPresetInk => 'Ink'; + + @override + String get chatWallpaperPresetPine => 'Pine'; + + @override + String get chatWallpaperPresetPlum => 'Plum'; + + @override + String get chatWallpaperPresetUmber => 'Umber'; + + @override + String get chatWallpaperPresetPaper => 'Paper'; + + @override + String get chatWallpaperPresetFog => 'Fog'; + + @override + String get chatWallpaperPresetSage => 'Sage'; + + @override + String get chatWallpaperPresetSand => 'Sand'; + + @override + String get chatWallpaperPresetPowder => 'Powder'; + @override String get chatWallpaperSheetNone => 'No wallpaper'; @@ -4859,6 +5084,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get webAppScreenCloseConfirm => 'Close the mini app?'; + @override + String get webAppUnsupportedPlatform => + 'Mini apps aren\'t available in the Linux version yet'; + @override String get voiceRecordUnsupported => 'Voice messages aren\'t available on this platform'; @@ -5232,6 +5461,53 @@ class AppLocalizationsEn extends AppLocalizations { String get codeConfirmationCodeExpired => 'The code expired — we sent a new one'; + @override + String get codeConfirmationIncomingCall => + 'We\'re calling your number. Enter the last 6 digits of the incoming number. If there\'s no call, check SMS and the “Verification codes” chat in MAX.'; + + @override + String get callOutDescription => + 'Call the number below from this number to confirm sign-in. Wait for the robot to answer and follow its prompts.'; + + @override + String get callOutWaitingNumber => 'Getting a number to call…'; + + @override + String get callOutTapToCopy => 'Tap to copy'; + + @override + String callOutTimer(String time) { + return 'Call within $time'; + } + + @override + String get callOutExpired => 'Time to call is up — refresh the number'; + + @override + String get callOutVerified => 'Call received, signing in…'; + + @override + String callOutDial(String number) { + return 'Call $number'; + } + + @override + String get callOutDialPending => 'Call'; + + @override + String get callOutRefresh => 'Refresh number'; + + @override + String get callOutNewNumber => 'We got a new number — call it instead'; + + @override + String callOutRefreshFailed(String error) { + return 'Couldn\'t refresh the number: $error'; + } + + @override + String get callOutCommonError => 'Couldn\'t sign in, please try again'; + @override String get pollViewVoteFailed => 'Couldn\'t vote'; @@ -5267,6 +5543,14 @@ class AppLocalizationsEn extends AppLocalizations { @override String get customizationTitle => 'Customization'; + @override + String get chatFoldersAddTo => 'Add to folder'; + + @override + String chatFoldersUpdateFailed(String title) { + return 'Couldn\'t update the folder “$title”'; + } + @override String get folderActionNewFolder => 'New folder'; @@ -5907,6 +6191,10 @@ class AppLocalizationsEn extends AppLocalizations { String get kometSettingsAntiReadSubtitle => 'Read messages without marking them as read'; + @override + String get kometSettingsAntiStoryViewSubtitle => + 'Watch stories without appearing among their viewers. The author still sees your reactions and replies'; + @override String get kometSettingsSelfOnlineCheckSubtitle => 'Checks every ~10 seconds when you were last online. Useful for testing ghost mode'; @@ -6915,42 +7203,6 @@ class AppLocalizationsEn extends AppLocalizations { @override String get transcriptionNotRecognized => 'Couldn\'t recognize the voice'; - @override - String get chatWallpaperThemeOcean => 'Ocean'; - - @override - String get chatWallpaperThemeSunset => 'Sunset'; - - @override - String get chatWallpaperThemeLavender => 'Lavender'; - - @override - String get chatWallpaperThemeMint => 'Mint'; - - @override - String get chatWallpaperThemeGraphite => 'Graphite'; - - @override - String get chatWallpaperThemeSky => 'Sky'; - - @override - String get chatWallpaperThemePeach => 'Peach'; - - @override - String get chatWallpaperThemeForest => 'Forest'; - - @override - String get chatWallpaperThemeGrape => 'Grape'; - - @override - String get chatWallpaperThemeNight => 'Night'; - - @override - String get chatWallpaperThemeRose => 'Rose'; - - @override - String get chatWallpaperThemeAmber => 'Amber'; - @override String get mediaSaveFileNotFound => 'file not found'; @@ -7051,6 +7303,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get callScreenMutedByAdmin => 'An admin stopped your screen sharing'; + @override + String get callMicUnavailable => + 'No microphone access — others can\'t hear you'; + + @override + String get callMicSettings => 'Settings'; + @override String get callMediaLocked => 'An admin has disabled this in the call'; @@ -7128,4 +7387,117 @@ class AppLocalizationsEn extends AppLocalizations { @override String get callYouLoweredHand => 'You lowered the participant\'s hand'; + + @override + String whatsNewBannerTitle(Object version) { + return 'Komet updated to $version'; + } + + @override + String get whatsNewBannerSubtitle => 'Tap to see what\'s new'; + + @override + String whatsNewSheetTitle(Object version) { + return 'What\'s new in $version'; + } + + @override + String get whatsNewNoNotes => 'Bug fixes and stability improvements.'; + + @override + String get whatsNewDone => 'Got it'; + + @override + String get appearanceAnimationsTitle => 'Animations'; + + @override + String get appearanceAnimationsSubtitle => + 'Transitions between screens and tabs. Turn off to open everything instantly'; + + @override + String get login2faRequiredTitle => + 'Set a password on the device you\'ve signed in to MAX on'; + + @override + String get login2faRequiredSteps => + 'To do so, go to Settings → Security → Sign-in password'; + + @override + String get login2faRequiredThen => 'Then you\'ll be able to sign in here'; + + @override + String get login2faRequiredNotKomet => + 'This is NOT a Komet error. MAX requires it from everyone.'; + + @override + String get login2faRequiredRetry => 'Try signing in again'; + + @override + String get login2faRequiredNoAccess => 'I can\'t access the account'; + + @override + String get login2faRequiredLinkFailed => + 'Couldn\'t open go.max.ru/reset-session'; + + @override + String get informerBannerServerNote => + 'This is an announcement from the MAX server. It isn\'t related to Komet.'; + + @override + String get storyReplyHint => 'Reply'; + + @override + String get storyReplySent => 'Message sent'; + + @override + String get storyReplyFailed => 'Couldn\'t send the reply'; + + @override + String get storyReplyEncrypted => + 'This chat is encrypted, so story replies aren\'t available'; + + @override + String get storyLikeFailed => 'Couldn\'t react to the story'; + + @override + String get storyReplyLabel => 'Story'; + + @override + String get storyReplyGone => 'A story was here'; + + @override + String get storyReplyUnavailable => 'The story is no longer available'; + + @override + String get storyMenuProfile => 'Go to profile'; + + @override + String get storyMenuHide => 'Hide author\'s stories'; + + @override + String get storyMenuSave => 'Save to gallery'; + + @override + String get storyMenuReport => 'Report'; + + @override + String get storyHiddenNotice => 'The author\'s stories are hidden'; + + @override + String get storyHideFailed => 'Couldn\'t hide the stories'; + + @override + String get storyReplyOpenChat => 'View'; + + @override + String get storyHiddenUndo => 'Undo'; + + @override + String get storyMenuShow => 'Show author\'s stories'; + + @override + String get storyShownNotice => 'The author\'s stories are visible again'; + + @override + String get storyShowFailed => 'Couldn\'t show the stories'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index fb5acb55..91b3ac46 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -157,7 +157,7 @@ class AppLocalizationsRu extends AppLocalizations { } @override - String get codeResendSms => 'Отправить код по SMS'; + String get codeResendSms => 'Выслать код повторно'; @override String get codeError2faMissing => 'Ошибка: отсутствуют данные для 2FA'; @@ -705,6 +705,12 @@ class AppLocalizationsRu extends AppLocalizations { @override String get msgActionsDelete => 'Удалить'; + @override + String get msgActionsRetry => 'Отправить повторно'; + + @override + String get chatRetryFileMissing => 'Файла больше нет на устройстве'; + @override String get msgActionsCopied => 'Скопировано'; @@ -1403,6 +1409,10 @@ class AppLocalizationsRu extends AppLocalizations { return 'Камера недоступна: $error'; } + @override + String get callMicrophonePermissionDenied => + 'Для звонка разрешите Komet доступ к микрофону в настройках устройства'; + @override String get callTooltipMicrophone => 'Микрофон'; @@ -2474,19 +2484,12 @@ class AppLocalizationsRu extends AppLocalizations { return 'Загрузка $percent%'; } - @override - String get cloudStorageStartUploadHint => - 'Начните загрузку для прогресс-бара'; - @override String get cloudStorageEmptyTitle => 'Облачных файлов пока нет...'; @override String get cloudStorageEmptySubtitle => 'Добавите?'; - @override - String get cloudStorageUpload => 'Загрузить'; - @override String get cloudStorageFromFile => 'С файла'; @@ -2522,6 +2525,15 @@ class AppLocalizationsRu extends AppLocalizations { @override String get cloudStorageSend => 'Отправить'; + @override + String get cloudStorageDeleteFile => 'Удалить файл'; + + @override + String get cloudStorageFileDeleted => 'Файл удалён'; + + @override + String get cloudStorageDeleteFailed => 'Не удалось удалить файл'; + @override String get cloudStorageAboutTooltip => 'Как работает хранилище'; @@ -3460,6 +3472,85 @@ class AppLocalizationsRu extends AppLocalizations { @override String get authLimitsConfirm => 'Понятно'; + @override + String get authLimitsServerNote => + 'Это ограничения от сервера MAX. Komet на них не влияет.'; + + @override + String get storageTitle => 'Память'; + + @override + String get storageTotalCaption => 'Komet занимает на устройстве'; + + @override + String get storageCategoryPhotos => 'Фото и картинки'; + + @override + String get storageCategoryVideos => 'Видео'; + + @override + String get storageCategoryFiles => 'Файлы'; + + @override + String get storageCategoryVoice => 'Голосовые'; + + @override + String get storageCategoryStickers => 'Стикеры'; + + @override + String get storageCategoryKept => 'Удалённые медиа'; + + @override + String get storageCategoryKeptHint => 'Сервер их уже стёр, заново не скачать'; + + @override + String get storageCategoryDatabase => 'Сообщения и чаты'; + + @override + String get storageCategoryDatabaseHint => 'История переписки, не очищается'; + + @override + String get storageScanning => 'Считаем…'; + + @override + String get storageScanFailed => 'Не удалось посчитать занятое место'; + + @override + String get storageEmpty => 'Кэш пуст'; + + @override + String storageClear(String size) { + return 'Очистить $size'; + } + + @override + String get storageNothingSelected => 'Выберите, что очистить'; + + @override + String storageCleared(String size) { + return 'Освобождено $size'; + } + + @override + String get storageClearFailed => 'Не удалось очистить кэш'; + + @override + String get storageClearKeptMessage => + 'Удалённые медиа больше не получится скачать: сервер их уже стёр. Очистить их тоже?'; + + @override + String get storageClearKeptConfirm => 'Очистить'; + + @override + String get storageLimitTitle => 'Максимальный размер кэша'; + + @override + String get storageLimitUnlimited => 'Без лимита'; + + @override + String get storageLimitHint => + 'Когда кэш перерастает лимит, Komet удаляет то, что дольше всего не открывали. Удалённые медиа и сообщения лимит не трогает.'; + @override String get e2eeTitle => 'Сквозное шифрование'; @@ -4610,6 +4701,33 @@ class AppLocalizationsRu extends AppLocalizations { return '$_temp0'; } + @override + String get channelRecommendationsTitle => 'Рекомендуемые каналы'; + + @override + String get channelRecommendationsHide => 'Скрыть рекомендации'; + + @override + String get channelRecommendationsHidden => + 'Рекомендации скрыты в этом канале'; + + @override + String get channelRecommendationsHideEverywhere => 'Скрыть везде'; + + @override + String get channelPostViews => 'Просмотры'; + + @override + String get kometSettingsHideRecommendations => + 'Не показывать рекомендуемые каналы'; + + @override + String get kometSettingsHideRecommendationsSubtitle => + 'Похожие каналы внизу канала'; + + @override + String get chatScreenFormatMenu => 'Форматирование'; + @override String get chatScreenFormatHeading => 'Заголовок'; @@ -4654,7 +4772,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get linkConfirmBody => - 'Текст ссылки не совпадает с адресом, а на этом сайте вы ещё не были. Проверьте адрес выше, прежде чем переходить.'; + 'Вы ещё не переходили на этот сайт. Проверьте адрес выше, прежде чем открывать.'; @override String get linkConfirmOpen => 'Перейти'; @@ -4662,6 +4780,68 @@ class AppLocalizationsRu extends AppLocalizations { @override String get linkConfirmCancel => 'Отмена'; + @override + String get linkConfirmSuspiciousTitle => 'Подозрительная ссылка'; + + @override + String get linkConfirmOpenAnyway => 'Всё равно открыть'; + + @override + String get linkConfirmDontOpen => 'Не открывать'; + + @override + String linkWarningTextMismatch(String shown, String host) { + return 'Текст показывает $shown, а ведёт на $host'; + } + + @override + String linkWarningUserInfo(String host) { + return 'На самом деле ведёт на $host'; + } + + @override + String linkWarningMixedScripts(String letters) { + return 'Смешаны алфавиты: $letters'; + } + + @override + String linkWarningLookalike(String script) { + return 'Только похоже на латиницу: буквы из $script'; + } + + @override + String get linkWarningInvisible => 'В адресе спрятаны невидимые символы'; + + @override + String get linkWarningIpAddress => 'Ведёт на IP-адрес, а не на сайт'; + + @override + String linkWarningScheme(String scheme) { + return 'Откроется не в браузере, а через $scheme:'; + } + + @override + String linkWarningLetter(String letter) { + return '«$letter»'; + } + + @override + String linkWarningLetters(String letters, String script) { + return '$letters из $script'; + } + + @override + String get linkScriptLatin => 'латиницы'; + + @override + String get linkScriptCyrillic => 'кириллицы'; + + @override + String get linkScriptGreek => 'греческого алфавита'; + + @override + String get linkScriptArmenian => 'армянского алфавита'; + @override String get chatScreenMessageTooLong => 'Слишком длинное сообщение. Разделите на несколько'; @@ -4797,6 +4977,51 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chatWallpaperSheetSampleOutgoing => 'Выглядит отлично 🔥'; + @override + String get chatWallpaperSheetInherit => 'Как у всех'; + + @override + String get chatWallpaperSheetCurrent => 'Текущие'; + + @override + String get chatWallpaperSheetCustomGradient => 'Градиент'; + + @override + String get chatWallpaperSheetApply => 'Применить'; + + @override + String get chatWallpaperPresetKomet => 'Комета'; + + @override + String get chatWallpaperPresetGraphite => 'Графит'; + + @override + String get chatWallpaperPresetInk => 'Чернила'; + + @override + String get chatWallpaperPresetPine => 'Хвоя'; + + @override + String get chatWallpaperPresetPlum => 'Слива'; + + @override + String get chatWallpaperPresetUmber => 'Умбра'; + + @override + String get chatWallpaperPresetPaper => 'Бумага'; + + @override + String get chatWallpaperPresetFog => 'Туман'; + + @override + String get chatWallpaperPresetSage => 'Шалфей'; + + @override + String get chatWallpaperPresetSand => 'Песок'; + + @override + String get chatWallpaperPresetPowder => 'Пудра'; + @override String get chatWallpaperSheetNone => 'Без обоев'; @@ -4899,6 +5124,10 @@ class AppLocalizationsRu extends AppLocalizations { @override String get webAppScreenCloseConfirm => 'Закрыть мини-приложение?'; + @override + String get webAppUnsupportedPlatform => + 'Мини-приложения пока недоступны в версии для Linux'; + @override String get voiceRecordUnsupported => 'Голосовые сообщения недоступны на этой платформе'; @@ -5273,6 +5502,54 @@ class AppLocalizationsRu extends AppLocalizations { @override String get codeConfirmationCodeExpired => 'Код устарел — выслали новый'; + @override + String get codeConfirmationIncomingCall => + 'Звоним на ваш номер. Введите последние 6 цифр входящего номера. Если звонка нет, проверьте SMS и чат «Коды подтверждения» в МАХ.'; + + @override + String get callOutDescription => + 'Позвоните с этого номера на номер ниже, чтобы подтвердить вход. Дождитесь ответа робота и следуйте его подсказкам.'; + + @override + String get callOutWaitingNumber => 'Получаем номер для звонка…'; + + @override + String get callOutTapToCopy => 'Нажмите, чтобы скопировать'; + + @override + String callOutTimer(String time) { + return 'Позвоните в течение $time'; + } + + @override + String get callOutExpired => 'Время на звонок вышло — обновите номер'; + + @override + String get callOutVerified => 'Звонок принят, входим…'; + + @override + String callOutDial(String number) { + return 'Позвонить на $number'; + } + + @override + String get callOutDialPending => 'Позвонить'; + + @override + String get callOutRefresh => 'Обновить номер'; + + @override + String get callOutNewNumber => 'Получили новый номер — позвоните на него'; + + @override + String callOutRefreshFailed(String error) { + return 'Не удалось обновить номер: $error'; + } + + @override + String get callOutCommonError => + 'Не удалось войти в профиль, попробуйте ещё раз'; + @override String get pollViewVoteFailed => 'Не удалось проголосовать'; @@ -5310,6 +5587,14 @@ class AppLocalizationsRu extends AppLocalizations { @override String get customizationTitle => 'Кастомизация'; + @override + String get chatFoldersAddTo => 'Добавить в папку'; + + @override + String chatFoldersUpdateFailed(String title) { + return 'Не удалось изменить папку «$title»'; + } + @override String get folderActionNewFolder => 'Новая папка'; @@ -5953,6 +6238,10 @@ class AppLocalizationsRu extends AppLocalizations { @override String get kometSettingsAntiReadSubtitle => 'Нечиталка сообщений'; + @override + String get kometSettingsAntiStoryViewSubtitle => + 'Смотреть истории так, чтобы автор не видел вас среди зрителей. Реакции и ответы он всё равно увидит'; + @override String get kometSettingsSelfOnlineCheckSubtitle => 'Каждые ~10 секунд сверяет, когда вы были онлайн. Полезно для проверки ghost mode'; @@ -6967,42 +7256,6 @@ class AppLocalizationsRu extends AppLocalizations { @override String get transcriptionNotRecognized => 'Не распознали голос'; - @override - String get chatWallpaperThemeOcean => 'Океан'; - - @override - String get chatWallpaperThemeSunset => 'Закат'; - - @override - String get chatWallpaperThemeLavender => 'Лаванда'; - - @override - String get chatWallpaperThemeMint => 'Мята'; - - @override - String get chatWallpaperThemeGraphite => 'Графит'; - - @override - String get chatWallpaperThemeSky => 'Небо'; - - @override - String get chatWallpaperThemePeach => 'Персик'; - - @override - String get chatWallpaperThemeForest => 'Лес'; - - @override - String get chatWallpaperThemeGrape => 'Виноград'; - - @override - String get chatWallpaperThemeNight => 'Ночь'; - - @override - String get chatWallpaperThemeRose => 'Роза'; - - @override - String get chatWallpaperThemeAmber => 'Янтарь'; - @override String get mediaSaveFileNotFound => 'файл не найден'; @@ -7104,6 +7357,12 @@ class AppLocalizationsRu extends AppLocalizations { String get callScreenMutedByAdmin => 'Администратор остановил вашу демонстрацию экрана'; + @override + String get callMicUnavailable => 'Нет доступа к микрофону — вас не слышно'; + + @override + String get callMicSettings => 'Настройки'; + @override String get callMediaLocked => 'Администратор запретил это в звонке'; @@ -7181,4 +7440,117 @@ class AppLocalizationsRu extends AppLocalizations { @override String get callYouLoweredHand => 'Вы опустили руку участнику'; + + @override + String whatsNewBannerTitle(Object version) { + return 'Комета обновилась до $version'; + } + + @override + String get whatsNewBannerSubtitle => 'Нажмите, чтобы узнать, что нового'; + + @override + String whatsNewSheetTitle(Object version) { + return 'Что нового в $version'; + } + + @override + String get whatsNewNoNotes => 'Исправления ошибок и улучшения стабильности.'; + + @override + String get whatsNewDone => 'Понятно'; + + @override + String get appearanceAnimationsTitle => 'Анимации'; + + @override + String get appearanceAnimationsSubtitle => + 'Переходы между экранами и вкладками. Выключите, чтобы всё открывалось сразу'; + + @override + String get login2faRequiredTitle => + 'Установите пароль на устройстве, где вы вошли в MAX'; + + @override + String get login2faRequiredSteps => + 'Для этого перейдите в Настройки → Безопасность → Пароль для входа'; + + @override + String get login2faRequiredThen => 'Затем вы сможете войти здесь'; + + @override + String get login2faRequiredNotKomet => + 'Это ошибка НЕ ОТ Komet. Это обязательство от МАХ, всем.'; + + @override + String get login2faRequiredRetry => 'Попробовать войти снова'; + + @override + String get login2faRequiredNoAccess => 'У меня нет доступа к аккаунту'; + + @override + String get login2faRequiredLinkFailed => + 'Не удалось открыть go.max.ru/reset-session'; + + @override + String get informerBannerServerNote => + 'Это объявления от сервера МАХ. К Komet не относятся.'; + + @override + String get storyReplyHint => 'Ответить'; + + @override + String get storyReplySent => 'Отправили сообщение'; + + @override + String get storyReplyFailed => 'Не удалось отправить ответ'; + + @override + String get storyReplyEncrypted => + 'В этом чате включено шифрование — ответить на историю нельзя'; + + @override + String get storyLikeFailed => 'Не удалось поставить реакцию'; + + @override + String get storyReplyLabel => 'История'; + + @override + String get storyReplyGone => 'Здесь была история'; + + @override + String get storyReplyUnavailable => 'История больше не доступна'; + + @override + String get storyMenuProfile => 'Перейти в профиль'; + + @override + String get storyMenuHide => 'Скрыть истории автора'; + + @override + String get storyMenuSave => 'Сохранить в галерею'; + + @override + String get storyMenuReport => 'Пожаловаться'; + + @override + String get storyHiddenNotice => 'Истории автора скрыты'; + + @override + String get storyHideFailed => 'Не удалось скрыть истории'; + + @override + String get storyReplyOpenChat => 'Посмотреть'; + + @override + String get storyHiddenUndo => 'Вернуть'; + + @override + String get storyMenuShow => 'Показывать истории автора'; + + @override + String get storyShownNotice => 'Истории автора снова видны'; + + @override + String get storyShowFailed => 'Не удалось вернуть истории'; } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 0752e6d9..6a6de1b7 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -53,7 +53,7 @@ } } }, - "codeResendSms": "Отправить код по SMS", + "codeResendSms": "Выслать код повторно", "codeError2faMissing": "Ошибка: отсутствуют данные для 2FA", "codeErrorInvalid": "Неверный код", "codeConfirmation2faWarning": "По умолчанию код приходит в МАХ. Если код не приходит по SMS - не заходите в Komet/MAX 30 минут, и попробуйте заново.", @@ -236,6 +236,8 @@ "msgActionsReadByUnknownUser": "Пользователь", "msgActionsReport": "Пожаловаться", "msgActionsDelete": "Удалить", + "msgActionsRetry": "Отправить повторно", + "chatRetryFileMissing": "Файла больше нет на устройстве", "msgActionsCopied": "Скопировано", "msgActionsLoadReasonsFailed": "Не удалось загрузить причины", "msgActionsCurrentVersion": "текущая версия", @@ -452,6 +454,7 @@ "callMute": "Выкл. звук", "callEndButton": "Завершить", "callCameraUnavailable": "Камера недоступна: {error}", + "callMicrophonePermissionDenied": "Для звонка разрешите Komet доступ к микрофону в настройках устройства", "callTooltipMicrophone": "Микрофон", "callMicrophoneTitle": "Микрофон", "callMicrophoneSystem": "Системный по умолчанию", @@ -784,10 +787,8 @@ "cloudStorageNotConfiguredSubtitle": "Начнем? Это быстро.", "cloudStorageStart": "Начать", "cloudStorageUploadingPercent": "Загрузка {percent}%", - "cloudStorageStartUploadHint": "Начните загрузку для прогресс-бара", "cloudStorageEmptyTitle": "Облачных файлов пока нет...", "cloudStorageEmptySubtitle": "Добавите?", - "cloudStorageUpload": "Загрузить", "cloudStorageFromFile": "С файла", "cloudStorageById": "По ID", "cloudStorageFileIdLabel": "ID файла", @@ -799,6 +800,9 @@ "cloudStorageSendError": "Ошибка отправки", "cloudStorageSendByIdTitle": "Отправить по ID", "cloudStorageSend": "Отправить", + "cloudStorageDeleteFile": "Удалить файл", + "cloudStorageFileDeleted": "Файл удалён", + "cloudStorageDeleteFailed": "Не удалось удалить файл", "cloudStorageAboutTooltip": "Как работает хранилище", "cloudStorageAboutTitle": "Как работает хранилище", "cloudStorageAboutSubtitle": "Отдельного сервера нет: всё лежит в вашем аккаунте MAX", @@ -1175,6 +1179,30 @@ "authLimitsSignupMoreTitle": "Возможны и другие ограничения", "authLimitsSignupMoreBody": "Полного списка сервер не сообщает — если действие не сработало, попробуйте позже.", "authLimitsConfirm": "Понятно", + "authLimitsServerNote": "Это ограничения от сервера MAX. Komet на них не влияет.", + "storageTitle": "Память", + "storageTotalCaption": "Komet занимает на устройстве", + "storageCategoryPhotos": "Фото и картинки", + "storageCategoryVideos": "Видео", + "storageCategoryFiles": "Файлы", + "storageCategoryVoice": "Голосовые", + "storageCategoryStickers": "Стикеры", + "storageCategoryKept": "Удалённые медиа", + "storageCategoryKeptHint": "Сервер их уже стёр, заново не скачать", + "storageCategoryDatabase": "Сообщения и чаты", + "storageCategoryDatabaseHint": "История переписки, не очищается", + "storageScanning": "Считаем…", + "storageScanFailed": "Не удалось посчитать занятое место", + "storageEmpty": "Кэш пуст", + "storageClear": "Очистить {size}", + "storageNothingSelected": "Выберите, что очистить", + "storageCleared": "Освобождено {size}", + "storageClearFailed": "Не удалось очистить кэш", + "storageClearKeptMessage": "Удалённые медиа больше не получится скачать: сервер их уже стёр. Очистить их тоже?", + "storageClearKeptConfirm": "Очистить", + "storageLimitTitle": "Максимальный размер кэша", + "storageLimitUnlimited": "Без лимита", + "storageLimitHint": "Когда кэш перерастает лимит, Komet удаляет то, что дольше всего не открывали. Удалённые медиа и сообщения лимит не трогает.", "e2eeTitle": "Сквозное шифрование", "e2eeStatusNone": "Выключено", "e2eeStatusOffered": "Ждём, пока {name} примет запрос", @@ -1499,6 +1527,14 @@ "chatScreenCallsDialogsOnly": "Звонки доступны только в диалогах", "chatScreenMembersCount": "{count, plural, one{{count} участник} few{{count} участника} many{{count} участников} other{{count} участника}}", "chatScreenSubscribersCount": "{count, plural, one{{count} подписчик} few{{count} подписчика} many{{count} подписчиков} other{{count} подписчика}}", + "channelRecommendationsTitle": "Рекомендуемые каналы", + "channelRecommendationsHide": "Скрыть рекомендации", + "channelRecommendationsHidden": "Рекомендации скрыты в этом канале", + "channelRecommendationsHideEverywhere": "Скрыть везде", + "channelPostViews": "Просмотры", + "kometSettingsHideRecommendations": "Не показывать рекомендуемые каналы", + "kometSettingsHideRecommendationsSubtitle": "Похожие каналы внизу канала", + "chatScreenFormatMenu": "Форматирование", "chatScreenFormatHeading": "Заголовок", "chatScreenFormatBold": "Жирный", "chatScreenFormatItalic": "Курсив", @@ -1513,9 +1549,25 @@ "chatScreenFormatLinkHint": "https://example.com", "chatScreenFormatLinkInvalid": "Это не похоже на ссылку", "linkConfirmTitle": "Открыть ссылку?", - "linkConfirmBody": "Текст ссылки не совпадает с адресом, а на этом сайте вы ещё не были. Проверьте адрес выше, прежде чем переходить.", + "linkConfirmBody": "Вы ещё не переходили на этот сайт. Проверьте адрес выше, прежде чем открывать.", "linkConfirmOpen": "Перейти", "linkConfirmCancel": "Отмена", + "linkConfirmSuspiciousTitle": "Подозрительная ссылка", + "linkConfirmOpenAnyway": "Всё равно открыть", + "linkConfirmDontOpen": "Не открывать", + "linkWarningTextMismatch": "Текст показывает {shown}, а ведёт на {host}", + "linkWarningUserInfo": "На самом деле ведёт на {host}", + "linkWarningMixedScripts": "Смешаны алфавиты: {letters}", + "linkWarningLookalike": "Только похоже на латиницу: буквы из {script}", + "linkWarningInvisible": "В адресе спрятаны невидимые символы", + "linkWarningIpAddress": "Ведёт на IP-адрес, а не на сайт", + "linkWarningScheme": "Откроется не в браузере, а через {scheme}:", + "linkWarningLetter": "«{letter}»", + "linkWarningLetters": "{letters} из {script}", + "linkScriptLatin": "латиницы", + "linkScriptCyrillic": "кириллицы", + "linkScriptGreek": "греческого алфавита", + "linkScriptArmenian": "армянского алфавита", "chatScreenMessageTooLong": "Слишком длинное сообщение. Разделите на несколько", "chatScreenEncryptionKeyMissing": "Не задан ключ шифрования", "chatScreenPluginFilesEncryptUnsupported": "Файлы плагинов пока нельзя зашифровать", @@ -1551,6 +1603,21 @@ "chatWallpaperSheetTitle": "Обои", "chatWallpaperSheetSampleIncoming": "Как насчёт новых обоев для этого чата?", "chatWallpaperSheetSampleOutgoing": "Выглядит отлично 🔥", + "chatWallpaperSheetInherit": "Как у всех", + "chatWallpaperSheetCurrent": "Текущие", + "chatWallpaperSheetCustomGradient": "Градиент", + "chatWallpaperSheetApply": "Применить", + "chatWallpaperPresetKomet": "Комета", + "chatWallpaperPresetGraphite": "Графит", + "chatWallpaperPresetInk": "Чернила", + "chatWallpaperPresetPine": "Хвоя", + "chatWallpaperPresetPlum": "Слива", + "chatWallpaperPresetUmber": "Умбра", + "chatWallpaperPresetPaper": "Бумага", + "chatWallpaperPresetFog": "Туман", + "chatWallpaperPresetSage": "Шалфей", + "chatWallpaperPresetSand": "Песок", + "chatWallpaperPresetPowder": "Пудра", "chatWallpaperSheetNone": "Без обоев", "chatWallpaperSheetYourPhoto": "Ваше фото", "chatWallpaperSheetFromGallery": "Из галереи", @@ -1582,6 +1649,7 @@ "appearanceMessageActionsSubtitle": "Как показывается меню при долгом нажатии на сообщение", "videoNoteBubbleTranscriptionFailed": "Не удалось распознать", "webAppScreenCloseConfirm": "Закрыть мини-приложение?", + "webAppUnsupportedPlatform": "Мини-приложения пока недоступны в версии для Linux", "voiceRecordUnsupported": "Голосовые сообщения недоступны на этой платформе", "voiceRecordNoMicAccess": "Нет доступа к микрофону", "voiceRecordStartFailed": "Не удалось начать запись", @@ -1690,6 +1758,19 @@ "codeConfirmationNewCodeSent": "Выслали новый код", "codeConfirmationSmsNoToken": "SMS-вход: сервер не вернул токен", "codeConfirmationCodeExpired": "Код устарел — выслали новый", + "codeConfirmationIncomingCall": "Звоним на ваш номер. Введите последние 6 цифр входящего номера. Если звонка нет, проверьте SMS и чат «Коды подтверждения» в МАХ.", + "callOutDescription": "Позвоните с этого номера на номер ниже, чтобы подтвердить вход. Дождитесь ответа робота и следуйте его подсказкам.", + "callOutWaitingNumber": "Получаем номер для звонка…", + "callOutTapToCopy": "Нажмите, чтобы скопировать", + "callOutTimer": "Позвоните в течение {time}", + "callOutExpired": "Время на звонок вышло — обновите номер", + "callOutVerified": "Звонок принят, входим…", + "callOutDial": "Позвонить на {number}", + "callOutDialPending": "Позвонить", + "callOutRefresh": "Обновить номер", + "callOutNewNumber": "Получили новый номер — позвоните на него", + "callOutRefreshFailed": "Не удалось обновить номер: {error}", + "callOutCommonError": "Не удалось войти в профиль, попробуйте ещё раз", "pollViewVoteFailed": "Не удалось проголосовать", "pollViewLoading": "Загрузка опроса…", "pollViewMultipleAnswers": "Несколько вариантов ответа", @@ -1699,6 +1780,8 @@ "customizationChatBackground": "Фон чатов", "customizationAppIcon": "Иконка приложения", "customizationTitle": "Кастомизация", + "chatFoldersAddTo": "Добавить в папку", + "chatFoldersUpdateFailed": "Не удалось изменить папку «{title}»", "folderActionNewFolder": "Новая папка", "folderActionDeleteConfirm": "Удалить папку «{title}»? Чаты останутся на месте.", "foldersSettingsCreate": "Создать папку", @@ -1876,6 +1959,7 @@ "kometSettingsArchiveOnPullSubtitle": "Прятать архив и показывать его, если потянуть список чатов вниз, после историй", "kometSettingsGhostModeSubtitle": "Вас не видно в сети", "kometSettingsAntiReadSubtitle": "Нечиталка сообщений", + "kometSettingsAntiStoryViewSubtitle": "Смотреть истории так, чтобы автор не видел вас среди зрителей. Реакции и ответы он всё равно увидит", "kometSettingsSelfOnlineCheckSubtitle": "Каждые ~10 секунд сверяет, когда вы были онлайн. Полезно для проверки ghost mode", "kometSettingsDebugHeader": "Отладка", "kometSettingsDebugLogsLabel": "Запись отладочных логов", @@ -2157,18 +2241,6 @@ "pluginPermissionStorage": "Локальное хранилище плагина", "pluginUpdateNewPermissions": "Обновление запрашивает новые разрешения: {permissions}", "transcriptionNotRecognized": "Не распознали голос", - "chatWallpaperThemeOcean": "Океан", - "chatWallpaperThemeSunset": "Закат", - "chatWallpaperThemeLavender": "Лаванда", - "chatWallpaperThemeMint": "Мята", - "chatWallpaperThemeGraphite": "Графит", - "chatWallpaperThemeSky": "Небо", - "chatWallpaperThemePeach": "Персик", - "chatWallpaperThemeForest": "Лес", - "chatWallpaperThemeGrape": "Виноград", - "chatWallpaperThemeNight": "Ночь", - "chatWallpaperThemeRose": "Роза", - "chatWallpaperThemeAmber": "Янтарь", "mediaSaveFileNotFound": "файл не найден", "mediaSaveNoGalleryAccess": "нет доступа к галерее", "mediaSaveNoStorageAccess": "нет доступа к памяти", @@ -2200,6 +2272,8 @@ "callMicMutedByAdmin": "Администратор выключил ваш микрофон", "callCameraMutedByAdmin": "Администратор выключил вашу камеру", "callScreenMutedByAdmin": "Администратор остановил вашу демонстрацию экрана", + "callMicUnavailable": "Нет доступа к микрофону — вас не слышно", + "callMicSettings": "Настройки", "callMediaLocked": "Администратор запретил это в звонке", "callRecordingBy": "{name} записывает звонок", "callRecordingSelf": "Вы записываете звонок", @@ -2223,5 +2297,39 @@ "callParticipantsSearchHint": "Поиск участников", "callShareScreen": "Показать экран", "callYouLoweredAllHands": "Вы опустили всем руки", - "callYouLoweredHand": "Вы опустили руку участнику" + "callYouLoweredHand": "Вы опустили руку участнику", + "whatsNewBannerTitle": "Комета обновилась до {version}", + "whatsNewBannerSubtitle": "Нажмите, чтобы узнать, что нового", + "whatsNewSheetTitle": "Что нового в {version}", + "whatsNewNoNotes": "Исправления ошибок и улучшения стабильности.", + "whatsNewDone": "Понятно", + "appearanceAnimationsTitle": "Анимации", + "appearanceAnimationsSubtitle": "Переходы между экранами и вкладками. Выключите, чтобы всё открывалось сразу", + "login2faRequiredTitle": "Установите пароль на устройстве, где вы вошли в MAX", + "login2faRequiredSteps": "Для этого перейдите в Настройки → Безопасность → Пароль для входа", + "login2faRequiredThen": "Затем вы сможете войти здесь", + "login2faRequiredNotKomet": "Это ошибка НЕ ОТ Komet. Это обязательство от МАХ, всем.", + "login2faRequiredRetry": "Попробовать войти снова", + "login2faRequiredNoAccess": "У меня нет доступа к аккаунту", + "login2faRequiredLinkFailed": "Не удалось открыть go.max.ru/reset-session", + "informerBannerServerNote": "Это объявления от сервера МАХ. К Komet не относятся.", + "storyReplyHint": "Ответить", + "storyReplySent": "Отправили сообщение", + "storyReplyFailed": "Не удалось отправить ответ", + "storyReplyEncrypted": "В этом чате включено шифрование — ответить на историю нельзя", + "storyLikeFailed": "Не удалось поставить реакцию", + "storyReplyLabel": "История", + "storyReplyGone": "Здесь была история", + "storyReplyUnavailable": "История больше не доступна", + "storyMenuProfile": "Перейти в профиль", + "storyMenuHide": "Скрыть истории автора", + "storyMenuSave": "Сохранить в галерею", + "storyMenuReport": "Пожаловаться", + "storyHiddenNotice": "Истории автора скрыты", + "storyHideFailed": "Не удалось скрыть истории", + "storyReplyOpenChat": "Посмотреть", + "storyHiddenUndo": "Вернуть", + "storyMenuShow": "Показывать истории автора", + "storyShownNotice": "Истории автора снова видны", + "storyShowFailed": "Не удалось вернуть истории" } diff --git a/lib/main.dart b/lib/main.dart index f2d91a7d..8736d798 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -17,12 +17,16 @@ import 'core/cache/chat_scroll_memory.dart'; import 'core/cache/info_cache.dart'; import 'core/plugins/plugin_store.dart'; import 'core/config/build_profile.dart'; +import 'core/config/whats_new.dart'; +import 'core/config/app_motion.dart'; +import 'frontend/widgets/app_motion_scope.dart'; import 'core/utils/app_foreground.dart'; import 'core/utils/logger.dart'; import 'core/cache/self_presence.dart'; import 'core/storage/app_instance.dart'; import 'core/storage/draft_store.dart'; import 'core/storage/archived_chats_store.dart'; +import 'core/storage/ghost_read_store.dart'; import 'core/storage/local_contact_avatars.dart'; import 'core/crypto/e2ee_service.dart'; import 'core/crypto/encrypted_photo_cache.dart'; @@ -55,7 +59,8 @@ import 'core/config/app_phonebook_names.dart'; import 'core/contacts/device_contacts_service.dart'; import 'core/config/app_link_preview.dart'; import 'core/config/app_unchecked_links.dart'; -import 'core/config/app_media_cache.dart'; +import 'core/config/app_cache_limit.dart'; +import 'core/cache/cache_janitor.dart'; import 'core/config/app_video_note_quality.dart'; import 'core/config/app_pill_gradient.dart'; import 'core/config/app_visual_style.dart'; @@ -98,6 +103,7 @@ import 'core/share/native_share_account_sync.dart'; import 'core/push/push_service.dart'; import 'core/storage/app_database.dart'; import 'core/storage/per_chat_json_store.dart'; +import 'core/transport/network_core.dart'; import 'core/transport/tls_config.dart'; import 'core/transport/traffic_monitor.dart'; import 'core/transport/vpn_bypass.dart'; @@ -111,6 +117,7 @@ import 'frontend/debug/performance_monitor.dart'; import 'frontend/screens/auth/login_screen.dart'; import 'frontend/widgets/adaptive_shell.dart'; import 'frontend/widgets/chat_wallpaper_view.dart' show WallpaperImages; +import 'frontend/widgets/theme_wallpaper.dart' show precacheWallpaperTheme; import 'frontend/widgets/custom_notification.dart'; import 'frontend/widgets/hint_bubble.dart'; import 'frontend/widgets/keyboard_cover.dart'; @@ -145,11 +152,21 @@ const ProgressIndicatorThemeData _expressiveProgressTheme = const PageTransitionsTheme _appPageTransitions = PageTransitionsTheme( builders: { - TargetPlatform.android: PredictiveBackPageTransitionsBuilder(), - TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), - TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), - TargetPlatform.windows: ZoomPageTransitionsBuilder(), - TargetPlatform.linux: ZoomPageTransitionsBuilder(), + TargetPlatform.android: MotionAwarePageTransitions( + PredictiveBackPageTransitionsBuilder(), + ), + TargetPlatform.iOS: MotionAwarePageTransitions( + CupertinoPageTransitionsBuilder(), + ), + TargetPlatform.macOS: MotionAwarePageTransitions( + CupertinoPageTransitionsBuilder(), + ), + TargetPlatform.windows: MotionAwarePageTransitions( + ZoomPageTransitionsBuilder(), + ), + TargetPlatform.linux: MotionAwarePageTransitions( + ZoomPageTransitionsBuilder(), + ), }, ); @@ -220,8 +237,8 @@ void main(List args) async { if (AppInstance.isNamed) { SharedPreferences.setPrefix('flutter.${AppInstance.id}.'); } - debugPrint('KOMET-STARTUP: applyMincifryTrust...'); - await TlsConfig.applyMincifryTrust(); + debugPrint('KOMET-STARTUP: NetworkCore.configure...'); + await NetworkCore.configure(); debugPrint('KOMET-STARTUP: AppDatabase.init...'); await AppDatabase.init(); await DecryptedPhotoStore.clear(); @@ -242,6 +259,8 @@ void main(List args) async { unawaited(DeepLinkService.instance.init()); final packageInfoFuture = PackageInfo.fromPlatform(); + final whatsNewFuture = WhatsNew.load(); + final motionFuture = AppMotion.load(); final localeFuture = AppLanguage.load(); final hapticsFuture = Haptics.load(); final prefsFuture = SharedPreferences.getInstance(); @@ -269,7 +288,7 @@ void main(List args) async { final phonebookNamesFuture = AppPhonebookNames.load(); final linkPreviewFuture = AppLinkPreview.load(); final uncheckedLinksFuture = AppUncheckedLinks.load(); - final cacheLimitFuture = AppMediaCacheLimit.load(); + final cacheLimitFuture = AppCacheLimit.load(); final videoNoteResolutionFuture = AppVideoNoteResolution.load(); final videoNoteFpsFuture = AppVideoNoteFps.load(); final videoNoteRearCameraFuture = AppVideoNoteRearCamera.load(); @@ -292,9 +311,12 @@ void main(List args) async { await FileHistoryCache.load(prefs); await DraftStore.instance.load(); await ArchivedChatsStore.instance.load(); + await GhostReadStore.instance.load(); await LocalContactAvatars.instance.load(); await badgeFuture; await notificationsFuture; + await whatsNewFuture; + await motionFuture; await ChatEncryptionStore.instance.load(); E2eeService.instance.attach(messagesModule); await KometSettings.load(); @@ -357,6 +379,7 @@ void main(List args) async { ]); debugPrint('KOMET-STARTUP: DeviceContactsService.loadFromStartup...'); unawaited(DeviceContactsService.loadFromStartup()); + CacheJanitor.instance.schedule(CacheJanitor.startupDelay); await trafficCaptureFuture; await debugLogFuture; debugPrint('KOMET-STARTUP: runApp'); @@ -937,8 +960,12 @@ class KometAppState extends State await ChatWallpaperStore.instance.load(); final wallpaper = accountId == 0 ? null - : ChatWallpaperStore.instance.get(accountId, kGlobalWallpaperChatId); + : ChatWallpaperStore.instance.effective( + accountId, + kGlobalWallpaperChatId, + ); WallpaperImages.holdGlobal(wallpaper); + ChatWallpaperStore.instance.themeIds.forEach(precacheWallpaperTheme); if (!AppWallpaperTint.current.value || wallpaper == null) { _globalWallpaper = null; wallpaperSeed.value = null; @@ -1155,15 +1182,13 @@ class KometAppState extends State valueListenable: fontScale, child: child ?? const SizedBox.shrink(), builder: (context, scale, appChild) { - Widget scaledChild = KeyboardCoverScope(child: appChild!); - final effective = AppFonts.effectiveScale(_fontId, scale); - if ((effective - 1.0).abs() > 0.001) { - scaledChild = MediaQuery.withClampedTextScaling( - minScaleFactor: effective, - maxScaleFactor: effective, - child: scaledChild, - ); - } + Widget scaledChild = AppMotionScope( + child: KeyboardCoverScope(child: appChild!), + ); + scaledChild = AppTextScaling( + factor: AppFonts.effectiveScale(_fontId, scale), + child: scaledChild, + ); return ValueListenableBuilder( valueListenable: fpsOverlayEnabled, child: scaledChild, diff --git a/lib/models/attachment.dart b/lib/models/attachment.dart index 03d69c8e..faea87f0 100644 --- a/lib/models/attachment.dart +++ b/lib/models/attachment.dart @@ -18,6 +18,7 @@ enum AttachmentType { call, inlineKeyboard, forward, + storyReply, unknown, } @@ -75,6 +76,8 @@ abstract class MessageAttachment { return ShareAttachment.fromMap(map); case 'INLINE_KEYBOARD': return InlineKeyboardAttachment.fromMap(map); + case 'STORY_REPLY': + return StoryReplyAttachment.fromMap(map); default: return UnknownAttachment(map); } @@ -217,6 +220,7 @@ class AudioAttachment extends MessageAttachment { final int? duration; final int? size; final String? waveform; + final String? localPath; const AudioAttachment({ super.previewData, @@ -227,6 +231,7 @@ class AudioAttachment extends MessageAttachment { this.duration, this.size, this.waveform, + this.localPath, }) : super(type: AttachmentType.audio); // #***! волна то строкой то байтами, сводим к строке @@ -251,6 +256,7 @@ class AudioAttachment extends MessageAttachment { duration: map['duration'] as int?, size: map['size'] as int?, waveform: waveStr, + localPath: map['localPath'] as String?, ); } @@ -264,6 +270,7 @@ class AudioAttachment extends MessageAttachment { 'duration': duration, 'size': size, 'waveform': waveform, + 'localPath': localPath, }; } @@ -274,6 +281,7 @@ class FileAttachment extends MessageAttachment { final String? name; final int? size; final PhotoAttachment? preview; + final String? localPath; const FileAttachment({ super.previewData, @@ -284,6 +292,7 @@ class FileAttachment extends MessageAttachment { this.name, this.size, this.preview, + this.localPath, }) : super(type: AttachmentType.file); // #***! обложка разбирается как обычное фото @@ -302,6 +311,7 @@ class FileAttachment extends MessageAttachment { name: repairLatin1Mojibake(map['name'] as String?), size: map['size'] as int?, preview: preview, + localPath: map['localPath'] as String?, ); } @@ -315,6 +325,7 @@ class FileAttachment extends MessageAttachment { 'name': name, 'size': size, if (preview != null) 'preview': preview!.toMap(), + 'localPath': localPath, }; } @@ -858,6 +869,46 @@ class ForwardedMessageAttachment extends MessageAttachment { }; } +class StoryReplyAttachment extends MessageAttachment { + final int storyId; + final int ownerId; + final int ownerType; + final String? previewUrl; + final int expirationTime; + + const StoryReplyAttachment({ + required this.storyId, + required this.ownerId, + this.ownerType = 0, + this.previewUrl, + this.expirationTime = 0, + }) : super(type: AttachmentType.storyReply); + + factory StoryReplyAttachment.fromMap(Map map) { + final owner = map['owner']; + final preview = map['previewUrl']?.toString(); + return StoryReplyAttachment( + storyId: parseIntOrNull(map['storyId']) ?? 0, + ownerId: owner is Map ? parseIntOrNull(owner['ownerId']) ?? 0 : 0, + ownerType: owner is Map ? parseIntOrNull(owner['type']) ?? 0 : 0, + previewUrl: preview == null || preview.isEmpty ? null : preview, + expirationTime: parseIntOrNull(map['expirationTime']) ?? 0, + ); + } + + bool goneAt(int nowMs) => + previewUrl == null || (expirationTime > 0 && nowMs > expirationTime); + + @override + Map toMap() => { + '_type': 'STORY_REPLY', + 'owner': {'ownerId': ownerId, 'type': ownerType}, + 'storyId': storyId, + 'previewUrl': ?previewUrl, + if (expirationTime > 0) 'expirationTime': expirationTime, + }; +} + // #***! неизвестное вложение храним как есть чтоб не потерять class UnknownAttachment extends MessageAttachment { final Map rawData; diff --git a/lib/models/story.dart b/lib/models/story.dart index 75792b6e..e6174471 100644 --- a/lib/models/story.dart +++ b/lib/models/story.dart @@ -1,3 +1,6 @@ +import 'dart:convert'; +import 'dart:typed_data'; + import '../core/utils/parse.dart'; import 'attachment.dart'; @@ -94,6 +97,7 @@ class StoryMedia { final String? url; final String? thumbnailUrl; final String? previewData; + final Uint8List? thumbhash; final int? width; final int? height; final int? durationMs; @@ -103,11 +107,26 @@ class StoryMedia { this.url, this.thumbnailUrl, this.previewData, + this.thumbhash, this.width, this.height, this.durationMs, }); + static Uint8List? _thumbhashOf(Object? raw) { + if (raw is Uint8List) return raw.isEmpty ? null : raw; + if (raw is List) { + final bytes = raw.whereType().toList(); + return bytes.isEmpty ? null : Uint8List.fromList(bytes); + } + if (raw is String && raw.isNotEmpty) { + try { + return base64Decode(raw); + } catch (_) {} + } + return null; + } + // #***! видео и фото рисуют разные виджеты bool get isVideo => type == AttachmentType.video; bool get isPhoto => type == AttachmentType.photo; @@ -125,6 +144,7 @@ class StoryMedia { final map = _asStringMap(raw); final typeStr = (map['_type'] as String? ?? '').toUpperCase(); final previewData = decodeAttachPreview(map['previewData']); + final thumbhash = _thumbhashOf(map['thumbhash']); final width = parseIntOrNull(map['width']); final height = parseIntOrNull(map['height']); switch (typeStr) { @@ -135,14 +155,15 @@ class StoryMedia { type: AttachmentType.photo, url: url, previewData: previewData, + thumbhash: thumbhash, width: width, height: height, ); case 'VIDEO': final url = - (map['mp4Url'] ?? + (map['MP4_1080'] ?? + map['mp4Url'] ?? map['videoUrl'] ?? - map['MP4_1080'] ?? map['baseUrl']) ?.toString(); return StoryMedia( @@ -150,6 +171,7 @@ class StoryMedia { url: url, thumbnailUrl: map['thumbnail']?.toString(), previewData: previewData, + thumbhash: thumbhash, width: width, height: height, durationMs: parseIntOrNull(map['duration']), @@ -158,6 +180,7 @@ class StoryMedia { return StoryMedia( type: AttachmentType.unknown, previewData: previewData, + thumbhash: thumbhash, width: width, height: height, ); @@ -180,6 +203,7 @@ class StoryMedia { final map = { '_type': _typeName, if (previewData != null) 'previewData': previewData, + if (thumbhash != null) 'thumbhash': base64Encode(thumbhash!), if (width != null) 'width': width, if (height != null) 'height': height, }; @@ -205,6 +229,9 @@ class Story { final int expiration; final StoryMedia? media; final StoryReaction? reaction; + final int version; + final int? viewsCount; + final int? reactionsCount; const Story({ required this.id, @@ -216,8 +243,34 @@ class Story { this.expiration = 0, this.media, this.reaction, + this.version = 0, + this.viewsCount, + this.reactionsCount, }); + static const int _reactionsOff = 4; + static const int _repliesOff = 8; + static const int _profileOff = 16; + static const int _hideAuthorOff = 32; + static const int _savingOff = 64; + static const int _complaintsOff = 128; + + bool _allows(int bit) => settings & bit == 0; + bool get allowsReactions => _allows(_reactionsOff); + bool get allowsReplies => owner.isUser && _allows(_repliesOff); + bool get allowsProfile => owner.isUser && _allows(_profileOff); + bool get allowsHidingAuthor => owner.isUser && _allows(_hideAuthorOff); + bool get allowsSaving => _allows(_savingOff); + bool get allowsComplaints => _allows(_complaintsOff); + + bool get liked => reaction != null; + + bool expiredAt(int nowMs) { + if (expiration <= 0 || time <= 0) return false; + final timeMs = time < 1000000000000 ? time * 1000 : time; + return nowMs >= timeMs + expiration; + } + // #***! локально меняется только реакция Story copyWith({StoryReaction? reaction, bool clearReaction = false}) { return Story( @@ -230,6 +283,9 @@ class Story { expiration: expiration, media: media, reaction: clearReaction ? null : (reaction ?? this.reaction), + version: version, + viewsCount: viewsCount, + reactionsCount: reactionsCount, ); } @@ -248,6 +304,9 @@ class Story { expiration: parseIntOrNull(map['expiration']) ?? 0, media: StoryMedia.fromMap(map['media']), reaction: StoryReaction.fromMap(map['reaction']), + version: parseIntOrNull(map['version']) ?? 0, + viewsCount: parseIntOrNull(map['viewsCount']), + reactionsCount: parseIntOrNull(map['reactionsCount']), ); } @@ -261,6 +320,9 @@ class Story { 'expiration': expiration, if (media != null) 'media': media!.toJson(), if (reaction != null) 'reaction': reaction!.toMap(), + if (version != 0) 'version': version, + 'viewsCount': ?viewsCount, + 'reactionsCount': ?reactionsCount, }; } diff --git a/lib/models/suggested_channel.dart b/lib/models/suggested_channel.dart new file mode 100644 index 00000000..212946aa --- /dev/null +++ b/lib/models/suggested_channel.dart @@ -0,0 +1,33 @@ +class SuggestedChannel { + final int id; + final String title; + final String? iconUrl; + final String link; + final int? subscribers; + + const SuggestedChannel({ + required this.id, + required this.title, + required this.link, + this.iconUrl, + this.subscribers, + }); + + static SuggestedChannel? fromServer(Object? raw) { + if (raw is! Map) return null; + final id = raw['id']; + final link = raw['link']; + if (id is! int || link is! String || link.isEmpty) return null; + if (raw['type'] != 'CHANNEL') return null; + final title = (raw['title'] as String?)?.trim() ?? ''; + final icon = raw['baseIconUrl']; + final count = raw['participantsCount']; + return SuggestedChannel( + id: id, + title: title, + link: link, + iconUrl: icon is String && icon.isNotEmpty ? icon : null, + subscribers: count is int ? count : null, + ); + } +} diff --git a/native/flutter_inappwebview_linux/lib/flutter_inappwebview_linux.dart b/native/flutter_inappwebview_linux/lib/flutter_inappwebview_linux.dart new file mode 100644 index 00000000..dbbad450 --- /dev/null +++ b/native/flutter_inappwebview_linux/lib/flutter_inappwebview_linux.dart @@ -0,0 +1,3 @@ +abstract final class LinuxInAppWebViewUnavailable { + static void registerWith() {} +} diff --git a/native/flutter_inappwebview_linux/pubspec.yaml b/native/flutter_inappwebview_linux/pubspec.yaml new file mode 100644 index 00000000..dd839500 --- /dev/null +++ b/native/flutter_inappwebview_linux/pubspec.yaml @@ -0,0 +1,23 @@ +name: flutter_inappwebview_linux +description: >- + Replaces the WPE WebKit implementation of flutter_inappwebview on Linux. + The mini-app bridge cannot verify the document origin there and stays closed + (WebAppBridge.isSupported), so Komet ships no Linux webview and does not + depend on WPE WebKit at build or run time. +version: 0.1.0-beta.1 +publish_to: none + +environment: + sdk: ^3.10.4 + flutter: ">=3.32.0" + +dependencies: + flutter: + sdk: flutter + +flutter: + plugin: + implements: flutter_inappwebview + platforms: + linux: + dartPluginClass: LinuxInAppWebViewUnavailable diff --git a/pubspec.lock b/pubspec.lock index e33cbca1..5dfc232a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -73,6 +73,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + audio_metadata_reader: + dependency: "direct main" + description: + name: audio_metadata_reader + sha256: "66e8e216deab90008fa161c345e93c7c3cab28667042264976eb03865122a7b9" + url: "https://pub.dev" + source: hosted + version: "1.8.1" audio_service: dependency: "direct main" description: @@ -209,6 +217,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + charset: + dependency: transitive + description: + name: charset + sha256: "27802032a581e01ac565904ece8c8962564b1070690794f0072f6865958ce8b9" + url: "https://pub.dev" + source: hosted + version: "2.0.1" checked_yaml: dependency: transitive description: @@ -540,12 +556,11 @@ packages: source: hosted version: "1.2.0-beta.3" flutter_inappwebview_linux: - dependency: transitive + dependency: "direct overridden" description: - name: flutter_inappwebview_linux - sha256: "2e1a3b09bb911fb5a8bb155cb7f1eb1428a19b6e20363b9db48beef428b8cef5" - url: "https://pub.dev" - source: hosted + path: "native/flutter_inappwebview_linux" + relative: true + source: path version: "0.1.0-beta.1" flutter_inappwebview_macos: dependency: transitive @@ -734,8 +749,8 @@ packages: dependency: "direct main" description: path: "." - ref: fddd76a999c6181813d9b1fddfe65a835ea2e7b2 - resolved-ref: fddd76a999c6181813d9b1fddfe65a835ea2e7b2 + ref: "8fcca4e41c6f4e736fb1b48dc8d86638ff01c9bf" + resolved-ref: "8fcca4e41c6f4e736fb1b48dc8d86638ff01c9bf" url: "https://github.com/KometTeam/flutter-webrtc.git" source: git version: "1.5.2" @@ -1009,10 +1024,10 @@ packages: dependency: "direct main" description: name: kolibri - sha256: e2f3414e6a8601c31dd3c5a7ebd901e48b67bf29265333b27366402bf4ac52ef + sha256: d33e509b6995dbf86f5b51dbb8f41ed479dd37a4d38ceb0918ed36765af75896 url: "https://pub.dev" source: hosted - version: "0.1.5" + version: "0.1.7" komet_crypto: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 5eb433cb..eee9164d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 0.5.22+22 +version: 0.5.23+23 environment: sdk: ^3.10.4 @@ -37,9 +37,9 @@ dependencies: # Rust networking core (kolibri) — FFI plugin, replaces the Dart transport. # Published from the KometTeam/kolibri repo; the native core is compiled at # app build time and pulled from that repo by git tag. - kolibri: ^0.1.5 + kolibri: ^0.1.7 - # Пробрасывается только ради RustStreamSink: kolibri 0.1.5 не отдаёт isPwa и + # Пробрасывается только ради RustStreamSink: kolibri 0.1.7 не отдаёт isPwa и # headerUserAgent через openSessionWithWireLog, а веб-хэндшейку они нужны, так # что SessionOptions собираем сами. Версия обязана совпадать с пином kolibri. flutter_rust_bridge: 2.12.0 @@ -99,7 +99,10 @@ dependencies: firebase_messaging: ^16.0.2 flutter_local_notifications: ^22.0.1 flutter_inappwebview: 6.2.0-beta.3 - flutter_webrtc: ^1.5.2 + flutter_webrtc: + git: + url: https://github.com/KometTeam/flutter-webrtc.git + ref: 8fcca4e41c6f4e736fb1b48dc8d86638ff01c9bf record: ^6.0.0 opus_dart: ^3.0.1 opus_flutter_android: ^3.0.1 @@ -107,6 +110,7 @@ dependencies: audio_service: ^0.18.19 audio_session: ^0.2.4 just_audio: ^0.10.6 + audio_metadata_reader: ^1.8.1 just_audio_media_kit: ^2.1.0 media_kit: ^1.2.6 media_kit_video: ^2.0.1 @@ -124,10 +128,8 @@ dependencies: desktop_drop: ^0.8.4 dependency_overrides: - flutter_webrtc: - git: - url: https://github.com/KometTeam/flutter-webrtc.git - ref: fddd76a999c6181813d9b1fddfe65a835ea2e7b2 + flutter_inappwebview_linux: + path: native/flutter_inappwebview_linux dev_dependencies: flutter_test: @@ -189,6 +191,7 @@ flutter: - assets/plugins/nekos/ - assets/plugins/info/ - assets/plugins/weather/ + - assets/whats_new/ fonts: - family: Inter diff --git a/scripts/sign_ios_appstore.py b/scripts/sign_ios_appstore.py index a40e0f0c..18a1560e 100644 --- a/scripts/sign_ios_appstore.py +++ b/scripts/sign_ios_appstore.py @@ -1,12 +1,24 @@ import argparse from dataclasses import dataclass +from fnmatch import fnmatchcase from pathlib import Path import plistlib +import re import shutil import subprocess import tempfile +PROFILE_KEYS = ( + "application-identifier", + "com.apple.developer.team-identifier", + "get-task-allow", + "beta-reports-active", +) +APP_GROUPS = "com.apple.security.application-groups" +BUILD_VARIABLE = re.compile(r"\$\(([A-Za-z0-9_]+)\)") + + class SigningPlanError(ValueError): pass @@ -23,6 +35,8 @@ class SigningPlan: app: ProfileIdentity share: ProfileIdentity | None group: str | None + app_entitlements: dict + share_entitlements: dict | None def profile_identity(profile): @@ -49,10 +63,69 @@ def profile_groups(identity): return {value for value in values if isinstance(value, str) and value.startswith("group.") and "*" not in value} -def create_plan(app_profile, share_profile=None, preferred_group=None): +def expand(value, variables): + if isinstance(value, str): + def resolve(match): + name = match.group(1) + if name not in variables: + raise SigningPlanError(f"Unknown build variable $({name}) in entitlements") + return variables[name] + return BUILD_VARIABLE.sub(resolve, value) + if isinstance(value, list): + return [expand(item, variables) for item in value] + if isinstance(value, dict): + return {key: expand(item, variables) for key, item in value.items()} + return value + + +def granted_by(value, granted): + if granted == "*": + return True + if isinstance(value, list): + return all(granted_by(item, granted) for item in value) + if isinstance(granted, list): + return any(granted_by(value, item) for item in granted) + if isinstance(value, str) and isinstance(granted, str): + return fnmatchcase(value, granted) + return value == granted + + +def contains_wildcard(value): + if isinstance(value, str): + return "*" in value + if isinstance(value, list): + return any(contains_wildcard(item) for item in value) + if isinstance(value, dict): + return any(contains_wildcard(item) for item in value.values()) + return False + + +def signing_entitlements(identity, requested, group): + granted = identity.entitlements + variables = { + "AppIdentifierPrefix": f"{identity.team_id}.", + "TeamIdentifierPrefix": f"{identity.team_id}.", + "PRODUCT_BUNDLE_IDENTIFIER": identity.bundle_id, + "KOMET_SHARE_APP_GROUP": group or "", + } + result = {key: granted[key] for key in PROFILE_KEYS if key in granted} + for key, value in expand(requested, variables).items(): + if key in PROFILE_KEYS: + continue + if key == APP_GROUPS and group is None: + continue + if key not in granted or not granted_by(value, granted[key]): + raise SigningPlanError(f"Provisioning profile does not allow entitlement {key}={value!r}") + if contains_wildcard(value): + raise SigningPlanError(f"Entitlement {key} must not contain a wildcard") + result[key] = value + return result + + +def create_plan(app_profile, share_profile=None, preferred_group=None, app_requested=None, share_requested=None): app = profile_identity(app_profile) if share_profile is None: - return SigningPlan(app, None, None) + return SigningPlan(app, None, None, signing_entitlements(app, app_requested or {}, None), None) share = profile_identity(share_profile) if app.team_id != share.team_id: raise SigningPlanError("App and Share Extension profiles must belong to the same team") @@ -62,7 +135,13 @@ def create_plan(app_profile, share_profile=None, preferred_group=None): if not groups: raise SigningPlanError("App and Share Extension profiles must allow a common explicit App Group") group = preferred_group if preferred_group in groups else sorted(groups)[0] - return SigningPlan(app, share, group) + return SigningPlan( + app, + share, + group, + signing_entitlements(app, app_requested or {}, group), + signing_entitlements(share, share_requested or {}, group), + ) def read_plist(path): @@ -128,10 +207,10 @@ def sign_bundles(app_path, share_path, plan, identity, keychain, run=subprocess. run([*common, str(bundle)], check=True) if plan.share is not None: share_entitlements = directory / "share.entitlements" - write_plist(share_entitlements, plan.share.entitlements) + write_plist(share_entitlements, plan.share_entitlements) run([*common, "--entitlements", str(share_entitlements), str(share_path)], check=True) app_entitlements = directory / "app.entitlements" - write_plist(app_entitlements, plan.app.entitlements) + write_plist(app_entitlements, plan.app_entitlements) run([*common, "--entitlements", str(app_entitlements), str(app_path)], check=True) run(["codesign", "--verify", "--deep", "--strict", "--verbose=2", str(app_path)], check=True) @@ -141,12 +220,20 @@ def main(): parser.add_argument("app", type=Path) parser.add_argument("--app-profile", type=Path, required=True) parser.add_argument("--share-profile", type=Path) + parser.add_argument("--app-entitlements", type=Path, required=True) + parser.add_argument("--share-entitlements", type=Path) parser.add_argument("--identity", required=True) parser.add_argument("--keychain", type=Path, required=True) args = parser.parse_args() app_profile = load_profile(args.app_profile) share_profile = load_profile(args.share_profile) if args.share_profile else None - plan = create_plan(app_profile, share_profile, read_plist(args.app / "Info.plist").get("KometShareAppGroup")) + plan = create_plan( + app_profile, + share_profile, + read_plist(args.app / "Info.plist").get("KometShareAppGroup"), + read_plist(args.app_entitlements), + read_plist(args.share_entitlements) if args.share_entitlements else None, + ) share_path = prepare_app(args.app, plan, args.app_profile, args.share_profile) if plan.share is None: print("::notice::APPSTORE_SHARE_PROVISION_PROFILE_BASE64 is not set; building the app without Share Extension") diff --git a/scripts/validate_ios_appstore_metadata.py b/scripts/validate_ios_appstore_metadata.py new file mode 100644 index 00000000..b2240740 --- /dev/null +++ b/scripts/validate_ios_appstore_metadata.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Validate App Store metadata that Apple checks after upload.""" + +from pathlib import Path +import plistlib +import struct + +ROOT = Path(__file__).resolve().parents[1] +RUNNER = ROOT / "ios" / "Runner" +PLIST = RUNNER / "Info.plist" +PROJECT = ROOT / "ios" / "Runner.xcodeproj" / "project.pbxproj" + +PURPOSE_KEYS = ( + "NSLocationAlwaysAndWhenInUseUsageDescription", + "NSSpeechRecognitionUsageDescription", +) +IPAD_ALTERNATE_ICONS = { + "MinimalIcon-76@2x.png": (152, 152), + "MinimalIcon-83.5@2x.png": (167, 167), +} + + +def png_size(path: Path) -> tuple[int, int]: + with path.open("rb") as image: + signature = image.read(24) + if signature[:8] != b"\x89PNG\r\n\x1a\n" or signature[12:16] != b"IHDR": + raise AssertionError(f"{path} is not a PNG with an IHDR header") + return struct.unpack(">II", signature[16:24]) + + +def main() -> None: + with PLIST.open("rb") as source: + plist = plistlib.load(source) + + for key in PURPOSE_KEYS: + value = plist.get(key) + assert isinstance(value, str) and value.strip(), f"missing {key}" + + ipad_icons = plist.get("CFBundleIcons~ipad", {}) + alternate = ipad_icons.get("CFBundleAlternateIcons", {}).get("MinimalIcon", {}) + declared = set(alternate.get("CFBundleIconFiles", [])) + expected_names = {Path(name).stem.split("@", 1)[0] for name in IPAD_ALTERNATE_ICONS} + assert expected_names <= declared, ( + f"CFBundleIcons~ipad.MinimalIcon must declare {sorted(expected_names)}" + ) + + project = PROJECT.read_text() + for filename, expected_size in IPAD_ALTERNATE_ICONS.items(): + path = RUNNER / filename + assert path.is_file(), f"missing {path}" + assert png_size(path) == expected_size, ( + f"{path} is {png_size(path)}, expected {expected_size}" + ) + assert project.count(filename) >= 4, f"{filename} is not bundled by Runner" + + print("App Store metadata is complete") + + +if __name__ == "__main__": + main() diff --git a/test/account_id_resolution_test.dart b/test/account_id_resolution_test.dart new file mode 100644 index 00000000..6b733f9a --- /dev/null +++ b/test/account_id_resolution_test.dart @@ -0,0 +1,58 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/account/account_models.dart'; + +void main() { + test('uses account id from login response without a phone lookup', () async { + var lookedUp = false; + + final accountId = await resolveLoginAccountId( + { + 'profile': { + 'contact': {'id': 42}, + }, + }, + phone: '+7 999 171-65-36', + lookupByPhone: (_) async { + lookedUp = true; + return 99; + }, + ); + + expect(accountId, 42); + expect(lookedUp, isFalse); + }); + + test('falls back to phone lookup when login response omits account id', () async { + String? lookedUpPhone; + + final accountId = await resolveLoginAccountId( + { + 'time': 123, + 'config': {}, + }, + phone: '+7 999 171-65-36', + lookupByPhone: (phone) async { + lookedUpPhone = phone; + return 77; + }, + ); + + expect(accountId, 77); + expect(lookedUpPhone, '+7 999 171-65-36'); + }); + + test('does not attempt a fallback without a phone hint', () async { + var lookedUp = false; + + final accountId = await resolveLoginAccountId( + {'time': 123}, + lookupByPhone: (_) async { + lookedUp = true; + return 77; + }, + ); + + expect(accountId, isNull); + expect(lookedUp, isFalse); + }); +} diff --git a/test/app_text_scaler_test.dart b/test/app_text_scaler_test.dart new file mode 100644 index 00000000..2a5d106d --- /dev/null +++ b/test/app_text_scaler_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/config/app_fonts.dart'; + +void main() { + test( + 'the slider multiplies the system font size instead of replacing it', + () { + const system = TextScaler.linear(1.3); + expect(const AppTextScaler(system, 1.0).scale(10), closeTo(13, 1e-9)); + expect(const AppTextScaler(system, 1.1).scale(10), closeTo(14.3, 1e-9)); + expect(const AppTextScaler(system, 0.9).scale(10), closeTo(11.7, 1e-9)); + }, + ); + + test('a bigger slider value always means bigger text', () { + const system = TextScaler.linear(1.3); + final sizes = [ + for (var f = AppFonts.minScale; f <= AppFonts.maxScale; f += 0.05) + AppTextScaler(system, f).scale(16), + ]; + for (var i = 1; i < sizes.length; i++) { + expect(sizes[i], greaterThan(sizes[i - 1])); + } + }); + + test('equal settings compare equal so cached layouts survive rebuilds', () { + const a = AppTextScaler(TextScaler.linear(1.2), 1.05); + const b = AppTextScaler(TextScaler.linear(1.2), 1.05); + expect(a, b); + expect(a.hashCode, b.hashCode); + expect(a == const AppTextScaler(TextScaler.linear(1.2), 1.1), isFalse); + }); +} diff --git a/test/audio_file_metadata_test.dart b/test/audio_file_metadata_test.dart new file mode 100644 index 00000000..d001f17e --- /dev/null +++ b/test/audio_file_metadata_test.dart @@ -0,0 +1,69 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; +import 'package:komet/core/media/audio_file_metadata.dart'; +import 'package:komet/core/utils/media_cache.dart'; +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +class _SyntheticPathProvider extends PathProviderPlatform + with MockPlatformInterfaceMixin { + _SyntheticPathProvider(this.path); + + final String path; + + @override + Future getApplicationSupportPath() async => path; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'reads title, artist, album and embedded cover from an audio file', + () async { + final directory = Directory.systemTemp.createTempSync( + 'synthetic_audio_metadata', + ); + addTearDown(() { + AudioFileMetadata.resetForTesting(); + MediaCache.resetForTesting(); + if (directory.existsSync()) directory.deleteSync(recursive: true); + }); + PathProviderPlatform.instance = _SyntheticPathProvider(directory.path); + MediaCache.resetForTesting(); + AudioFileMetadata.resetForTesting(); + + final metadata = await AudioFileMetadata.read( + File('test/fixtures/audio_metadata.mp3'), + cacheName: 'synthetic-audio.mp3', + ); + + expect(metadata, isNotNull); + expect(metadata!.title, 'Synthetic Track'); + expect(metadata.artist, 'Synthetic Artist'); + expect(metadata.album, 'Synthetic Album'); + expect(metadata.artworkUri, isNotNull); + final artwork = File.fromUri(metadata.artworkUri!); + expect(await artwork.exists(), isTrue); + final decoded = img.decodeImage(await artwork.readAsBytes()); + expect(decoded, isNotNull); + expect(decoded!.width, 160); + expect(decoded.height, 160); + expect(AudioFileMetadata.parseCountForTesting, 1); + + await File( + 'test/fixtures/audio_metadata.mp3', + ).setLastModified(DateTime.now().add(const Duration(seconds: 1))); + AudioFileMetadata.resetMemoryForTesting(); + final cached = await AudioFileMetadata.read( + File('test/fixtures/audio_metadata.mp3'), + cacheName: 'synthetic-audio.mp3', + ); + expect(cached?.title, 'Synthetic Track'); + expect(cached?.artworkUri, metadata.artworkUri); + expect(AudioFileMetadata.parseCountForTesting, 1); + }, + ); +} diff --git a/test/auto_download_gate_test.dart b/test/auto_download_gate_test.dart new file mode 100644 index 00000000..84cfc25a --- /dev/null +++ b/test/auto_download_gate_test.dart @@ -0,0 +1,89 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/media/auto_download_gate.dart'; + +const _cached = 'https://cdn.invalid/cached.jpg'; +const _missing = 'https://cdn.invalid/missing.jpg'; + +Future _settle() => Future.delayed(Duration.zero); + +void main() { + setUp(() { + AutoDownloadGate.reset(); + AutoDownloadGate.isCached = (key) async => key == _cached; + }); + + test('auto-download on always allows without asking the cache', () { + var asked = false; + AutoDownloadGate.isCached = (_) async => asked = true; + expect(AutoDownloadGate.allows(true, _missing), isTrue); + expect(asked, isFalse); + }); + + test('a picture already in the cache opens without a tap', () async { + expect(AutoDownloadGate.allows(false, _cached), isFalse); + expect(AutoDownloadGate.awaitsTap(false, _cached), isFalse); + await _settle(); + expect(AutoDownloadGate.allows(false, _cached), isTrue); + expect(AutoDownloadGate.listen(_cached).value, ManualLoad.loaded); + }); + + test('a picture missing from the cache waits for a tap', () async { + expect(AutoDownloadGate.awaitsTap(false, _missing), isFalse); + await _settle(); + expect(AutoDownloadGate.awaitsTap(false, _missing), isTrue); + AutoDownloadGate.loadManually(_missing); + expect(AutoDownloadGate.allows(false, _missing), isTrue); + expect(AutoDownloadGate.awaitsTap(false, _missing), isFalse); + }); + + test( + 'a tap during the cache lookup is not overwritten by its answer', + () async { + expect(AutoDownloadGate.allows(false, _missing), isFalse); + AutoDownloadGate.loadManually(_missing); + await _settle(); + expect(AutoDownloadGate.allows(false, _missing), isTrue); + }, + ); + + test('a failing cache lookup falls back to the button', () async { + AutoDownloadGate.isCached = (_) async => throw StateError('disk'); + AutoDownloadGate.allows(false, _cached); + await _settle(); + expect(AutoDownloadGate.awaitsTap(false, _cached), isTrue); + }); + + test('idle entries are evicted once the gate is full', () async { + AutoDownloadGate.capacity = 3; + for (var i = 0; i < 10; i++) { + AutoDownloadGate.allows(false, 'https://cdn.invalid/$i.jpg'); + } + expect(AutoDownloadGate.size, 3); + await _settle(); + }); + + test('an entry a bubble listens to is never evicted', () async { + AutoDownloadGate.capacity = 2; + final watched = AutoDownloadGate.listen(_cached); + AutoDownloadGate.allows(false, _cached); + void onChange() {} + watched.addListener(onChange); + addTearDown(() => watched.removeListener(onChange)); + for (var i = 0; i < 10; i++) { + AutoDownloadGate.allows(false, 'https://cdn.invalid/$i.jpg'); + } + expect(identical(AutoDownloadGate.listen(_cached), watched), isTrue); + await _settle(); + expect(watched.value, ManualLoad.loaded); + }); + + test('an evicted picture asks the cache again when it comes back', () async { + AutoDownloadGate.capacity = 1; + AutoDownloadGate.loadManually(_missing); + AutoDownloadGate.allows(false, _cached); + await _settle(); + expect(AutoDownloadGate.allows(false, _missing), isFalse); + await _settle(); + expect(AutoDownloadGate.awaitsTap(false, _missing), isTrue); + }); +} diff --git a/test/cache_janitor_test.dart b/test/cache_janitor_test.dart new file mode 100644 index 00000000..1a3ccd0f --- /dev/null +++ b/test/cache_janitor_test.dart @@ -0,0 +1,182 @@ +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/cache/cache_janitor.dart'; +import 'package:komet/core/config/app_cache_limit.dart'; +import 'package:komet/core/utils/media_cache.dart'; +import 'package:komet/core/utils/media_cache_names.dart'; +import 'package:path/path.dart' as p; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + + setUpAll(() async { + root = await Directory.systemTemp.createTemp('komet-janitor-test-'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => root.path, + ); + }); + + tearDownAll(() => root.delete(recursive: true)); + + setUp(() { + for (final entity in root.listSync()) { + entity.deleteSync(recursive: true); + } + MediaCache.resetForTesting(); + CacheJanitor.instance.resetForTesting(); + }); + + tearDown(() { + CacheJanitor.instance.resetForTesting(); + AppCacheLimit.current.value = AppCacheLimit.defaultValue; + }); + + Future place(File file, int size, Duration age) async { + await file.parent.create(recursive: true); + await file.writeAsBytes(List.filled(size, 1)); + await file.setLastModified(DateTime.now().subtract(age)); + return file; + } + + Future media(String name, int size, Duration age) async => + place(await MediaCache.fileFor(name), size, age); + + Future image(String name, int size, Duration age) => + place(File(p.join(root.path, DefaultCacheManager.key, name)), size, age); + + Future frames(String name, int size, Duration age) => + place(File(p.join(root.path, 'tlottie_frames', name)), size, age); + + test('cache file names map to the kind of media they hold', () { + expect( + mediaCacheKindOf(avatarCacheName('https://cdn.test/a.jpg')), + MediaCacheKind.photo, + ); + expect(mediaCacheKindOf(videoPreviewCacheName(5)), MediaCacheKind.video); + expect(mediaCacheKindOf(gifCacheName(6)), MediaCacheKind.video); + expect(mediaCacheKindOf(storyVideoCacheName(1, 2)), MediaCacheKind.video); + expect( + mediaCacheKindOf(voiceCacheName(audioId: 7, messageId: '8')), + MediaCacheKind.voice, + ); + expect( + mediaCacheKindOf(voiceCacheName(messageId: '-3')), + MediaCacheKind.voice, + ); + expect(mediaCacheKindOf('12_track.ogg'), MediaCacheKind.file); + expect(mediaCacheKindOf('12_report.pdf'), MediaCacheKind.file); + expect( + mediaCacheKindOf(MediaCache.keptName('photo_1.jpg')), + MediaCacheKind.kept, + ); + }); + + test('trim drops the least recently used files across caches', () async { + AppCacheLimit.current.value = 100; + final oldVideo = await media('video_1.mp4', 60, const Duration(days: 3)); + final oldImage = await image('a.jpg', 60, const Duration(days: 2)); + final document = await media('1_doc.pdf', 30, const Duration(hours: 1)); + final fresh = await media('photo_9.jpg', 40, Duration.zero); + final kept = await media( + MediaCache.keptName('photo_2.jpg'), + 50, + const Duration(days: 10), + ); + + await CacheJanitor.instance.trim(); + + expect(await oldVideo.exists(), isFalse); + expect(await oldImage.exists(), isFalse); + expect(await document.exists(), isTrue); + expect(await fresh.exists(), isTrue); + expect(await kept.exists(), isTrue); + }); + + test('trim keeps everything when the cache is unlimited', () async { + AppCacheLimit.current.value = AppCacheLimit.unlimited; + final old = await media('video_1.mp4', 500, const Duration(days: 30)); + + await CacheJanitor.instance.trim(); + + expect(await old.exists(), isTrue); + }); + + test( + 'scan groups usage by kind and clear removes only chosen kinds', + () async { + const day = Duration(days: 1); + await media('photo_1.jpg', 10, day); + await media('video_1.mp4', 20, day); + await media('5.ogg', 30, day); + await media('7_archive.zip', 40, day); + await media(MediaCache.keptName('video_2.mp4'), 50, day); + await image('b.webp', 60, day); + await image('c.json', 70, day); + await frames('x_256.ktlf', 80, day); + + final report = await CacheJanitor.instance.scan(); + expect(report.of(StorageCategory.photos), 70); + expect(report.of(StorageCategory.videos), 20); + expect(report.of(StorageCategory.voice), 30); + expect(report.of(StorageCategory.files), 40); + expect(report.of(StorageCategory.keptMedia), 50); + expect(report.of(StorageCategory.stickers), 150); + + final (:freed, report: cleared) = await CacheJanitor.instance.clear({ + StorageCategory.videos, + StorageCategory.stickers, + StorageCategory.database, + }); + expect(freed, 170); + expect(cleared.of(StorageCategory.videos), 0); + expect(cleared.of(StorageCategory.stickers), 0); + + final after = await CacheJanitor.instance.scan(); + expect(after.of(StorageCategory.videos), 0); + expect(after.of(StorageCategory.stickers), 0); + expect(after.of(StorageCategory.photos), 70); + expect(after.of(StorageCategory.keptMedia), 50); + }, + ); + + test('a write within the limit does not schedule a full pass', () { + AppCacheLimit.current.value = 1000; + final janitor = CacheJanitor.instance; + + janitor.noteWrite(CacheStore.media, 10); + expect( + janitor.debugPassScheduled, + isTrue, + reason: 'an unmeasured cache is measured once', + ); + + janitor.resetForTesting(); + janitor.debugMeasured({CacheStore.media: 100}); + janitor.noteWrite(CacheStore.media, 10); + expect( + janitor.debugPassScheduled, + isFalse, + reason: 'still under the limit, nothing to scan', + ); + + janitor.noteWrite(CacheStore.images, 950); + expect(janitor.debugPassScheduled, isTrue, reason: 'over the limit'); + }); + + test('clearing a downloaded file updates its presence flag', () async { + await media('3_notes.txt', 10, const Duration(days: 1)); + final presence = MediaCache.presence('3_notes.txt'); + await MediaCache.existing('3_notes.txt'); + expect(presence.value, isTrue); + + await CacheJanitor.instance.clear({StorageCategory.files}); + + expect(presence.value, isFalse); + }); +} diff --git a/test/call_out_controller_test.dart b/test/call_out_controller_test.dart new file mode 100644 index 00000000..e22947f5 --- /dev/null +++ b/test/call_out_controller_test.dart @@ -0,0 +1,198 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/account.dart'; +import 'package:komet/core/protocol/packet.dart'; +import 'package:komet/frontend/screens/auth/call_out_controller.dart'; + +const _params = CallOutParams( + trackId: 'track-1', + ttl: Duration(minutes: 5), + pollingInterval: Duration(seconds: 2), +); + +class _FakeServer { + final List answers; + final List asked = []; + + _FakeServer(this.answers); + + Future check(String trackId) async { + asked.add(trackId); + final answer = answers.length > 1 ? answers.removeAt(0) : answers.first; + if (answer is CallOutCheck) return answer; + throw answer; + } +} + +CallOutCheck _status(CallOutStatus status, [String? number]) => + CallOutCheck(status: status, callNumber: number); + +void main() { + group('callOutParams из ответа AUTH_REQUEST', () { + test('полный набор полей даёт параметры звонка в миллисекундах', () { + final params = CallOutParams.tryParse({ + 'trackId': 'abc', + 'ttl': 300000, + 'pollingInterval': 3000, + }); + + expect(params, isNotNull); + expect(params!.trackId, 'abc'); + expect(params.ttl, const Duration(minutes: 5)); + expect(params.pollingInterval, const Duration(seconds: 3)); + }); + + test('без trackId или с нулевым ttl звонка нет', () { + expect( + CallOutParams.tryParse({'ttl': 1000, 'pollingInterval': 1000}), + isNull, + ); + expect( + CallOutParams.tryParse({ + 'trackId': 'abc', + 'ttl': 0, + 'pollingInterval': 1000, + }), + isNull, + ); + expect(CallOutParams.tryParse(null), isNull); + }); + }); + + group('ответ AUTH_CHECK_CALL', () { + test('статусы читаются по коду', () { + expect( + CallOutCheck.fromPayload({ + 'status': 1, + 'callNumber': '+70000000000', + }).status, + CallOutStatus.numberAssigned, + ); + expect( + CallOutCheck.fromPayload({'status': 2}).status, + CallOutStatus.verificationPassed, + ); + expect(CallOutCheck.fromPayload({'status': 9}).status, isNull); + }); + + test('пустой номер считается отсутствующим', () { + expect( + CallOutCheck.fromPayload({'status': 1, 'callNumber': ''}).callNumber, + isNull, + ); + }); + }); + + group('опрос звонка', () { + testWidgets('номер выдан, звонок принят — опрос останавливается', ( + tester, + ) async { + final server = _FakeServer([ + _status(CallOutStatus.numberNotAssigned), + _status(CallOutStatus.numberAssigned, '+70000000001'), + _status(CallOutStatus.verificationPassed), + ]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + expect(controller.phase, CallOutPhase.waitingForNumber); + + await tester.pump(_params.pollingInterval); + expect(controller.phase, CallOutPhase.awaitingCall); + expect(controller.callNumber, '+70000000001'); + + await tester.pump(_params.pollingInterval); + expect(controller.phase, CallOutPhase.verified); + + final asked = server.asked.length; + await tester.pump(_params.pollingInterval * 3); + expect(server.asked.length, asked); + expect(server.asked, everyElement('track-1')); + + controller.dispose(); + }); + + testWidgets('обрыв связи не прерывает опрос', (tester) async { + final server = _FakeServer([ + StateError('AccountModule: сессия не онлайн'), + _status(CallOutStatus.numberAssigned, '+70000000002'), + ]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + expect(controller.phase, CallOutPhase.waitingForNumber); + + await tester.pump(_params.pollingInterval); + expect(controller.phase, CallOutPhase.awaitingCall); + + controller.dispose(); + }); + + testWidgets('ошибка сервера останавливает опрос', (tester) async { + final server = _FakeServer([const PacketError('Трек не найден')]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + expect(controller.phase, CallOutPhase.failed); + expect(controller.error, isA()); + + await tester.pump(_params.pollingInterval * 3); + expect(server.asked, hasLength(1)); + + controller.dispose(); + }); + + testWidgets('таймаут на сервере — номер надо обновить', (tester) async { + final server = _FakeServer([_status(CallOutStatus.verificationTimeout)]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + expect(controller.phase, CallOutPhase.expired); + expect(controller.remaining.value, Duration.zero); + + controller.dispose(); + }); + + testWidgets('новый номер сбрасывает прошлое состояние', (tester) async { + final server = _FakeServer([ + _status(CallOutStatus.verificationTimeout), + _status(CallOutStatus.numberAssigned, '+70000000003'), + ]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + expect(controller.phase, CallOutPhase.expired); + + controller.restart( + const CallOutParams( + trackId: 'track-2', + ttl: Duration(minutes: 5), + pollingInterval: Duration(seconds: 2), + ), + ); + await tester.pump(); + expect(controller.phase, CallOutPhase.awaitingCall); + expect(controller.trackId, 'track-2'); + expect(server.asked.last, 'track-2'); + + controller.dispose(); + }); + + testWidgets('после dispose запросов больше нет', (tester) async { + final server = _FakeServer([_status(CallOutStatus.numberNotAssigned)]); + final controller = CallOutController(params: _params, check: server.check) + ..start(); + + await tester.pump(); + controller.dispose(); + final asked = server.asked.length; + + await tester.pump(_params.pollingInterval * 3); + expect(server.asked.length, asked); + }); + }); +} diff --git a/test/call_permissions_test.dart b/test/call_permissions_test.dart new file mode 100644 index 00000000..0ab7abcf --- /dev/null +++ b/test/call_permissions_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/calls/call_permissions.dart'; +import 'package:permission_handler/permission_handler.dart'; + +void main() { + test('an already granted microphone is not requested again', () async { + var requests = 0; + final access = await CallPermissions.ensureMicrophone( + needsRuntimePermission: true, + readStatus: () async => PermissionStatus.granted, + request: () async { + requests++; + return PermissionStatus.granted; + }, + ); + + expect(access, CallMicrophoneAccess.granted); + expect(requests, 0); + }); + + test('a denied microphone is requested before the call starts', () async { + var requests = 0; + final access = await CallPermissions.ensureMicrophone( + needsRuntimePermission: true, + readStatus: () async => PermissionStatus.denied, + request: () async { + requests++; + return PermissionStatus.granted; + }, + ); + + expect(access, CallMicrophoneAccess.granted); + expect(requests, 1); + }); + + test('a permanently denied microphone produces a specific failure', () async { + await expectLater( + CallPermissions.requireMicrophone( + needsRuntimePermission: true, + readStatus: () async => PermissionStatus.permanentlyDenied, + request: () async => PermissionStatus.permanentlyDenied, + ), + throwsA( + isA().having( + (error) => error.access, + 'access', + CallMicrophoneAccess.permanentlyDenied, + ), + ), + ); + }); + + test( + 'platforms without runtime microphone permissions skip the prompt', + () async { + var reads = 0; + var requests = 0; + final access = await CallPermissions.ensureMicrophone( + needsRuntimePermission: false, + readStatus: () async { + reads++; + return PermissionStatus.denied; + }, + request: () async { + requests++; + return PermissionStatus.denied; + }, + ); + + expect(access, CallMicrophoneAccess.granted); + expect(reads, 0); + expect(requests, 0); + }, + ); +} diff --git a/test/channel_post_bubble_test.dart b/test/channel_post_bubble_test.dart new file mode 100644 index 00000000..51cfe370 --- /dev/null +++ b/test/channel_post_bubble_test.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/frontend/widgets/message_bubble.dart'; +import 'package:komet/frontend/widgets/sending_clock_icon.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:material_symbols_icons/symbols.dart'; + +const int _me = 900401; +const int _otherAdmin = 900402; +const int _channelId = -900501; +const String _channel = 'Синтетический канал'; +const double _width = 432; + +CachedMessage _post({ + String id = '1', + int sender = _me, + String text = 'Первый пост', + String status = 'sent', + int minute = 0, +}) => CachedMessage( + id: id, + accountId: _me, + chatId: _channelId, + senderId: sender, + text: text, + time: DateTime(2026, 1, 1, 12, minute).millisecondsSinceEpoch, + status: status, +); + +MessageBubble _channelBubble( + CachedMessage message, { + CachedMessage? prev, + CachedMessage? next, +}) => MessageBubble( + message: message, + isMe: message.senderId == _me, + channelPost: true, + myId: _me, + chatType: 'CHANNEL', + peerName: _channel, + senderNameOverride: _channel, + prevMessage: prev, + nextMessage: next, +); + +Future _pump(WidgetTester tester, List bubbles) async { + tester.view + ..devicePixelRatio = 1 + ..physicalSize = const Size(_width, 800); + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: Column(children: bubbles)), + ), + ); + await tester.pump(); +} + +bool _onLeft(WidgetTester tester, String text) => + tester.getCenter(find.text(text)).dx < _width / 2; + +void main() { + testWidgets('own channel post sits on the left under the channel name', ( + tester, + ) async { + await _pump(tester, [_channelBubble(_post())]); + + expect(_onLeft(tester, 'Первый пост'), isTrue); + expect(find.text(_channel), findsOneWidget); + expect(find.byIcon(Symbols.check), findsNothing); + expect(find.byIcon(Symbols.done_all), findsNothing); + }); + + testWidgets('own channel post still shows that it is being sent or failed', ( + tester, + ) async { + await _pump(tester, [ + _channelBubble(_post(status: 'sending')), + _channelBubble(_post(id: '2', text: 'Второй пост', status: 'error')), + ]); + + expect(find.byType(SendingClockIcon), findsOneWidget); + expect(find.byIcon(Symbols.error), findsOneWidget); + }); + + testWidgets('posts of different admins read as one channel', (tester) async { + final mine = _post(); + final theirs = _post( + id: '2', + sender: _otherAdmin, + text: 'Второй пост', + minute: 1, + ); + await _pump(tester, [ + _channelBubble(mine, next: theirs), + _channelBubble(theirs, prev: mine), + ]); + + expect(_onLeft(tester, 'Первый пост'), isTrue); + expect(_onLeft(tester, 'Второй пост'), isTrue); + expect(find.text(_channel), findsOneWidget); + }); + + testWidgets('own message outside a channel stays on the right', ( + tester, + ) async { + await _pump(tester, [ + MessageBubble( + message: _post(text: 'Обычное сообщение'), + isMe: true, + myId: _me, + chatType: 'DIALOG', + ), + ]); + + expect(_onLeft(tester, 'Обычное сообщение'), isFalse); + expect(find.byIcon(Symbols.check), findsOneWidget); + }); +} diff --git a/test/channel_recommendations_test.dart b/test/channel_recommendations_test.dart new file mode 100644 index 00000000..2e50313d --- /dev/null +++ b/test/channel_recommendations_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/core/config/komet_settings.dart'; +import 'package:komet/frontend/screens/chats/chat/channel_recommendations.dart'; +import 'package:komet/frontend/screens/chats/chat/view/channel_recommendations_view.dart'; +import 'package:komet/frontend/widgets/message_bubble.dart'; +import 'package:komet/frontend/widgets/small_spinner.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:komet/models/suggested_channel.dart'; +import 'package:material_symbols_icons/symbols.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const int _channelId = -900601; +const String _title = 'Рекомендуемые каналы'; +const String _join = 'Подписаться'; +const String _open = 'Открыть'; + +const List _channels = [ + SuggestedChannel( + id: -900602, + title: 'Синтетический канал А', + link: 'https://example.test/channel_a', + subscribers: 3663, + ), + SuggestedChannel( + id: -900603, + title: 'Синтетический канал Б', + link: 'https://example.test/channel_b', + subscribers: 129812, + ), +]; + +Future _pump(WidgetTester tester, Widget child) async { + tester.view + ..devicePixelRatio = 1 + ..physicalSize = const Size(400, 700); + addTearDown(tester.view.reset); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Align(alignment: Alignment.bottomCenter, child: child), + ), + ), + ); +} + +ChannelRecommendations _recommendations({ + Future Function(SuggestedChannel channel)? join, +}) { + final recommendations = ChannelRecommendations( + chatId: _channelId, + fetch: () async => _channels, + join: join ?? (_) async {}, + ); + addTearDown(recommendations.dispose); + return recommendations; +} + +double _blockHeight(WidgetTester tester) => + tester.getSize(find.byType(ChannelRecommendationsView)).height; + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + KometSettings.hideChannelRecommendations.value = false; + KometSettings.recommendationsHiddenIn.value = const {}; + }); + + testWidgets('the block slides in once the channels arrive', (tester) async { + final recommendations = _recommendations(); + await _pump( + tester, + ChannelRecommendationsView(recommendations: recommendations), + ); + expect(_blockHeight(tester), 0); + + await recommendations.load(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + final midway = _blockHeight(tester); + await tester.pumpAndSettle(); + + expect(midway, inExclusiveRange(0, _blockHeight(tester))); + expect(find.text(_title), findsOneWidget); + expect(find.text('Синтетический канал А'), findsOneWidget); + expect(find.text('3,7K'), findsOneWidget); + expect(find.text('129,8K'), findsOneWidget); + }); + + testWidgets('joining shows progress and then offers to open the channel', ( + tester, + ) async { + final joining = Completer(); + final joined = []; + final recommendations = _recommendations( + join: (channel) { + joined.add(channel.id); + return joining.future; + }, + ); + await recommendations.load(); + await _pump( + tester, + ChannelRecommendationsView(recommendations: recommendations), + ); + + await tester.tap(find.text(_join).first); + await tester.pump(); + expect(joined, [-900602]); + expect(find.byType(SmallSpinner), findsOneWidget); + + joining.complete(); + await tester.pumpAndSettle(); + expect(find.text(_open), findsOneWidget); + expect(find.text(_join), findsOneWidget); + }); + + testWidgets('a failed join puts the button back', (tester) async { + final recommendations = _recommendations( + join: (_) async => throw StateError('synthetic'), + ); + await recommendations.load(); + await _pump( + tester, + ChannelRecommendationsView(recommendations: recommendations), + ); + + await tester.tap(find.text(_join).first); + await tester.pumpAndSettle(); + + expect(find.text(_join), findsNWidgets(2)); + expect(find.text('Не удалось подписаться'), findsOneWidget); + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); + }); + + testWidgets('the close button folds the block away and remembers it', ( + tester, + ) async { + final recommendations = _recommendations(); + await recommendations.load(); + await _pump( + tester, + ChannelRecommendationsView(recommendations: recommendations), + ); + final full = _blockHeight(tester); + + await tester.tap(find.byIcon(Symbols.close)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 120)); + final folding = _blockHeight(tester); + await tester.pump(const Duration(milliseconds: 300)); + + expect(folding, inExclusiveRange(0, full)); + expect(_blockHeight(tester), 0); + expect(KometSettings.recommendationsHiddenIn.value, {_channelId}); + final prefs = await SharedPreferences.getInstance(); + expect(prefs.getStringList('komet_recommendations_hidden_in'), [ + '$_channelId', + ]); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + }); + + testWidgets('the Komet switch hides recommendations everywhere', ( + tester, + ) async { + final recommendations = _recommendations(); + await recommendations.load(); + await _pump( + tester, + ChannelRecommendationsView(recommendations: recommendations), + ); + expect(_blockHeight(tester), greaterThan(0)); + + await KometSettings.setHideChannelRecommendations(true); + await tester.pumpAndSettle(); + expect(_blockHeight(tester), 0); + + final another = _recommendations(); + await another.load(); + expect(another.visible, isFalse); + expect(another.channels, isEmpty); + }); + + testWidgets('a channel post shows its views before the time', (tester) async { + final views = ValueNotifier(null); + addTearDown(views.dispose); + await _pump( + tester, + MessageBubble( + message: CachedMessage( + id: '900701', + accountId: 1, + chatId: _channelId, + senderId: 2, + text: 'Синтетический пост', + time: DateTime(2026, 1, 1, 12).millisecondsSinceEpoch, + status: 'sent', + ), + isMe: false, + channelPost: true, + views: views, + myId: 1, + chatType: 'CHANNEL', + peerName: 'Синтетический канал', + ), + ); + expect(find.byIcon(Symbols.visibility), findsNothing); + + views.value = 8948; + await tester.pump(); + + expect(find.byIcon(Symbols.visibility), findsOneWidget); + expect(find.text('8,9K'), findsOneWidget); + }); +} diff --git a/test/channel_stats_test.dart b/test/channel_stats_test.dart new file mode 100644 index 00000000..3147b61a --- /dev/null +++ b/test/channel_stats_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/channel_stats.dart'; +import 'package:komet/backend/modules/channel_suggestions.dart'; +import 'package:komet/core/utils/format.dart'; + +const int _channelId = -900601; + +Map _channel(int id, {String type = 'CHANNEL'}) => { + 'id': id, + 'type': type, + 'title': 'Синтетический канал $id', + 'baseIconUrl': 'https://example.test/icon/$id.png', + 'link': 'https://example.test/channel_$id', + 'participantsCount': 3663, +}; + +void main() { + group('views', () { + test('ask with numeric ids the way the server validates them', () { + final payload = ChannelStats.requestPayload(_channelId, [ + '115000000000000001', + 'temp_1_1700000000000', + '900701', + ], countView: true); + + expect(payload, { + 'chatId': _channelId, + 'messageIds': [115000000000000001, 900701], + }); + }); + + test('only read the counters when the view must not count', () { + final payload = ChannelStats.requestPayload(_channelId, [ + '900701', + ], countView: false); + + expect(payload['readOnly'], isTrue); + }); + + test('never ask for more than the server accepts at once', () { + final payload = ChannelStats.requestPayload(_channelId, [ + for (var i = 0; i < ChannelStats.maxBatch + 20; i++) '${900000 + i}', + ], countView: true); + + expect(payload['messageIds'], hasLength(ChannelStats.maxBatch)); + }); + + test('are read per message id from the stats map', () { + expect( + ChannelStats.parseViews({ + 'stats': { + '900701': {'views': 8948}, + '900702': {'views': 0}, + '900703': {'reactions': 4}, + }, + }), + {'900701': 8948, '900702': 0}, + ); + }); + + test('an unexpected answer gives no views', () { + expect(ChannelStats.parseViews(null), isEmpty); + expect(ChannelStats.parseViews({'stats': 'nope'}), isEmpty); + }); + }); + + group('recommendations', () { + test('keep channels with a link and drop the current one', () { + final channels = ChannelSuggestions.parse({ + 'chats': [ + _channel(_channelId), + _channel(-900602), + _channel(-900603, type: 'CHAT'), + {..._channel(-900604), 'link': null}, + _channel(-900605), + ], + 'recomId': 'synthetic', + }, exclude: _channelId); + + expect(channels.map((c) => c.id), [-900602, -900605]); + expect(channels.first.title, 'Синтетический канал -900602'); + expect(channels.first.subscribers, 3663); + expect(channels.first.iconUrl, 'https://example.test/icon/-900602.png'); + }); + + test('an unexpected answer gives no channels', () { + expect(ChannelSuggestions.parse(null, exclude: _channelId), isEmpty); + }); + }); + + test('counts are shortened the way MAX shows them', () { + expect(formatCompactCount(623), '623'); + expect(formatCompactCount(1000), '1K'); + expect(formatCompactCount(3663), '3,7K'); + expect(formatCompactCount(8948), '8,9K'); + expect(formatCompactCount(129812), '129,8K'); + expect(formatCompactCount(175155), '175,2K'); + expect(formatCompactCount(999950), '1M'); + expect(formatCompactCount(2450000), '2,5M'); + }); +} diff --git a/test/channel_views_test.dart b/test/channel_views_test.dart new file mode 100644 index 00000000..9a4bc6d7 --- /dev/null +++ b/test/channel_views_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/screens/chats/chat/channel_views.dart'; + +void main() { + late List> requests; + late List counted; + late DateTime now; + late ChannelViews views; + + setUp(() { + requests = []; + counted = []; + now = DateTime(2026, 1, 1, 12); + views = ChannelViews((ids, {required count}) async { + requests.add(ids); + if (count) counted.addAll(ids); + return {for (final id in ids) id: int.parse(id) % 1000}; + }, clock: () => now); + }); + + tearDown(() => views.dispose()); + + testWidgets('posts seen together are asked for in one request', ( + tester, + ) async { + final first = views.of('900801'); + final second = views.of('900802'); + views.of('900802'); + + expect(requests, isEmpty); + await tester.pump(ChannelViews.batchDelay); + + expect(requests, [ + ['900801', '900802'], + ]); + expect(first.value, 801); + expect(second.value, 802); + }); + + testWidgets('unsent posts are not asked for', (tester) async { + final pending = views.of('temp_1_1700000000000'); + await tester.pump(ChannelViews.batchDelay); + + expect(requests, isEmpty); + expect(pending.value, isNull); + }); + + testWidgets('views are refreshed only after a minute', (tester) async { + views.of('900801'); + await tester.pump(ChannelViews.batchDelay); + + views.of('900801'); + await tester.pump(ChannelViews.batchDelay); + expect(requests, hasLength(1)); + + now = now.add(ChannelViews.freshFor); + views.of('900801'); + await tester.pump(ChannelViews.batchDelay); + expect(requests, hasLength(2)); + expect(counted, ['900801']); + }); + + testWidgets('a refused request stops asking in this chat', (tester) async { + var calls = 0; + final refusing = ChannelViews((ids, {required count}) async { + calls++; + return null; + }); + addTearDown(refusing.dispose); + + refusing.of('900801'); + await tester.pump(ChannelViews.batchDelay); + refusing.of('900802'); + await tester.pump(ChannelViews.batchDelay); + + expect(calls, 1); + }); + + testWidgets('a long scroll is split into batches', (tester) async { + for (var i = 0; i < ChannelViews.batchSize + 5; i++) { + views.of('${900900 + i}'); + } + await tester.pump(ChannelViews.batchDelay); + await tester.pump(ChannelViews.batchDelay); + + expect(requests.map((batch) => batch.length), [ChannelViews.batchSize, 5]); + }); +} diff --git a/test/chat_bar_alignment_test.dart b/test/chat_bar_alignment_test.dart index 41425899..b9e09dbe 100644 --- a/test/chat_bar_alignment_test.dart +++ b/test/chat_bar_alignment_test.dart @@ -84,6 +84,7 @@ void main() { body: Align( alignment: Alignment.bottomCenter, child: ComposerInputBar( + bottomPadding: 0, chatType: 'DIALOG', chrome: ChatChromeStyle.none, vignette: true, diff --git a/test/chat_list_stamp_test.dart b/test/chat_list_stamp_test.dart new file mode 100644 index 00000000..441fb6c9 --- /dev/null +++ b/test/chat_list_stamp_test.dart @@ -0,0 +1,38 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/utils/format.dart'; +import 'package:komet/l10n/app_localizations.dart'; + +void main() { + final ru = lookupAppLocalizations(const Locale('ru')); + final en = lookupAppLocalizations(const Locale('en')); + final now = DateTime(2026, 11, 7, 15, 30); + + String stamp(AppLocalizations l10n, DateTime dt) => + formatChatListStamp(l10n, dt, now: now); + + test('today shows the clock', () { + expect(stamp(ru, DateTime(2026, 11, 7, 0, 5)), '00:05'); + expect(stamp(ru, DateTime(2026, 11, 7, 14, 10)), '14:10'); + }); + + test('a message from a skewed clock in the future still shows the clock', () { + expect(stamp(ru, DateTime(2026, 11, 8, 0, 1)), '00:01'); + }); + + test('the last six days show the weekday', () { + expect(stamp(ru, DateTime(2026, 11, 6, 23, 59)), 'пт'); + expect(stamp(en, DateTime(2026, 11, 2, 9)), 'Mon'); + expect(stamp(ru, DateTime(2026, 11, 1, 12)), 'вс'); + }); + + test('a week or more ago in this year shows day and month', () { + expect(stamp(ru, DateTime(2026, 10, 31, 12)), '31 окт'); + expect(stamp(en, DateTime(2026, 1, 5, 12)), '5 Jan'); + }); + + test('earlier years show the full date', () { + expect(stamp(ru, DateTime(2025, 8, 5, 12)), '05.08.2025'); + expect(stamp(en, DateTime(2025, 12, 31, 23, 59)), '31.12.2025'); + }); +} diff --git a/test/chat_text_send_controller_test.dart b/test/chat_text_send_controller_test.dart index 638f8cd5..1fc92b2a 100644 --- a/test/chat_text_send_controller_test.dart +++ b/test/chat_text_send_controller_test.dart @@ -252,6 +252,31 @@ void main() { expect((await chats.getChat(101, 303)).single.lastMsgStatus, 'pending'); }); + test('a rejected message goes back to the outbox on retry', () async { + final harness = _Harness(); + addTearDown(harness.dispose); + final sending = harness.sender.sendTextMessage(); + await harness.api.started.future; + harness.api.response.completeError( + const PacketError('Synthetic rejection'), + ); + await sending; + final failed = harness.chat.messages.single; + harness.chat.persistSessionCache(); + expect(failed.status, 'error'); + expect(harness.sender.canRetry(failed), isTrue); + expect(await AppDatabase.loadPendingMessages(101), isEmpty); + + await harness.sender.retry(failed); + + final queued = harness.chat.messages.single; + expect(queued.status, 'pending'); + expect(queued.id, failed.id); + expect(harness.sender.canRetry(queued), isFalse); + expect(await AppDatabase.loadPendingMessages(101), hasLength(1)); + expect(MessageSessionCache.get(101, 303)!.messages.single.status, 'pending'); + }); + test('a failed comment stays outside the ordinary message outbox', () async { final harness = _Harness(commentsMode: true); addTearDown(harness.dispose); diff --git a/test/chat_wallpaper_test.dart b/test/chat_wallpaper_test.dart new file mode 100644 index 00000000..67f6000f --- /dev/null +++ b/test/chat_wallpaper_test.dart @@ -0,0 +1,213 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/config/chat_wallpaper_themes.dart'; +import 'package:komet/core/storage/chat_wallpaper_store.dart'; +import 'package:komet/core/storage/per_chat_json_store.dart'; +import 'package:komet/frontend/widgets/chat_wallpaper_sheet.dart'; +import 'package:komet/frontend/widgets/theme_wallpaper.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:material_symbols_icons/symbols.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const int _account = 900901; +const int _chat = 900902; +const int _otherChat = 900903; +const List _colors = [Color(0xFF223344), Color(0xFF556677)]; + +const String _none = 'Без обоев'; +const String _inherit = 'Как у всех'; +const String _current = 'Текущие'; +const String _apply = 'Применить'; + +Future _pick( + WidgetTester tester, { + required ChatWallpaper? current, + ChatWallpaper? inherited, + bool perChat = false, + required Future Function() choose, +}) async { + WallpaperPick? result; + var closed = false; + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + result = await showChatWallpaperSheet( + context, + current: current, + inherited: inherited, + perChat: perChat, + ); + closed = true; + }, + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + await choose(); + await tester.pumpAndSettle(); + expect(closed, isTrue); + return result; +} + +FilledButton _applyButton(WidgetTester tester) => tester.widget( + find.ancestor(of: find.text(_apply), matching: find.byType(FilledButton)), +); + +void main() { + group('store', () { + final store = ChatWallpaperStore.instance; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + await store.clearAll(); + await store.load(); + }); + + test('no wallpaper in a chat beats the wallpaper of all chats', () async { + await store.setGradient(_account, kGlobalWallpaperChatId, _colors); + await store.setNone(_account, _chat); + + expect(store.effective(_account, _chat), isNull); + expect(store.effective(_account, _otherChat)?.gradientColors, _colors); + }); + + test('going back to default inherits the wallpaper of all chats', () async { + await store.setGradient(_account, kGlobalWallpaperChatId, _colors); + await store.setNone(_account, _chat); + await store.clear(_account, _chat); + + expect(store.effective(_account, _chat)?.gradientColors, _colors); + }); + + test('no wallpaper is saved as such', () async { + await store.setNone(_account, _chat); + await PerChatJsonStore.flushAll(); + + final prefs = await SharedPreferences.getInstance(); + final saved = jsonDecode(prefs.getString('chat_wallpapers')!) as Map; + expect(saved['$_account/$_chat'], {'none': true}); + }); + }); + + test('retired presets open as their strict replacements', () { + expect(chatWallpaperThemeById('ocean')?.id, 'ink'); + expect(chatWallpaperThemeById('rose')?.id, 'powder'); + expect(chatWallpaperThemeById('graphite')?.id, 'graphite'); + expect(chatWallpaperThemeById('unknown'), isNull); + }); + + group('gallery', () { + testWidgets('a gradient is shown as current and can be turned off', ( + tester, + ) async { + final pick = await _pick( + tester, + current: const ChatWallpaper.gradient(_colors), + perChat: true, + choose: () async { + expect(find.text(_current), findsOneWidget); + expect(_applyButton(tester).onPressed, isNull); + await tester.tap(find.text(_none)); + await tester.pumpAndSettle(); + expect(_applyButton(tester).onPressed, isNotNull); + await tester.tap(find.text(_apply)); + }, + ); + + expect(pick?.type, WallpaperPickType.none); + }); + + testWidgets('a chat without its own wallpaper starts from the default', ( + tester, + ) async { + final pick = await _pick( + tester, + current: null, + inherited: const ChatWallpaper.gradient(_colors), + perChat: true, + choose: () async { + expect(find.text(_inherit), findsOneWidget); + expect(_applyButton(tester).onPressed, isNull); + await tester.tap(find.text('Хвоя')); + await tester.pumpAndSettle(); + await tester.tap(find.text(_apply)); + }, + ); + + expect(pick?.type, WallpaperPickType.theme); + expect(pick?.theme?.id, 'pine'); + }); + + testWidgets('the explicit none of a chat can go back to the default', ( + tester, + ) async { + final pick = await _pick( + tester, + current: const ChatWallpaper.none(), + perChat: true, + choose: () async { + await tester.tap(find.text(_inherit)); + await tester.pumpAndSettle(); + await tester.tap(find.text(_apply)); + }, + ); + + expect(pick?.type, WallpaperPickType.inherit); + }); + + testWidgets('the wallpaper of all chats has no default to fall back to', ( + tester, + ) async { + await _pick( + tester, + current: null, + choose: () async { + expect(find.text(_inherit), findsNothing); + expect(_applyButton(tester).onPressed, isNull); + await tester.tap(find.byIcon(Symbols.arrow_back)); + }, + ); + }); + }); + + group('pattern', () { + testWidgets('a resize within one step reuses the rendered pattern', ( + tester, + ) async { + final pattern = kChatWallpaperThemes + .firstWhere((theme) => theme.pattern != null) + .pattern!; + await tester.runAsync(() => WallpaperPatternLayer.load(pattern.asset)); + + Future renderedAt(Size size) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(devicePixelRatio: 2), + child: Center( + child: SizedBox.fromSize( + size: size, + child: WallpaperPatternLayer(pattern: pattern), + ), + ), + ), + ); + return tester.widget(find.byType(RawImage)).image; + } + + final first = await renderedAt(const Size(300, 600)); + expect(first, isNotNull); + expect(await renderedAt(const Size(310, 620)), same(first)); + expect(await renderedAt(const Size(520, 620)), isNot(same(first))); + }); + }); +} diff --git a/test/cloud_storage_paging_test.dart b/test/cloud_storage_paging_test.dart new file mode 100644 index 00000000..aed70f06 --- /dev/null +++ b/test/cloud_storage_paging_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/api.dart'; +import 'package:komet/backend/modules/cloud_storage.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/models/attachment.dart'; + +const int _account = 900001; +const int _chat = -900201; + +class _SyntheticHistory extends MessagesModule { + _SyntheticHistory(this.times) : super(Api()); + + final List times; + + @override + Future> fetchHistory( + int accountId, + int chatId, { + int? fromTime, + int count = 50, + int forward = 0, + int? backward, + }) async { + final upTo = fromTime ?? 1 << 50; + final window = [ + for (final t in times) + if (t <= upTo) t, + ]; + final start = window.length > count ? window.length - count : 0; + return [ + for (final t in window.sublist(start)) + CachedMessage( + id: '$t', + accountId: accountId, + chatId: chatId, + senderId: accountId, + time: t, + attachments: [FileAttachment(fileId: t, name: 'synthetic_$t.bin')], + ), + ]; + } +} + +void main() { + test('pages walk back through the whole storage without repeats', () async { + final history = _SyntheticHistory([for (var t = 1; t <= 250; t++) t]); + final seen = []; + int? before; + var pages = 0; + while (true) { + final page = await CloudStorageModule.fetchPage( + history, + _account, + _chat, + before: before, + ); + if (page.oldestTime == null) break; + seen.addAll(page.files.map((f) => f.fileId!)); + before = page.oldestTime; + pages++; + } + expect(pages, 3); + expect(seen, [for (var t = 250; t >= 1; t--) t]); + }); + + test('an empty storage reports no older page', () async { + final page = await CloudStorageModule.fetchPage( + _SyntheticHistory(const []), + _account, + _chat, + ); + expect(page.files, isEmpty); + expect(page.oldestTime, isNull); + }); +} diff --git a/test/composer_attach_button_test.dart b/test/composer_attach_button_test.dart index 82973cc8..4c00b084 100644 --- a/test/composer_attach_button_test.dart +++ b/test/composer_attach_button_test.dart @@ -55,6 +55,7 @@ void main() { composerContext = context; return Scaffold( bottomNavigationBar: ComposerInputBar( + bottomPadding: 0, chatType: 'DIALOG', chrome: ChatChromeStyle.color, style: ComposerStyle.materialYou, diff --git a/test/composer_forward_preview_test.dart b/test/composer_forward_preview_test.dart index 4e4f3f70..35c4b651 100644 --- a/test/composer_forward_preview_test.dart +++ b/test/composer_forward_preview_test.dart @@ -77,6 +77,7 @@ void main() { composerContext = context; return Scaffold( bottomNavigationBar: ComposerInputBar( + bottomPadding: 0, chatType: 'CHAT', chrome: ChatChromeStyle.color, style: ComposerStyle.materialYou, diff --git a/test/composer_height_test.dart b/test/composer_height_test.dart new file mode 100644 index 00000000..03114f15 --- /dev/null +++ b/test/composer_height_test.dart @@ -0,0 +1,121 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/screens/chats/chat/composer_height.dart'; +import 'package:komet/frontend/screens/chats/chat/sticker_panel_controller.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _bar = 96.0; +const _keyboard = 320.0; + +Future _withComposer( + WidgetTester tester, + Future Function(StickerPanelController stickers, ComposerHeight height) + body, +) async { + final stickers = StickerPanelController(vsync: tester, onSendTyping: () {}) + ..maxHeight = 700; + final height = ComposerHeight(stickers)..measured(_bar); + await body(stickers, height); + height.dispose(); + stickers.dispose(); +} + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + testWidgets( + 'takes the panel in at once when it replaces the keyboard', + (tester) async => _withComposer(tester, (stickers, height) async { + var notified = 0; + height.addListener(() => notified++); + + stickers.showInPlaceOfKeyboard(_keyboard); + + expect(height.value, _bar + _keyboard); + expect(notified, 1); + + height.measured(_bar + _keyboard); + expect(height.value, _bar + _keyboard); + expect(notified, 1); + }), + ); + + testWidgets( + 'drops the panel at once when the keyboard covers it', + (tester) async => _withComposer(tester, (stickers, height) async { + stickers.showInPlaceOfKeyboard(_keyboard); + height.measured(_bar + _keyboard); + + stickers.yieldToKeyboard(); + stickers.keyboardChanged(_keyboard, landscape: false); + + expect(height.value, _bar); + await tester.pump(const Duration(milliseconds: 300)); + }), + ); + + testWidgets( + 'follows the slide-in frame by frame without a measurement', + (tester) async => _withComposer(tester, (stickers, height) async { + stickers.show(landscape: false); + + for (var frame = 0; frame < 12; frame++) { + await tester.pump(const Duration(milliseconds: 20)); + expect(height.value, _bar + stickers.visibleHeight); + } + expect(stickers.visibleHeight, greaterThan(0)); + }), + ); + + testWidgets( + 'keeps a change of the bar itself measured under the panel', + (tester) async => _withComposer(tester, (stickers, height) async { + stickers.showInPlaceOfKeyboard(_keyboard); + height.measured(_bar + 40 + _keyboard); + + expect(height.value, _bar + 40 + _keyboard); + + stickers.hide(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 250)); + expect(height.value, _bar + 40); + }), + ); + + testWidgets( + 'hands the safe area over to the panel without a jump', + (tester) async => _withComposer(tester, (stickers, height) async { + const navigationBar = 48.0; + stickers.safeBottom = navigationBar; + height.measured(_bar + navigationBar); + final resting = height.value; + final values = []; + + void expectSeamless() { + final visible = stickers.visibleHeight; + expect(stickers.barBottomPadding + visible, stickers.slotHeight); + expect( + height.value, + _bar + (visible > navigationBar ? visible : navigationBar), + ); + expect(height.value, greaterThanOrEqualTo(resting)); + values.add(height.value); + } + + stickers.show(landscape: false); + for (var frame = 0; frame < 16; frame++) { + await tester.pump(const Duration(milliseconds: 16)); + expectSeamless(); + } + expect(stickers.barBottomPadding, 0); + + stickers.hide(); + for (var frame = 0; frame < 16; frame++) { + await tester.pump(const Duration(milliseconds: 16)); + expectSeamless(); + } + expect(height.value, resting); + expect(stickers.barBottomPadding, navigationBar); + expect(values.first, resting); + }), + ); +} diff --git a/test/debug_session_log_test.dart b/test/debug_session_log_test.dart index 622ba9b7..ccdbca0c 100644 --- a/test/debug_session_log_test.dart +++ b/test/debug_session_log_test.dart @@ -123,6 +123,8 @@ void main() { expect(text, contains('<= ошибка: synthetic failure')); expect(text, contains('synthetic legacy line')); expect(text, contains('first synthetic line')); + expect(text, contains('"probe": "answer"')); + expect(text, contains('"1": "numeric key"')); expect(files.where((file) => file.name.startsWith('session_')).length, 3); }); } diff --git a/test/double_tap_reaction_test.dart b/test/double_tap_reaction_test.dart index 7b124ac4..a23be2cd 100644 --- a/test/double_tap_reaction_test.dart +++ b/test/double_tap_reaction_test.dart @@ -119,7 +119,7 @@ void main() { _app( SelectableMessageRow( message: _message(), - isMe: false, + outgoing: false, selectedIds: selected, selectionAnim: kAlwaysDismissedAnimation, isSelectionActive: () => false, diff --git a/test/downloads_screen_test.dart b/test/downloads_screen_test.dart index fd16fba4..aafc925e 100644 --- a/test/downloads_screen_test.dart +++ b/test/downloads_screen_test.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/media/audio_file_metadata.dart'; import 'package:komet/core/utils/download_history.dart'; import 'package:komet/core/utils/media_cache.dart'; import 'package:komet/frontend/screens/downloads_screen.dart'; @@ -74,7 +75,7 @@ void main() { locale: Locale('ru'), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - home: DownloadsScreen(), + home: DownloadsScreen(highlightCacheName: 'synthetic-package.zip'), ), ); await tester.pump(); @@ -84,6 +85,10 @@ void main() { expect(find.text('sample-package.zip'), findsOneWidget); expect(find.text('2.0 КБ · Synthetic channel'), findsOneWidget); expect(find.byKey(const ValueKey('downloads-settings')), findsOneWidget); + expect( + find.byKey(const ValueKey('download-highlight-synthetic-package.zip')), + findsOneWidget, + ); await tester.tap( find.byKey(const ValueKey('download-more-synthetic-package.zip')), @@ -93,4 +98,59 @@ void main() { expect(find.text('Перейти к сообщению'), findsOneWidget); expect(find.text('Сохранить как…'), findsOneWidget); }); + + testWidgets('audio downloads show embedded title, artist and cover', ( + tester, + ) async { + final directory = Directory.systemTemp.createTempSync( + 'synthetic_audio_downloads_test', + ); + addTearDown(() { + AudioFileMetadata.resetForTesting(); + DownloadHistory.resetForTesting(); + MediaCache.resetForTesting(); + if (directory.existsSync()) directory.deleteSync(recursive: true); + }); + PathProviderPlatform.instance = _SyntheticPathProvider(directory.path); + MediaCache.resetForTesting(); + AudioFileMetadata.resetForTesting(); + SharedPreferences.setMockInitialValues({}); + late AudioFileMetadataInfo metadata; + + await tester.runAsync(() async { + DownloadHistory.resetForTesting(); + final file = await MediaCache.fileFor('synthetic-audio.mp3'); + await file.writeAsBytes( + await File('test/fixtures/audio_metadata.mp3').readAsBytes(), + ); + await DownloadHistory.record( + const DownloadMetadata( + cacheName: 'synthetic-audio.mp3', + name: 'fallback-name.mp3', + kind: DownloadKind.audio, + sourceName: 'Fallback source', + ), + file, + ); + metadata = (await AudioFileMetadata.read( + file, + cacheName: 'synthetic-audio.mp3', + ))!; + }); + + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DownloadsScreen(audioMetadataLoader: (_) async => metadata), + ), + ); + await tester.pump(); + await tester.pumpAndSettle(); + + expect(find.text('Synthetic Track'), findsOneWidget); + expect(find.textContaining('Synthetic Artist'), findsOneWidget); + expect(find.byType(Image), findsOneWidget); + }); } diff --git a/test/failed_message_actions_test.dart b/test/failed_message_actions_test.dart new file mode 100644 index 00000000..89fb3edd --- /dev/null +++ b/test/failed_message_actions_test.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/frontend/screens/chats/chat/view/message_row_widgets.dart'; +import 'package:komet/l10n/app_localizations.dart'; + +CachedMessage _message({int senderId = 101, String status = 'error'}) => + CachedMessage( + id: 'temp_failed_1', + accountId: 101, + chatId: 303, + senderId: senderId, + text: 'Synthetic failed message', + time: 1700000000000, + status: status, + ); + +Widget _app(Widget child) => MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: Center(child: child)), +); + +void main() { + test('only an outgoing error is treated as a failed send', () { + expect(isFailedOutgoingMessage(_message(), 101), isTrue); + expect(isFailedOutgoingMessage(_message(status: 'pending'), 101), isFalse); + expect(isFailedOutgoingMessage(_message(senderId: 202), 101), isFalse); + }); + + testWidgets( + 'a failed send has a separate retry button and a delete-only menu', + (tester) async { + final selected = ValueNotifier>(const {}); + addTearDown(selected.dispose); + var retries = 0; + + await tester.pumpWidget( + _app( + SizedBox( + width: 340, + child: SelectableMessageRow( + message: _message(), + outgoing: true, + failedSend: true, + selectedIds: selected, + selectionAnim: kAlwaysDismissedAnimation, + isSelectionActive: () => false, + onToggleSelection: () {}, + onEnterSelection: () {}, + onStartTextSelection: (_) {}, + onDragTextSelection: (_) {}, + onDelete: () {}, + onRetry: () => retries++, + onReply: () {}, + onForward: () {}, + onMarkUnread: () {}, + onPin: () {}, + onCopyLink: () {}, + onReact: (_) {}, + onDoubleTapReact: (_) {}, + isPinned: () => false, + child: const SizedBox( + height: 72, + child: Center(child: Text('failed source row')), + ), + ), + ), + ), + ); + await tester.pump(); + + final retry = find.byKey( + const ValueKey('failed-message-retry-temp_failed_1'), + ); + expect(retry, findsOneWidget); + expect(find.text('Отправить повторно'), findsOneWidget); + await tester.tap(retry); + await tester.pump(const Duration(milliseconds: 250)); + expect(retries, 1); + expect(find.text('Удалить'), findsNothing); + + await tester.tap(find.text('failed source row')); + await tester.pump(const Duration(milliseconds: 250)); + await tester.pump(const Duration(milliseconds: 350)); + + final sourceOpacity = tester.widget( + find.byKey(const ValueKey('message-actions-source-temp_failed_1')), + ); + expect(sourceOpacity.opacity, 0); + expect(find.text('Ответить'), findsNothing); + expect(find.text('Переслать'), findsNothing); + expect(find.text('Непрочитанное'), findsNothing); + expect(find.text('Удалить'), findsOneWidget); + expect(find.text('Отправить повторно'), findsOneWidget); + + await tester.tapAt(const Offset(4, 4)); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } + final restoredOpacity = tester.widget( + find.byKey(const ValueKey('message-actions-source-temp_failed_1')), + ); + expect(restoredOpacity.opacity, 1); + }, + ); +} diff --git a/test/file_bubble_test.dart b/test/file_bubble_test.dart index 593e84eb..c7e841e9 100644 --- a/test/file_bubble_test.dart +++ b/test/file_bubble_test.dart @@ -10,6 +10,8 @@ import 'package:komet/core/utils/download_progress.dart'; import 'package:komet/core/utils/file_download.dart'; import 'package:komet/core/utils/haptics.dart'; import 'package:komet/core/utils/media_cache.dart'; +import 'package:komet/core/media/audio_file_track.dart'; +import 'package:komet/core/media/audio_file_metadata.dart'; import 'package:komet/frontend/widgets/attachment/bubbles/bubble_context.dart'; import 'package:komet/frontend/widgets/attachment/bubbles/file_bubble.dart'; import 'package:komet/models/attachment.dart'; @@ -33,6 +35,10 @@ Future _pump( required FileBubbleOpener openFile, bool cached = false, double? progress, + FileBubbleOpener? audioCache, + FileBubbleAudioMetadataLoader? audioMetadataLoader, + AudioFileEnricher? audioEnricher, + AudioFileActivator? audioActivator, Widget Function(Widget child)? wrap, }) async { final cacheName = '901_$name'; @@ -58,6 +64,10 @@ Future _pump( fill: true, file: FileAttachment(fileId: 901, name: name, size: 2048), openFile: openFile, + cacheAudioFile: audioCache, + loadAudioMetadata: audioMetadataLoader, + enrichAudioFile: audioEnricher, + activateAudioFile: audioActivator, ctx: BubbleContext( context: context, cs: Theme.of(context).colorScheme, @@ -173,6 +183,81 @@ void main() { expect(find.text('Открыть · 2.0 КБ'), findsOneWidget); }); + testWidgets('audio starts without an opening label or an endless spinner', ( + tester, + ) async { + final activated = Completer(); + final finished = Completer(); + final cacheName = await _pump( + tester, + name: 'synthetic-track.mp3', + cached: true, + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) async { + throw StateError('audio must not use the generic file opener'); + }, + audioCache: + (cacheName, resolveUrl, {onProgress, onReady, download}) async { + onReady?.call(); + final file = await MediaCache.fileFor(cacheName); + return FileDownloadResult(ok: true, path: file.path); + }, + audioEnricher: (track) async => track, + audioActivator: (track, {required notificationChannelName}) async { + expect(track.cacheName, '901_synthetic-track.mp3'); + activated.complete(); + await finished.future; + }, + ); + + await tester.tap(find.text('synthetic-track.mp3')); + for (var i = 0; i < 20 && !activated.isCompleted; i++) { + await tester.pump(const Duration(milliseconds: 10)); + } + expect(activated.isCompleted, isTrue); + + expect(find.textContaining('Открытие'), findsNothing); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(MediaDownloadProgress.notifier(cacheName).value, isNull); + + finished.complete(); + await tester.pumpAndSettle(); + }); + + testWidgets('cached audio shows metadata and a compact cover in the bubble', ( + tester, + ) async { + final artwork = Uri.file('${directory.path}/synthetic-audio-cover.png'); + + var metadataLoads = 0; + await _pump( + tester, + name: 'metadata-track.mp3', + cached: true, + openFile: (cacheName, resolveUrl, {onProgress, onReady, download}) async { + throw StateError('audio must not use the generic file opener'); + }, + audioMetadataLoader: (cacheName) async { + metadataLoads++; + return AudioFileMetadataInfo( + title: 'Metadata title', + artist: 'Metadata artist', + artworkUri: artwork, + ); + }, + ); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 10)); + } + + expect(metadataLoads, 1); + expect(find.text('Metadata title'), findsOneWidget); + expect(find.text('Metadata artist'), findsOneWidget); + expect( + find.byKey(const ValueKey('audio-metadata-cover-901_metadata-track.mp3')), + findsOneWidget, + ); + }); + testWidgets('active download taps neither restart it nor open the row menu', ( tester, ) async { diff --git a/test/fixtures/audio_metadata.mp3 b/test/fixtures/audio_metadata.mp3 new file mode 100644 index 00000000..5e6171a5 Binary files /dev/null and b/test/fixtures/audio_metadata.mp3 differ diff --git a/test/folder_edit_sheet_test.dart b/test/folder_edit_sheet_test.dart index 4c9afd0f..ae87219d 100644 --- a/test/folder_edit_sheet_test.dart +++ b/test/folder_edit_sheet_test.dart @@ -5,7 +5,11 @@ import 'package:komet/backend/models/chat_folder.dart'; import 'package:komet/frontend/screens/chats/folder_edit_sheet.dart'; import 'package:komet/frontend/widgets/sheet_helpers.dart'; -Future _openSheet(WidgetTester tester, {ChatFolder? folder}) async { +Future _openSheet( + WidgetTester tester, { + ChatFolder? folder, + List initialChatIds = const [], +}) async { await tester.pumpWidget( MaterialApp( locale: const Locale('ru'), @@ -14,7 +18,11 @@ Future _openSheet(WidgetTester tester, {ChatFolder? folder}) async { home: Scaffold( body: Builder( builder: (context) => TextButton( - onPressed: () => showFolderEditSheet(context, folder: folder), + onPressed: () => showFolderEditSheet( + context, + folder: folder, + initialChatIds: initialChatIds, + ), child: const Text('open'), ), ), @@ -58,6 +66,17 @@ void main() { expect(find.text('Создать папку'), findsOneWidget); }); + testWidgets('a folder started from a chat already holds that chat', ( + tester, + ) async { + await _openSheet(tester, initialChatIds: const [900201]); + + expect(_button(tester, 'Очистить выбор').onTap, isNotNull); + await tester.enterText(find.byType(TextField).first, 'Работа'); + await tester.pump(); + expect(_button(tester, 'Создать папку').onTap, isNotNull); + }); + testWidgets('creating needs both a name and a selection', (tester) async { await _openSheet(tester); diff --git a/test/format_selection_toolbar_test.dart b/test/format_selection_toolbar_test.dart new file mode 100644 index 00000000..3e44f1ba --- /dev/null +++ b/test/format_selection_toolbar_test.dart @@ -0,0 +1,297 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/utils/text_format.dart'; +import 'package:komet/frontend/widgets/format_selection_toolbar.dart'; +import 'package:komet/frontend/widgets/rich_message_controller.dart'; +import 'package:komet/frontend/widgets/selection_toolbar.dart'; +import 'package:komet/l10n/app_localizations.dart'; + +const _text = 'первое слово и второе слово'; +const _keyboard = 300.0; +const _formatting = 'Форматирование'; +const _bold = 'Жирный'; +const _link = 'Ссылка'; +const _replyKey = ValueKey('reply'); +const _floorKey = ValueKey('floor'); + +final _android = TargetPlatformVariant.only(TargetPlatform.android); + +class _Composer extends StatelessWidget { + const _Composer({required this.controller, this.floored = false}); + + final RichMessageController controller; + final bool floored; + + @override + Widget build(BuildContext context) { + final field = TextField( + controller: controller, + maxLines: 4, + contextMenuBuilder: (_, state) => + FormatSelectionToolbar(controller: controller, editableState: state), + ); + return MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Column( + children: [ + const Spacer(), + if (floored) + SelectionToolbarFloor( + child: Column( + key: _floorKey, + children: [ + const SizedBox(key: _replyKey, height: 56), + field, + ], + ), + ) + else + field, + ], + ), + ), + ); + } +} + +Future _openComposer( + WidgetTester tester, { + double width = 393, + double keyboard = 0, + String text = _text, + bool floored = false, +}) async { + tester.view + ..devicePixelRatio = 1 + ..physicalSize = Size(width, 800) + ..viewInsets = FakeViewPadding(bottom: keyboard); + addTearDown(tester.view.reset); + final controller = RichMessageController(text: text); + addTearDown(controller.dispose); + await tester.pumpWidget(_Composer(controller: controller, floored: floored)); + await tester.showKeyboard(find.byType(TextField)); + return controller; +} + +Future _showToolbar( + WidgetTester tester, + RichMessageController controller, + TextSelection selection, +) async { + controller.selection = selection; + await tester.pump(); + expect(_editable(tester).showToolbar(), isTrue); + await tester.pumpAndSettle(); +} + +Future _hideToolbar(WidgetTester tester) async { + _editable(tester).hideToolbar(); + await tester.pumpAndSettle(); +} + +EditableTextState _editable(WidgetTester tester) => + tester.state(find.byType(EditableText)); + +MaterialLocalizations _material(WidgetTester tester) => + MaterialLocalizations.of(tester.element(find.byType(TextField))); + +Rect _toolbarRect(WidgetTester tester) => + tester.getRect(find.byType(SelectionToolbarSurface)); + +Future _tapTooltip(WidgetTester tester, String tooltip) async { + await tester.tap(find.byTooltip(tooltip)); + await tester.pumpAndSettle(); +} + +const _firstWord = TextSelection(baseOffset: 0, extentOffset: 6); +const _lastWord = TextSelection(baseOffset: 22, extentOffset: 27); + +void main() { + testWidgets('opens on the text actions with an entry to formatting', ( + tester, + ) async { + final controller = await _openComposer(tester, width: 800); + await _showToolbar(tester, controller, _firstWord); + + expect(find.byTooltip(_formatting), findsOneWidget); + expect(find.text(_material(tester).copyButtonLabel), findsOneWidget); + expect(find.byTooltip(_bold), findsNothing); + }, variant: _android); + + testWidgets('formats in place and keeps the toolbar open', (tester) async { + final controller = await _openComposer(tester); + await _showToolbar(tester, controller, _firstWord); + await _tapTooltip(tester, _formatting); + await _tapTooltip(tester, _bold); + + expect(controller.isFormatActive(TextFormat.strong), isTrue); + expect(find.byTooltip(_bold), findsOneWidget); + + await _tapTooltip(tester, _bold); + expect(controller.isFormatActive(TextFormat.strong), isFalse); + }, variant: _android); + + testWidgets('back returns to the text actions', (tester) async { + final controller = await _openComposer(tester); + await _showToolbar(tester, controller, _firstWord); + await _tapTooltip(tester, _formatting); + await _tapTooltip(tester, _material(tester).backButtonTooltip); + + expect(find.byTooltip(_formatting), findsOneWidget); + expect(find.byTooltip(_bold), findsNothing); + }, variant: _android); + + testWidgets('stays one row high above the keyboard on every page', ( + tester, + ) async { + final controller = await _openComposer( + tester, + width: 320, + keyboard: _keyboard, + ); + await _showToolbar(tester, controller, _firstWord); + final visibleBottom = 800 - _keyboard; + final textTop = tester.getRect(find.byType(EditableText)).top; + + void expectAboveKeyboard() { + final rect = _toolbarRect(tester); + expect(rect.height, SelectionToolbarStyle.height); + expect(rect.bottom, lessThanOrEqualTo(textTop)); + expect(rect.bottom, lessThanOrEqualTo(visibleBottom)); + expect( + rect.left, + greaterThanOrEqualTo(SelectionToolbarStyle.screenMargin), + ); + expect( + rect.right, + lessThanOrEqualTo(320 - SelectionToolbarStyle.screenMargin), + ); + } + + expectAboveKeyboard(); + await _tapTooltip(tester, _formatting); + expectAboveKeyboard(); + await _tapTooltip(tester, _material(tester).moreButtonTooltip); + expectAboveKeyboard(); + }, variant: _android); + + testWidgets('pages a row that does not fit and keeps a wide one whole', ( + tester, + ) async { + final narrow = await _openComposer(tester, width: 320); + await _showToolbar(tester, narrow, _firstWord); + await _tapTooltip(tester, _formatting); + + expect(find.byTooltip(_link), findsNothing); + await _tapTooltip(tester, _material(tester).moreButtonTooltip); + expect(find.byTooltip(_link), findsOneWidget); + expect(find.byTooltip(_bold), findsNothing); + await _hideToolbar(tester); + + final wide = await _openComposer(tester, width: 412); + await _showToolbar(tester, wide, _lastWord); + await _tapTooltip(tester, _formatting); + + expect(find.byTooltip(_bold), findsOneWidget); + expect(find.byTooltip(_link), findsOneWidget); + expect(find.byTooltip(_material(tester).moreButtonTooltip), findsNothing); + }, variant: _android); + + testWidgets('returns to formatting only for the same selection', ( + tester, + ) async { + final controller = await _openComposer(tester); + await _showToolbar(tester, controller, _firstWord); + await _tapTooltip(tester, _formatting); + await _hideToolbar(tester); + + await _showToolbar( + tester, + controller, + const TextSelection(baseOffset: 0, extentOffset: 12), + ); + expect(find.byTooltip(_bold), findsOneWidget); + await _hideToolbar(tester); + + await _showToolbar(tester, controller, _lastWord); + expect(find.byTooltip(_formatting), findsOneWidget); + expect(find.byTooltip(_bold), findsNothing); + }, variant: _android); + + testWidgets('drops formatting once the selection collapses', (tester) async { + final controller = await _openComposer(tester); + await _showToolbar(tester, controller, _firstWord); + await _tapTooltip(tester, _formatting); + + controller.selection = const TextSelection.collapsed(offset: 3); + await tester.pumpAndSettle(); + expect(find.byTooltip(_bold), findsNothing); + await _hideToolbar(tester); + + await _showToolbar(tester, controller, _firstWord); + expect(find.byTooltip(_formatting), findsOneWidget); + }, variant: _android); + + testWidgets('never sinks below the top of the input panel', (tester) async { + const lines = 'один\nдва\nтри\nчетыре'; + final lastLine = TextSelection( + baseOffset: lines.lastIndexOf('\n') + 1, + extentOffset: lines.length, + ); + final controller = await _openComposer( + tester, + text: lines, + floored: true, + keyboard: _keyboard, + ); + await _showToolbar(tester, controller, lastLine); + final floorTop = tester.getRect(find.byKey(_floorKey)).top; + + void expectAbovePanel() { + final rect = _toolbarRect(tester); + expect( + rect.bottom, + lessThanOrEqualTo(floorTop - SelectionToolbarStyle.screenMargin), + ); + expect(rect.top, greaterThanOrEqualTo(0)); + } + + expectAbovePanel(); + expect( + tester.getRect(find.byKey(_replyKey)).top, + greaterThanOrEqualTo(_toolbarRect(tester).bottom), + ); + await _tapTooltip(tester, _formatting); + expectAbovePanel(); + }, variant: _android); + + testWidgets('opens above the input panel on a right click', (tester) async { + final controller = await _openComposer( + tester, + width: 900, + text: 'один\nдва\nтри\nчетыре', + floored: true, + ); + final text = tester.getRect(find.byType(EditableText)); + final click = await tester.startGesture( + Offset(text.left + 12, text.bottom - 6), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + await click.up(); + await tester.pumpAndSettle(); + + final floorTop = tester.getRect(find.byKey(_floorKey)).top; + final rect = _toolbarRect(tester); + expect( + rect.bottom, + lessThanOrEqualTo(floorTop - SelectionToolbarStyle.screenMargin), + ); + expect(rect.height, SelectionToolbarStyle.height); + expect(controller.selection.isValid, isTrue); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); +} diff --git a/test/formatted_text_cache_test.dart b/test/formatted_text_cache_test.dart index e354dbe4..e07c8886 100644 --- a/test/formatted_text_cache_test.dart +++ b/test/formatted_text_cache_test.dart @@ -64,7 +64,9 @@ void main() { final launched = []; setUp(() { - SharedPreferences.setMockInitialValues({}); + SharedPreferences.setMockInitialValues({ + VisitedLinkSites.prefKey: ['example.com'], + }); VisitedLinkSites.resetForTest(); launched.clear(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger diff --git a/test/ghost_read_store_test.dart b/test/ghost_read_store_test.dart new file mode 100644 index 00000000..c6ef42de --- /dev/null +++ b/test/ghost_read_store_test.dart @@ -0,0 +1,94 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/storage/ghost_read_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const int _account = 900001; +const int _chat = 900201; + +GhostRead _read() => GhostReadStore.instance.of(_account, _chat)!; + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + await GhostReadStore.instance.clearAll(); + await GhostReadStore.instance.load(); + }); + + test( + 'a chat read locally stays read while the server still counts it', + () async { + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1000, + left: 0, + serverUnread: 5, + serverOwnMark: 400, + ); + expect(_read().unreadFor(5, lastMessageTime: 1000), 0); + expect(_read().unreadFor(5), 0); + }, + ); + + test('messages arriving after the local read are counted', () async { + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1000, + left: 0, + serverUnread: 5, + serverOwnMark: 400, + ); + await GhostReadStore.instance.noteServer(_account, _chat, unread: 8); + expect(_read().unreadFor(8, lastMessageTime: 1300), 3); + }); + + test('reading again rebases on the latest server count', () async { + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1000, + left: 0, + serverUnread: 5, + serverOwnMark: 400, + ); + await GhostReadStore.instance.noteServer(_account, _chat, unread: 8); + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1300, + left: 0, + serverUnread: 0, + serverOwnMark: 0, + ); + expect(_read().mark, 1300); + expect(_read().serverOwnMark, 400); + expect(_read().unreadFor(8, lastMessageTime: 1300), 0); + expect(_read().unreadFor(9, lastMessageTime: 1400), 1); + }); + + test('a partial read keeps what is left below', () async { + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1000, + left: 2, + serverUnread: 5, + serverOwnMark: 400, + ); + expect(_read().unreadFor(5, lastMessageTime: 1200), 2); + }); + + test('the count never goes below zero or above the server count', () async { + await GhostReadStore.instance.noteLocalRead( + _account, + _chat, + mark: 1000, + left: 4, + serverUnread: 5, + serverOwnMark: 400, + ); + expect(_read().unreadFor(2, lastMessageTime: 1200), 1); + expect(_read().unreadFor(0, lastMessageTime: 1200), 0); + }); +} diff --git a/test/link_confirm_sheet_test.dart b/test/link_confirm_sheet_test.dart index 1b1c9bd5..ef26902c 100644 --- a/test/link_confirm_sheet_test.dart +++ b/test/link_confirm_sheet_test.dart @@ -62,16 +62,6 @@ void main() { .setMockMethodCallHandler(_launcher, null); }); - test('a link is hidden only when its text hides the address', () { - expect(linkShowsItsTarget('example.com', 'https://example.com/'), isTrue); - expect( - linkShowsItsTarget('Https://WWW.Example.com', 'https://example.com'), - isTrue, - ); - expect(linkShowsItsTarget('Synthetic', 'https://example.com'), isFalse); - expect(linkShowsItsTarget('safe.org', 'https://example.com'), isFalse); - }); - test('visited sites are kept per host', () async { expect( VisitedLinkSites.siteOf('https://WWW.Example.com/a?b'), @@ -117,13 +107,92 @@ void main() { expect(launched, hasLength(2)); }); - testWidgets('a link that shows its own address opens directly', ( - tester, - ) async { + testWidgets('a plain link to a new site asks too', (tester) async { await _pumpMessage(tester, 'example.com', 'https://example.com'); await _tapLink(tester, 'example.com'); - expect(find.text('Открыть ссылку?'), findsNothing); + expect(find.text('Открыть ссылку?'), findsOneWidget); + await tester.tap(find.text('Перейти')); + await tester.pumpAndSettle(); expect(launched, ['https://example.com']); + + await _tapLink(tester, 'example.com'); + expect(find.text('Открыть ссылку?'), findsNothing); + expect(launched, hasLength(2)); + }); + + testWidgets('a lookalike address warns every time', (tester) async { + const url = 'https://ex\u0430mple.test/login'; + await _pumpMessage(tester, 'Synthetic link', url); + await _tapLink(tester, 'Synthetic link'); + + expect(find.text('Подозрительная ссылка'), findsOneWidget); + expect(find.textContaining('«а» из кириллицы'), findsOneWidget); + await tester.tap(find.text('Всё равно открыть')); + await tester.pumpAndSettle(); + expect(launched, hasLength(1)); + + await _tapLink(tester, 'Synthetic link'); + expect(find.text('Подозрительная ссылка'), findsOneWidget); + await tester.tap(find.text('Не открывать')); + await tester.pumpAndSettle(); + expect(launched, hasLength(1)); + expect(await VisitedLinkSites.contains(url), isFalse); + }); + + testWidgets('a bare domain from the server is checked like any link', ( + tester, + ) async { + const domain = 'burm\u0430ld\u0430.test'; + await _pumpMessage(tester, domain, domain); + await _tapLink(tester, domain); + + expect(find.text('Подозрительная ссылка'), findsOneWidget); + await tester.tap(find.text('Всё равно открыть')); + await tester.pumpAndSettle(); + expect(launched.single, startsWith('https://')); + }); + + testWidgets('a preview shows the check but never opens the link', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => + previewLinkCheck(context, 'https://k\u043emet.example'), + child: const Text('Preview'), + ), + ), + ), + ), + ); + + for (final button in ['Всё равно открыть', 'Не открывать']) { + await tester.tap(find.text('Preview')); + await tester.pumpAndSettle(); + expect(find.text('Подозрительная ссылка'), findsOneWidget); + await tester.tap(find.text(button)); + await tester.pumpAndSettle(); + } + expect(launched, isEmpty); + }); + + testWidgets('a link whose text names another site is suspicious', ( + tester, + ) async { + await _pumpMessage(tester, 'bank.example', 'https://login.test/form'); + await _tapLink(tester, 'bank.example'); + + expect(find.text('Подозрительная ссылка'), findsOneWidget); + expect( + find.textContaining('показывает bank.example, а ведёт на login.test'), + findsOneWidget, + ); }); } diff --git a/test/link_inspector_test.dart b/test/link_inspector_test.dart new file mode 100644 index 00000000..6836ddff --- /dev/null +++ b/test/link_inspector_test.dart @@ -0,0 +1,205 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/links/link_inspector.dart'; +import 'package:komet/core/links/punycode.dart'; + +List _kinds(LinkInspection inspection) => [ + for (final warning in inspection.warnings) warning.kind, +]; + +String _flaggedText(LinkInspection inspection) { + final indices = inspection.flagged.toList()..sort(); + return String.fromCharCodes([ + for (final i in indices) inspection.address.codeUnitAt(i), + ]); +} + +void main() { + group('punycode', () { + test('decodes the RFC 3492 Russian sample', () { + expect( + decodePunycodeLabel('xn--b1abfaaepdrnnbgefbadotcwatmq2g4l'), + 'почемужеонинеговорятпорусски', + ); + }); + + test('decodes a whole host and keeps ASCII labels', () { + expect(decodePunycodeHost('xn--d1abbgf6aiiy.xn--p1ai'), 'президент.рф'); + expect(decodePunycodeHost('www.example.com'), 'www.example.com'); + }); + + test('rejects garbage', () { + expect(decodePunycodeLabel('xn--'), isNull); + expect(decodePunycodeLabel('xn--abж'), isNull); + }); + }); + + group('linkWithScheme', () { + test('adds https only where the scheme is missing', () { + expect(linkWithScheme('example.test/a'), 'https://example.test/a'); + expect(linkWithScheme(' example.test '), 'https://example.test'); + expect( + linkWithScheme('example.test:8080/a'), + 'https://example.test:8080/a', + ); + expect(linkWithScheme('//example.test'), 'https://example.test'); + expect(linkWithScheme('http://example.test'), 'http://example.test'); + expect( + linkWithScheme('mailto:someone@example.test'), + 'mailto:someone@example.test', + ); + expect(linkWithScheme('tel:+70000000000'), 'tel:+70000000000'); + expect(linkWithScheme('tel:80000000000'), 'tel:80000000000'); + expect(linkWithScheme('geo:55.75,37.61'), 'geo:55.75,37.61'); + expect(linkWithScheme('sms:900'), 'sms:900'); + expect(linkWithScheme('192.0.2.10:8080'), 'https://192.0.2.10:8080'); + }); + }); + + group('inspectLink', () { + test('a bare domain is inspected as a site', () { + final inspection = inspectLink('burm\u0430ld\u0430.test'); + expect(inspection.host, 'burm\u0430ld\u0430.test'); + expect(_kinds(inspection), [LinkWarningKind.mixedScripts]); + }); + + test('an ordinary link is clean', () { + final inspection = inspectLink('https://www.example.com/path?q=1'); + expect(inspection.suspicious, isFalse); + expect(inspection.host, 'www.example.com'); + expect( + inspection.address.substring(inspection.hostStart, inspection.hostEnd), + 'www.example.com', + ); + }); + + test('a whole-Cyrillic site under a Cyrillic zone is clean', () { + expect(inspectLink('https://пример.рф/').suspicious, isFalse); + expect(inspectLink('https://яндекс.example').suspicious, isFalse); + }); + + test('Latin with accents is not a mix', () { + expect(inspectLink('https://café.example').suspicious, isFalse); + }); + + test('one Cyrillic letter among Latin is flagged', () { + final inspection = inspectLink('https://exаmple.test/a'); + expect(_kinds(inspection), [LinkWarningKind.mixedScripts]); + final warning = inspection.warnings.single; + expect(warning.letters, [(letter: 'а', script: LinkScript.cyrillic)]); + expect(_flaggedText(inspection), 'а'); + }); + + test('the minority script is the one highlighted', () { + final inspection = inspectLink('https://приmер.test'); + final warning = inspection.warnings.single; + expect(warning.kind, LinkWarningKind.mixedScripts); + expect(warning.letters.single.script, LinkScript.latin); + expect(_flaggedText(inspection), 'm'); + }); + + test('a Cyrillic label that only looks Latin is flagged', () { + final inspection = inspectLink('https://раураӏ.com'); + expect(_kinds(inspection), [LinkWarningKind.lookalikeScript]); + expect(_flaggedText(inspection), 'раураӏ'); + }); + + test('punycode alone is shown decoded, not flagged', () { + final inspection = inspectLink('https://xn--d1abbgf6aiiy.xn--p1ai/'); + expect(inspection.host, 'президент.рф'); + expect(inspection.address, 'https://президент.рф/'); + expect(inspection.suspicious, isFalse); + }); + + test('a forgery hidden in punycode is still caught', () { + final inspection = inspectLink('http://xn--burmld-6nfc.test'); + expect(inspection.host, 'burm\u0430ld\u0430.test'); + expect(_kinds(inspection), [LinkWarningKind.mixedScripts]); + }); + + test('user info before @ hides the real site', () { + final inspection = inspectLink('https://bank.example@login.test/form'); + expect(_kinds(inspection), [LinkWarningKind.userInfo]); + expect(inspection.host, 'login.test'); + expect(inspection.warnings.single.value, 'login.test'); + expect(_flaggedText(inspection), 'bank.example@'); + }); + + test('invisible characters are shown and flagged', () { + final inspection = inspectLink('https://exa​mple.test/'); + expect(_kinds(inspection), [LinkWarningKind.invisibleCharacters]); + expect(inspection.address, contains('[U+200B]')); + expect(_flaggedText(inspection), '[U+200B]'); + }); + + test('a literal bidi override in the path is flagged', () { + final inspection = inspectLink('https://example.test/\u202Efdp.exe'); + expect(_kinds(inspection), [LinkWarningKind.invisibleCharacters]); + expect(inspection.address, 'https://example.test/[U+202E]fdp.exe'); + }); + + test('encoded control characters stay encoded and are not flagged', () { + const url = 'https://example.test/send?text=Hello%0AWorld%E2%80%AE'; + final inspection = inspectLink(url); + expect(inspection.suspicious, isFalse); + expect(inspection.address, url); + }); + + test('percent-encoded paths are shown decoded', () { + final inspection = inspectLink( + 'https://example.test/wiki/%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80', + ); + expect(inspection.suspicious, isFalse); + expect(inspection.address, 'https://example.test/wiki/Пример'); + }); + + test('IP hosts are flagged', () { + expect(_kinds(inspectLink('http://192.0.2.10/login')), [ + LinkWarningKind.ipAddress, + ]); + expect(_kinds(inspectLink('http://[2001:db8::1]/')), [ + LinkWarningKind.ipAddress, + ]); + }); + + test('unusual schemes are flagged, mail and phone are not', () { + expect(_kinds(inspectLink('intent://scan/#Intent;end')), [ + LinkWarningKind.unusualScheme, + ]); + expect(_kinds(inspectLink('javascript:void(0)')), [ + LinkWarningKind.unusualScheme, + ]); + expect(inspectLink('mailto:someone@example.test').suspicious, isFalse); + expect(inspectLink('tel:+70000000000').suspicious, isFalse); + expect(inspectLink('geo:55.75,37.61').suspicious, isFalse); + expect(_kinds(inspectLink('sms:900')), [LinkWarningKind.unusualScheme]); + }); + + test('link text naming another site is a mismatch', () { + final inspection = inspectLink( + 'https://login.test/form', + shownText: 'https://bank.example', + ); + expect(_kinds(inspection), [LinkWarningKind.textMismatch]); + expect(inspection.warnings.single.value, 'bank.example'); + }); + + test('link text matching the site or its subdomain is fine', () { + for (final shown in [ + 'example.test', + 'www.example.test/other', + 'Example.Test', + 'Click here', + 'docs v1.2', + ]) { + expect( + inspectLink( + 'https://login.example.test/path', + shownText: shown, + ).suspicious, + isFalse, + reason: shown, + ); + } + }); + }); +} diff --git a/test/media_cache_security_test.dart b/test/media_cache_security_test.dart index 06094207..ca03f0f6 100644 --- a/test/media_cache_security_test.dart +++ b/test/media_cache_security_test.dart @@ -3,7 +3,8 @@ import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:komet/core/config/app_media_cache.dart'; +import 'package:komet/core/cache/cache_janitor.dart'; +import 'package:komet/core/config/app_cache_limit.dart'; import 'package:komet/core/utils/media_cache.dart'; void main() { @@ -23,7 +24,7 @@ void main() { (call) async => temp.path, ); MediaCache.resetForTesting(); - AppMediaCacheLimit.current.value = 8; + AppCacheLimit.current.value = 8; server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); server.listen((request) async { if (request.uri.path == '/slow') { @@ -40,7 +41,8 @@ void main() { HttpOverrides.global = originalOverrides; await server.close(force: true); MediaCache.resetForTesting(); - AppMediaCacheLimit.current.value = AppMediaCacheLimit.defaultValue; + CacheJanitor.instance.resetForTesting(); + AppCacheLimit.current.value = AppCacheLimit.defaultValue; await temp.delete(recursive: true); }); test( diff --git a/test/media_retry_test.dart b/test/media_retry_test.dart new file mode 100644 index 00000000..bbfca624 --- /dev/null +++ b/test/media_retry_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/frontend/screens/chats/chat/chat_controller.dart'; +import 'package:komet/frontend/screens/chats/chat/chat_media_send_controller.dart'; +import 'package:komet/frontend/screens/chats/chat/upload_status.dart'; +import 'package:komet/models/attachment.dart'; + +const int _me = 101; +const int _chatId = 303; + +CachedMessage _failed( + List attachments, { + String status = 'error', + int e2ee = CachedMessage.e2eeNone, +}) => CachedMessage( + id: 'temp_1_1', + accountId: _me, + chatId: _chatId, + senderId: _me, + time: 1700000000000, + status: status, + attachments: attachments, + e2ee: e2ee, +); + +void main() { + final chat = ChatController() + ..myId = _me + ..chatId = _chatId; + final media = ChatMediaSendController( + chatController: chat, + showAttachmentPanel: ValueNotifier(false), + uploadStatus: ValueNotifier(const UploadStatus()), + bumpMessages: () {}, + scrollToBottom: () {}, + setLastSentId: (_) {}, + notify: (_) {}, + isMounted: () => true, + encryptionEnabled: () => false, + encryptOutgoing: (text, {notify = true}) async => text, + confirmSend: () async => true, + markHasScheduled: () {}, + takeReply: () => null, + ); + + test('media with its source on the device can be sent again', () { + expect( + media.canRetry(_failed([const PhotoAttachment(localPath: '/tmp/a.jpg')])), + isTrue, + ); + expect( + media.canRetry( + _failed([ + const VideoAttachment(videoType: 1, localPath: '/tmp/note.mp4'), + ]), + ), + isTrue, + ); + expect( + media.canRetry(_failed([const AudioAttachment(localPath: '/tmp/v.ogg')])), + isTrue, + ); + expect( + media.canRetry( + _failed([const FileAttachment(localPath: '/tmp/doc.pdf')]), + ), + isTrue, + ); + }); + + test('a file already on the server is sent again by its id', () { + expect(media.canRetry(_failed([const FileAttachment(fileId: 7)])), isTrue); + }); + + test('stickers, contacts and places are rebuilt from the attachment', () { + expect( + media.canRetry(_failed([const StickerAttachment(stickerId: '12')])), + isTrue, + ); + expect( + media.canRetry(_failed([const ContactAttachment(contactId: 900301)])), + isTrue, + ); + expect( + media.canRetry( + _failed([const LocationAttachment(latitude: 55.7, longitude: 37.6)]), + ), + isTrue, + ); + }); + + test('nothing to send again is not offered', () { + expect(media.canRetry(_failed([const AudioAttachment()])), isFalse); + expect(media.canRetry(_failed([const FileAttachment()])), isFalse); + expect( + media.canRetry( + _failed([ + const PhotoAttachment(localPath: '/tmp/a.jpg'), + const PhotoAttachment(), + ]), + ), + isFalse, + ); + expect(media.canRetry(_failed(const [])), isFalse); + }); + + test('only failed unencrypted messages are offered', () { + const photo = PhotoAttachment(localPath: '/tmp/a.jpg'); + expect(media.canRetry(_failed([photo], status: 'sending')), isFalse); + expect(media.canRetry(_failed([photo], status: 'sent')), isFalse); + expect( + media.canRetry(_failed([photo], e2ee: CachedMessage.e2eeFile)), + isFalse, + ); + }); +} diff --git a/test/message_actions_back_test.dart b/test/message_actions_back_test.dart index c9d0408b..097ebbdc 100644 --- a/test/message_actions_back_test.dart +++ b/test/message_actions_back_test.dart @@ -32,7 +32,7 @@ void main() { context: context, originRect: const Rect.fromLTWH(20, 200, 200, 40), tapPoint: const Offset(60, 220), - isMe: false, + outgoing: false, messageText: 'текст', copyText: 'текст', controller: controller, diff --git a/test/message_actions_info_test.dart b/test/message_actions_info_test.dart index 3afbde17..146d551b 100644 --- a/test/message_actions_info_test.dart +++ b/test/message_actions_info_test.dart @@ -29,7 +29,7 @@ Future _openMenu( context: context, originRect: const Rect.fromLTWH(20, 200, 200, 40), tapPoint: const Offset(60, 220), - isMe: false, + outgoing: false, messageText: 'текст', copyText: 'текст', controller: controller, diff --git a/test/message_actions_save_test.dart b/test/message_actions_save_test.dart index b6b6d573..dbc56237 100644 --- a/test/message_actions_save_test.dart +++ b/test/message_actions_save_test.dart @@ -23,7 +23,7 @@ Future _openMenu(WidgetTester tester, {VoidCallback? onSave}) async { context: context, originRect: const Rect.fromLTWH(20, 200, 200, 40), tapPoint: const Offset(60, 220), - isMe: false, + outgoing: false, messageText: null, copyText: null, controller: controller, diff --git a/test/message_media_edit_test.dart b/test/message_media_edit_test.dart index 67169b9f..60c9bc14 100644 --- a/test/message_media_edit_test.dart +++ b/test/message_media_edit_test.dart @@ -124,7 +124,6 @@ void main() { text: '', formatRanges: const [], photos: const [_first, _second], - contextMenuBuilder: (_, _, _) => const SizedBox.shrink(), ), ), ), diff --git a/test/native/test_ios_appstore_signing.py b/test/native/test_ios_appstore_signing.py index 1d59a787..7fbda6fc 100644 --- a/test/native/test_ios_appstore_signing.py +++ b/test/native/test_ios_appstore_signing.py @@ -75,6 +75,62 @@ def test_rejects_inconsistent_profile_prefix(self): SIGNING.create_plan(self.app_profile) +APP_REQUESTED = { + "com.apple.security.application-groups": ["$(KOMET_SHARE_APP_GROUP)"], + "keychain-access-groups": ["$(AppIdentifierPrefix)$(PRODUCT_BUNDLE_IDENTIFIER)"], +} +SHARE_REQUESTED = {"com.apple.security.application-groups": ["$(KOMET_SHARE_APP_GROUP)"]} + + +def wildcard_profile(bundle_id="example.synthetic.app", groups=None, team="SYNTH12345"): + result = profile(bundle_id, groups, team) + result["Entitlements"].update({ + "keychain-access-groups": [f"{team}.*", "com.apple.token"], + "com.apple.developer.associated-domains": "*", + "beta-reports-active": True, + }) + return result + + +class AppStoreSigningEntitlementsTest(unittest.TestCase): + def test_signs_with_the_apps_own_entitlements_not_profile_templates(self): + plan = SIGNING.create_plan(wildcard_profile(), app_requested=APP_REQUESTED) + self.assertEqual(plan.app_entitlements, { + "application-identifier": "SYNTH12345.example.synthetic.app", + "com.apple.developer.team-identifier": "SYNTH12345", + "get-task-allow": False, + "beta-reports-active": True, + "keychain-access-groups": ["SYNTH12345.example.synthetic.app"], + }) + + def test_app_groups_are_signed_only_with_the_extension(self): + app_profile = wildcard_profile(groups=["group.synthetic.shared"]) + share_profile = wildcard_profile("example.synthetic.app.ShareExtension", ["group.synthetic.shared"]) + alone = SIGNING.create_plan(app_profile, app_requested=APP_REQUESTED) + self.assertNotIn(SIGNING.APP_GROUPS, alone.app_entitlements) + paired = SIGNING.create_plan(app_profile, share_profile, "group.synthetic.shared", APP_REQUESTED, SHARE_REQUESTED) + self.assertEqual(paired.app_entitlements[SIGNING.APP_GROUPS], ["group.synthetic.shared"]) + self.assertEqual(paired.share_entitlements[SIGNING.APP_GROUPS], ["group.synthetic.shared"]) + self.assertEqual(paired.share_entitlements["application-identifier"], "SYNTH12345.example.synthetic.app.ShareExtension") + self.assertNotIn("keychain-access-groups", paired.share_entitlements) + + def test_rejects_entitlements_the_profile_does_not_grant(self): + for requested in [ + {"com.apple.developer.icloud-services": ["CloudKit"]}, + {"keychain-access-groups": ["OTHER12345.example.synthetic.app"]}, + ]: + with self.subTest(requested=requested), self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(wildcard_profile(), app_requested=requested) + + def test_rejects_wildcards_and_unknown_build_variables(self): + for requested in [ + {"keychain-access-groups": ["$(AppIdentifierPrefix)*"]}, + {"keychain-access-groups": ["$(UNDEFINED_SETTING)"]}, + ]: + with self.subTest(requested=requested), self.assertRaises(SIGNING.SigningPlanError): + SIGNING.create_plan(wildcard_profile(), app_requested=requested) + + class AppStoreBundlePreparationTest(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix="synthetic signing ") @@ -152,8 +208,8 @@ def capture(command, **options): self.assertEqual(calls[-3][-1], str(self.share)) self.assertEqual(calls[-2][-1], str(self.app)) self.assertEqual(calls[-1], ["codesign", "--verify", "--deep", "--strict", "--verbose=2", str(self.app)]) - self.assertEqual(entitlements[str(self.share)], plan.share.entitlements) - self.assertEqual(entitlements[str(self.app)], plan.app.entitlements) + self.assertEqual(entitlements[str(self.share)], plan.share_entitlements) + self.assertEqual(entitlements[str(self.app)], plan.app_entitlements) self.assertEqual({command[-1] for command in calls[:-3]}, {str(framework), str(nested)}) for command in calls[:-1]: self.assertEqual(command[command.index("--sign") + 1], "Synthetic Identity With Spaces") diff --git a/test/outgoing_reply_test.dart b/test/outgoing_reply_test.dart new file mode 100644 index 00000000..96e60cfb --- /dev/null +++ b/test/outgoing_reply_test.dart @@ -0,0 +1,107 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/modules/messages.dart'; +import 'package:komet/backend/modules/outgoing_reply.dart'; + +const int _me = 1; +const int _chatId = 900201; +const int _peer = 900301; + +CachedMessage _message( + String id, { + int sender = _me, + Map? payload, +}) => CachedMessage( + id: id, + accountId: _me, + chatId: _chatId, + senderId: sender, + text: 'синтетика', + time: 1700000000000, + payload: payload, +); + +void main() { + test('a message still waiting for its server id cannot be replied to', () { + expect(OutgoingReply.of(_message('temp_1_2', sender: _peer)), isNull); + expect(OutgoingReply.of(null), isNull); + }); + + test('the optimistic message carries the full quote', () { + final reply = OutgoingReply.of(_message('42', sender: _peer))!; + final quoted = reply.quotedIn(_message('temp_9_9')); + final link = quoted.payload!['link'] as Map; + expect(link['type'], 'REPLY'); + expect(link['chatId'], _chatId); + expect((link['message'] as Map)['id'], 42); + expect((link['message'] as Map)['sender'], _peer); + }); + + test('a cross-chat reply points at the source chat', () { + final reply = OutgoingReply.of( + _message('42', sender: _peer), + sourceChatId: 777, + )!; + expect(reply.linkIn(_chatId)['chatId'], 777); + }); + + test('the server echo keeps the local quote when it lacks the message', () { + final reply = OutgoingReply.of(_message('42', sender: _peer))!; + final local = reply.quotedIn(_message('temp_9_9')); + final echo = _message( + '100', + payload: { + 'link': {'type': 'REPLY', 'chatId': _chatId, 'messageId': 42}, + }, + ); + final kept = OutgoingReply.keepQuote(echo, local); + expect(((kept.payload!['link'] as Map)['message'] as Map)['id'], 42); + expect(OutgoingReply.keepQuote(_message('101'), null).payload, isNull); + }); + + test('a full quote from the server wins over the local one', () { + final reply = OutgoingReply.of(_message('42', sender: _peer))!; + final local = reply.quotedIn(_message('temp_9_9')); + final echo = _message( + '100', + payload: { + 'link': { + 'type': 'REPLY', + 'chatId': _chatId, + 'message': {'id': 42, 'sender': _peer, 'text': 'с сервера'}, + }, + }, + ); + final kept = OutgoingReply.keepQuote(echo, local); + expect( + ((kept.payload!['link'] as Map)['message'] as Map)['text'], + 'с сервера', + ); + }); + + test('a failed message gives back the reply it was sent with', () { + final original = OutgoingReply.of( + _message('42', sender: _peer), + sourceChatId: 777, + )!; + final failed = original.quotedIn(_message('temp_9_9')); + final restored = OutgoingReply.fromPayload( + failed.payload, + accountId: _me, + chatId: _chatId, + )!; + expect(restored.messageId, 42); + expect(restored.sourceChatId, 777); + expect(restored.linkIn(_chatId), original.linkIn(_chatId)); + }); + + test('a message without a reply restores none', () { + expect( + OutgoingReply.fromPayload( + _message('temp_1_1').payload, + accountId: _me, + chatId: _chatId, + ), + isNull, + ); + }); +} diff --git a/test/per_chat_json_store_test.dart b/test/per_chat_json_store_test.dart index ed77635a..36a15fce 100644 --- a/test/per_chat_json_store_test.dart +++ b/test/per_chat_json_store_test.dart @@ -75,6 +75,9 @@ void main() { expect(store.valueOf(101, 12), isTrue); expect(store.valueOf(202, 22), isTrue); expect(store.revision.value, 2); + expect(persisted, isEmpty); + await store.flush(); + expect(persisted, hasLength(1)); expect(persisted.last, {'101/11': false, '101/12': true, '202/22': true}); final restored = _ChatFlags(); addTearDown(restored.revision.dispose); @@ -115,6 +118,7 @@ void main() { await Future.wait([loading, deletion]); expect(store.valueOf(101, 11), isNull); expect(store.valueOf(202, 11), isFalse); + await store.flush(); expect(persisted, {'202/11': false}); expect(store.revision.value, 1); }, @@ -151,6 +155,7 @@ void main() { expect(loadCount, 2); expect(store.valueOf(101, 11), isTrue); expect(store.valueOf(202, 22), isFalse); + await store.flush(); expect(persisted, {'101/11': true, '202/22': false}); }, ); diff --git a/test/photo_viewer_placeholder_test.dart b/test/photo_viewer_placeholder_test.dart new file mode 100644 index 00000000..99688d6f --- /dev/null +++ b/test/photo_viewer_placeholder_test.dart @@ -0,0 +1,121 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/widgets/attachment/photo_hero.dart'; +import 'package:komet/frontend/widgets/photo_viewer.dart'; +import 'package:komet/frontend/widgets/small_spinner.dart'; +import 'package:komet/l10n/app_localizations.dart'; +import 'package:komet/models/attachment.dart'; + +Finder _insideViewer(bool Function(Widget widget) test) => find + .byElementPredicate( + (element) => + test(element.widget) && + element.findAncestorWidgetOfExactType() != null, + ); + +Finder get _preview => + _insideViewer((w) => w is Image && w.image is RawImageProvider); + +Finder get _full => _insideViewer((w) => w is Image && w.image is FileImage); + +double _spinnerOpacity(WidgetTester tester) => tester + .widget( + find.ancestor( + of: find.byType(SmallSpinner), + matching: find.byType(AnimatedOpacity), + ), + ) + .opacity; + +Future _photoFile(WidgetTester tester) async { + final file = (await tester.runAsync(() async { + final directory = await Directory.systemTemp.createTemp('viewer_photo'); + final image = await createTestImage(width: 40, height: 20); + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + image.dispose(); + final file = File('${directory.path}/photo.png'); + await file.writeAsBytes(bytes!.buffer.asUint8List()); + return file; + }))!; + addTearDown(() => file.parent.deleteSync(recursive: true)); + return file; +} + +Future _open(WidgetTester tester, PhotoAttachment photo) async { + final image = (await tester.runAsync( + () => createTestImage(width: 40, height: 20), + ))!; + addTearDown(image.dispose); + final hero = PhotoHeroController( + origin: () => const Rect.fromLTWH(20, 60, 80, 40), + image: RawImageProvider(image), + ); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('ru'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + PhotoHeroRoute( + hero: hero, + builder: (_) => PhotoViewerScreen(photos: [photo], hero: hero), + ), + ), + child: const Text('open'), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); +} + +void main() { + testWidgets('keeps the opened photo on screen while the full one loads', ( + tester, + ) async { + await _open( + tester, + const PhotoAttachment(baseUrl: 'https://example.test/full.jpg'), + ); + + expect(_preview, findsOneWidget); + expect(tester.getRect(_preview).width, greaterThan(0)); + expect(_spinnerOpacity(tester), 0); + + await tester.pump(const Duration(milliseconds: 150)); + await tester.pump(const Duration(milliseconds: 200)); + expect(_preview, findsOneWidget); + expect(_spinnerOpacity(tester), 1); + }); + + testWidgets('swaps the preview for the full photo once it is decoded', ( + tester, + ) async { + final file = await _photoFile(tester); + await _open(tester, PhotoAttachment(localPath: file.path)); + + for (var i = 0; i < 20 && _full.evaluate().isEmpty; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(); + } + for (var i = 0; i < 20 && _preview.evaluate().isNotEmpty; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(const Duration(milliseconds: 100)); + } + + expect(_full, findsOneWidget); + expect(_preview, findsNothing); + expect(find.byType(SmallSpinner), findsNothing); + }); +} diff --git a/test/photo_viewer_test.dart b/test/photo_viewer_test.dart index c0213f26..0522b738 100644 --- a/test/photo_viewer_test.dart +++ b/test/photo_viewer_test.dart @@ -108,8 +108,11 @@ void main() { await gesture.up(timeStamp: const Duration(milliseconds: 500)); await tester.pump(); - final flight = find.byWidgetPredicate( - (widget) => widget is Image && widget.image is RawImageProvider, + final flight = find.byElementPredicate( + (element) => + element.widget is Image && + (element.widget as Image).image is RawImageProvider && + element.findAncestorWidgetOfExactType() == null, ); expect(flight, findsOneWidget); expect(tester.getRect(flight).top, closeTo(draggedPhoto.top, 1)); @@ -315,8 +318,15 @@ void main() { ) async { await _pumpViewer(tester, message: _message()); - double chromeOpacity() => - tester.widget(find.byType(AnimatedOpacity)).opacity; + double chromeOpacity() => tester + .widget( + find.byElementPredicate( + (element) => + element.widget is AnimatedOpacity && + element.findAncestorWidgetOfExactType() == null, + ), + ) + .opacity; expect(chromeOpacity(), 1); diff --git a/test/seed_scheme_test.dart b/test/seed_scheme_test.dart index 6eeced1d..9a817d69 100644 --- a/test/seed_scheme_test.dart +++ b/test/seed_scheme_test.dart @@ -23,6 +23,8 @@ bool _isGray(Color color) { return r == g && g == b; } +const Set _neutralPresets = {'komet', 'graphite', 'paper'}; + Future _seedOf(String themeId) async { final seed = await computeWallpaperSeed(ChatWallpaper.theme(themeId)); expect(seed, isNotNull, reason: themeId); @@ -30,20 +32,26 @@ Future _seedOf(String themeId) async { } void main() { - test('серые обои дают серый акцент, а не синий', () async { - final seed = await _seedOf('graphite'); - - expect(isAchromaticSeed(seed), isTrue); - for (final brightness in Brightness.values) { - final scheme = schemeFromSeed(seed, brightness); - expect(_isGray(scheme.primary), isTrue, reason: '$brightness'); - expect(_isGray(scheme.secondaryContainer), isTrue, reason: '$brightness'); + test('нейтральные обои дают серый акцент, а не синий', () async { + for (final id in _neutralPresets) { + final seed = await _seedOf(id); + + expect(isAchromaticSeed(seed), isTrue, reason: id); + for (final brightness in Brightness.values) { + final scheme = schemeFromSeed(seed, brightness); + expect(_isGray(scheme.primary), isTrue, reason: '$id $brightness'); + expect( + _isGray(scheme.secondaryContainer), + isTrue, + reason: '$id $brightness', + ); + } } }); test('цветные встроенные обои остаются цветными', () async { for (final theme in kChatWallpaperThemes) { - if (theme.id == 'graphite') continue; + if (_neutralPresets.contains(theme.id)) continue; final seed = await _seedOf(theme.id); expect(isAchromaticSeed(seed), isFalse, reason: theme.id); diff --git a/test/story_quiet_views_test.dart b/test/story_quiet_views_test.dart new file mode 100644 index 00000000..0b407ac6 --- /dev/null +++ b/test/story_quiet_views_test.dart @@ -0,0 +1,161 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/backend/api.dart'; +import 'package:komet/backend/modules/stories.dart'; +import 'package:komet/core/config/komet_settings.dart'; +import 'package:komet/core/protocol/opcode_map.dart'; +import 'package:komet/core/protocol/packet.dart'; +import 'package:komet/core/storage/app_database.dart'; +import 'package:komet/models/story.dart'; +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +class _SyntheticPathProvider extends PathProviderPlatform + with MockPlatformInterfaceMixin { + _SyntheticPathProvider(this.path); + + final String path; + + @override + Future getApplicationSupportPath() async => path; +} + +const _account = 101; +const _owner = StoryOwner(ownerId: 202); + +Map _preview({int readCount = 0}) => { + 'owner': _owner.toMap(), + 'updateTime': 1000, + 'totalCount': 2, + 'readCount': readCount, +}; + +Map _story(int id, int now) => { + 'id': id, + 'owner': _owner.toMap(), + 'time': now, + 'expiration': const Duration(hours: 24).inMilliseconds, +}; + +class _StoriesApi extends Api { + _StoriesApi(this.now); + + final int now; + int serverReadCount = 0; + final sentOpcodes = []; + + @override + SessionState get state => SessionState.online; + + @override + Future sendRequest( + int opcode, + Map payload, { + bool silent = false, + void Function()? beforeSend, + }) async { + sentOpcodes.add(opcode); + final Object body = switch (opcode) { + Opcode.storiesList => { + 'storiesPreviews': [_preview(readCount: serverReadCount)], + }, + Opcode.storiesGetByOwner => { + 'storiesPreviews': [_preview(readCount: serverReadCount)], + 'peerStories': [ + { + 'owner': _owner.toMap(), + 'stories': [_story(1, now), _story(2, now)], + }, + ], + }, + _ => {}, + }; + if (opcode == Opcode.storiesMark) serverReadCount++; + return Packet(cmd: CmdType.ok, payload: body); + } +} + +Future _drainWrites() async { + await Future.delayed(Duration.zero); + await AppDatabase.getSyncValue(_account, 'stories_previews'); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late _StoriesApi api; + late StoriesModule stories; + + setUpAll(AppDatabase.init); + + setUp(() async { + SharedPreferences.setMockInitialValues({'active_account_id': '$_account'}); + final directory = await Directory.systemTemp.createTemp('synthetic_story'); + final previousProvider = PathProviderPlatform.instance; + PathProviderPlatform.instance = _SyntheticPathProvider(directory.path); + await databaseFactory.setDatabasesPath(directory.path); + await AppDatabase.saveProfile(ProfileData.stub(_account)); + api = _StoriesApi(DateTime.now().millisecondsSinceEpoch); + stories = StoriesModule(api); + addTearDown(() async { + KometSettings.antiStoryView.value = false; + await _drainWrites(); + await api.dispose(); + await AppDatabase.close(); + PathProviderPlatform.instance = previousProvider; + await directory.delete(recursive: true); + }); + }); + + test('a quiet view never reaches the server but dims the ring', () async { + KometSettings.antiStoryView.value = true; + await stories.loadFeed(); + await stories.getByOwner(_owner); + api.sentOpcodes.clear(); + + expect(await stories.mark(_owner, 1), isTrue); + expect(api.sentOpcodes, isEmpty); + expect(stories.previewFor(_owner.ownerId)!.readCount, 1); + expect(stories.previews.single.hasUnread, isTrue); + + await stories.mark(_owner, 2); + expect(api.sentOpcodes, isEmpty); + expect(stories.previewFor(_owner.ownerId)!.readCount, 2); + expect(stories.previewOf(_owner.ownerId)!.hasUnread, isFalse); + }); + + test('quiet views survive a fresh feed and a restart', () async { + KometSettings.antiStoryView.value = true; + await stories.loadFeed(); + await stories.getByOwner(_owner); + await stories.mark(_owner, 1); + + await stories.loadFeed(); + expect(stories.previewFor(_owner.ownerId)!.readCount, 1); + + await _drainWrites(); + final restarted = StoriesModule(api); + await restarted.loadCache(); + expect(restarted.previewFor(_owner.ownerId)!.readCount, 1); + }); + + test( + 'turning the mode off marks on the server without double counting', + () async { + KometSettings.antiStoryView.value = true; + await stories.loadFeed(); + await stories.getByOwner(_owner); + await stories.mark(_owner, 1); + + KometSettings.antiStoryView.value = false; + api.sentOpcodes.clear(); + await stories.mark(_owner, 1); + expect(api.sentOpcodes, [Opcode.storiesMark]); + + await stories.loadFeed(); + expect(stories.previewFor(_owner.ownerId)!.readCount, 1); + }, + ); +} diff --git a/test/story_viewer_controls_test.dart b/test/story_viewer_controls_test.dart new file mode 100644 index 00000000..f26ca622 --- /dev/null +++ b/test/story_viewer_controls_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/frontend/screens/stories/story_viewer_screen.dart'; + +void main() { + group('storyViewerMenuActions', () { + test('an own story offers save and delete', () { + expect(storyViewerMenuActions(isOwn: true), [ + StoryViewerMenuAction.save, + StoryViewerMenuAction.delete, + ]); + }); + + test('a foreign story respects its server capabilities', () { + expect( + storyViewerMenuActions( + isOwn: false, + opensProfile: true, + allowsHidingAuthor: true, + allowsSaving: true, + allowsComplaints: true, + ), + [ + StoryViewerMenuAction.profile, + StoryViewerMenuAction.hide, + StoryViewerMenuAction.save, + StoryViewerMenuAction.report, + ], + ); + expect(storyViewerMenuActions(isOwn: false), isEmpty); + }); + }); + + group('storySeekPosition', () { + const duration = Duration(seconds: 40); + + test('slides relative to the position where the hold started', () { + expect( + storySeekPosition( + start: const Duration(seconds: 10), + deltaX: 100, + viewportWidth: 400, + duration: duration, + ), + const Duration(seconds: 20), + ); + expect( + storySeekPosition( + start: const Duration(seconds: 20), + deltaX: -100, + viewportWidth: 400, + duration: duration, + ), + const Duration(seconds: 10), + ); + }); + + test('clamps seeking to the story boundaries', () { + expect( + storySeekPosition( + start: const Duration(seconds: 5), + deltaX: -500, + viewportWidth: 400, + duration: duration, + ), + Duration.zero, + ); + expect( + storySeekPosition( + start: const Duration(seconds: 35), + deltaX: 500, + viewportWidth: 400, + duration: duration, + ), + duration, + ); + }); + }); +} diff --git a/test/thumbhash_test.dart b/test/thumbhash_test.dart new file mode 100644 index 00000000..c6e71904 --- /dev/null +++ b/test/thumbhash_test.dart @@ -0,0 +1,37 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; +import 'package:komet/core/media/thumbhash.dart'; + +List _flatHash() => [ + 0x3F, + 0x08, + 0x02, + 0x05, + 0x00, + ...List.filled(20, 0x77), +]; + +void main() { + test('a hash without detail decodes to one flat colour', () { + final decoded = thumbHashToRgba(_flatHash())!; + expect(decoded.width, 23); + expect(decoded.height, 32); + for (var i = 0; i < decoded.rgba.length; i += 4) { + expect(decoded.rgba.sublist(i, i + 4), [255, 254, 252, 255]); + } + }); + + test('the png keeps the decoded size and pixels', () { + final png = thumbHashToPng(_flatHash())!; + final image = img.decodePng(png)!; + expect(image.width, 23); + expect(image.height, 32); + final pixel = image.getPixel(11, 20); + expect([pixel.r, pixel.g, pixel.b, pixel.a], [255, 254, 252, 255]); + }); + + test('truncated hashes are rejected instead of throwing', () { + expect(thumbHashToRgba(const [0x3F, 0x08]), isNull); + expect(thumbHashToRgba(_flatHash().sublist(0, 9)), isNull); + }); +} diff --git a/test/tlottie_engine_test.dart b/test/tlottie_engine_test.dart index f0a4554d..bdf3e802 100644 --- a/test/tlottie_engine_test.dart +++ b/test/tlottie_engine_test.dart @@ -138,4 +138,44 @@ void main() { expect(second.ready.value, second.frameCount); TlottieEngine.instance.release(second); }); + + test('a clip taken over in the frame its holder lets go keeps rendering', () async { + final libPath = Platform.environment['TLOTTIE_LIB']; + if (libPath == null || !File(libPath).existsSync()) { + markTestSkipped('set TLOTTIE_LIB to libkomet_tlottie.so to run'); + return; + } + TlottieEngine.debugLibraryPath = libPath; + final tmp = Directory.systemTemp.createTempSync('tlottie_handover_test'); + addTearDown(() => tmp.deleteSync(recursive: true)); + PathProviderPlatform.instance = _FakePathProvider(tmp.path); + + final json = File('assets/lottie/ic_settings.json').readAsStringSync(); + const url = 'poc://ic_settings_handover'; + final first = await TlottieEngine.instance.acquire( + url, + 384, + inlineJson: json, + ); + expect(first, isNotNull); + expect(first!.complete, isFalse); + + final takeover = TlottieEngine.instance.acquire( + url, + 384, + inlineJson: json, + ); + TlottieEngine.instance.release(first); + final second = await takeover; + expect(identical(second, first), isTrue, reason: 'clip handed over'); + + final deadline = DateTime.now().add(const Duration(seconds: 20)); + while (second!.ready.value < second.frameCount && + DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 20)); + } + expect(second.ready.value, second.frameCount); + expect(second.frameAt(second.frameCount - 1), isNotNull); + TlottieEngine.instance.release(second); + }); } diff --git a/test/whats_new_document_test.dart b/test/whats_new_document_test.dart new file mode 100644 index 00000000..77750a9f --- /dev/null +++ b/test/whats_new_document_test.dart @@ -0,0 +1,207 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/whats_new/spotlight_ids.dart'; +import 'package:komet/core/whats_new/whats_new_document.dart'; +import 'package:komet/frontend/widgets/spotlight.dart'; + +void main() { + group('notes', () { + test('inline links, whole-line targets and plain lines', () { + final document = WhatsNewDocument.parse(''' +// comment for writers +• Plain line. +• Open [the storage](#storage) to see it. +• Whole line goes to devices. → :settings/devices + +#storage + open :settings/storage +'''); + + expect(document.problems, isEmpty); + expect(document.notes, hasLength(3)); + expect(document.notes[0].target, isNull); + expect(document.notes[0].spans.single, isA()); + + final linked = document.notes[1].spans; + expect(linked.map((s) => s.text), [ + '• Open ', + 'the storage', + ' to see it.', + ]); + expect((linked[1] as WhatsNewLinkSpan).target.scenario, 'storage'); + + final whole = document.notes[2]; + expect(whole.text, '• Whole line goes to devices.'); + expect(whole.target?.link, 'https://max.ru/:settings/devices'); + + expect( + document.plainText, + '• Plain line.\n' + '• Open the storage to see it.\n' + '• Whole line goes to devices.', + ); + }); + + test('external links are kept as they are', () { + final document = WhatsNewDocument.parse( + '• Read [the post](https://example.test/post).', + ); + final span = document.notes.single.spans[1] as WhatsNewLinkSpan; + expect(span.target.link, 'https://example.test/post'); + }); + }); + + group('scenarios', () { + test('steps keep quoted text and escaped quotes', () { + final document = WhatsNewDocument.parse(''' +#tour + tab settings + hint ${SpotlightIds.settingsStorage} "Say \\"hi\\" here" + notify "Done" "Again" #tour2 + wait 300 +#tour2 + close +'''); + expect(document.problems, isEmpty); + final steps = document.scenarios['tour']!; + expect(steps.map((s) => s.command), [ + WhatsNewCommand.tab, + WhatsNewCommand.hint, + WhatsNewCommand.notify, + WhatsNewCommand.wait, + ]); + expect(steps[1].args, [SpotlightIds.settingsStorage, 'Say "hi" here']); + expect(steps[2].args, ['Done', 'Again', '#tour2']); + }); + + test('mistakes are reported with their line and dropped', () { + final document = WhatsNewDocument.parse(''' +• Broken [link](#missing). +#tour + tab gallery + highlight nowhere.button + jump + wait forever + notify "unclosed +'''); + expect(document.problems, [ + 'строка 3: tab chats | calls | contacts | settings', + 'строка 4: нет элемента «nowhere.button» (см. SpotlightIds)', + 'строка 5: неизвестная команда «jump»', + 'строка 6: wait <мс от 0 до 10000>', + 'строка 7: не закрыта кавычка', + 'строка 1: нет сценария #missing', + ]); + expect(document.scenarios['tour'], isEmpty); + }); + + test('check takes exactly one link', () { + final document = WhatsNewDocument.parse(''' +#tour + check https://synthetic.example/login + check #tour + check +'''); + expect(document.problems, [ + 'строка 3: check ждёт ссылку, а не «#tour»', + 'строка 4: check <ссылка>', + ]); + final steps = document.scenarios['tour']!; + expect(steps.single.command, WhatsNewCommand.check); + expect(steps.single.args, ['https://synthetic.example/login']); + }); + + test('only elements with an action can be tapped', () { + final document = WhatsNewDocument.parse(''' +#tour + tap ${SpotlightIds.settingsStorage} + tap ${SpotlightIds.storageLimit} +'''); + expect(document.problems, [ + 'строка 3: «${SpotlightIds.storageLimit}» нельзя нажать ' + '(см. SpotlightIds.tappable)', + ]); + expect(document.scenarios['tour'], hasLength(1)); + }); + + test('scenarios that run each other in a loop are reported', () { + final document = WhatsNewDocument.parse(''' +#a + run #b +#b + run #a +'''); + expect(document.problems.single, contains('зациклены')); + }); + }); + + test('shipped notes parse cleanly and languages stay in step', () { + final files = Directory('assets/whats_new') + .listSync() + .whereType() + .where((file) => file.path.endsWith('.txt')) + .toList(); + expect(files, isNotEmpty); + + final documents = { + for (final file in files) + file.path: WhatsNewDocument.parse(file.readAsStringSync()), + }; + for (final MapEntry(key: path, value: document) in documents.entries) { + expect(document.problems, isEmpty, reason: path); + } + final reference = documents.values.first; + for (final MapEntry(key: path, value: document) in documents.entries) { + expect( + document.scenarios.keys.toSet(), + reference.scenarios.keys.toSet(), + reason: '$path has a different set of scenarios', + ); + expect( + document.notes.length, + reference.notes.length, + reason: '$path has a different number of notes', + ); + } + }); + + testWidgets('a target far down a lazy list is scrolled to and found', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ListView.builder( + itemCount: 120, + itemBuilder: (context, index) => index == 90 + ? const SpotlightTarget( + id: SpotlightIds.storageLimit, + child: SizedBox(height: 60, child: Text('target')), + ) + : SizedBox(height: 60, child: Text('row $index')), + ), + ), + ), + ); + expect(find.text('target'), findsNothing); + + var done = false; + var found = false; + Spotlight.highlight(SpotlightIds.storageLimit).then((value) { + found = value; + done = true; + }); + for (var i = 0; i < 400 && !done; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + await tester.pump(const Duration(seconds: 2)); + + expect(found, isTrue); + final rect = tester.getRect(find.text('target')); + final screen = + Offset.zero & tester.view.physicalSize / tester.view.devicePixelRatio; + expect(screen.contains(rect.center), isTrue); + }); +} diff --git a/test/whats_new_runner_test.dart b/test/whats_new_runner_test.dart new file mode 100644 index 00000000..f31a8208 --- /dev/null +++ b/test/whats_new_runner_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:komet/core/whats_new/spotlight_ids.dart'; +import 'package:komet/core/whats_new/whats_new_document.dart'; +import 'package:komet/frontend/widgets/spotlight.dart'; +import 'package:komet/frontend/widgets/whats_new_runner.dart'; +import 'package:komet/main.dart' show KometApp; + +class _Section extends StatefulWidget { + const _Section(); + + @override + State<_Section> createState() => _SectionState(); +} + +class _SectionState extends State<_Section> { + bool _expanded = false; + + @override + Widget build(BuildContext context) { + return Column( + children: [ + SpotlightTarget( + id: SpotlightIds.settingsCustomization, + onActivate: () => setState(() => _expanded = true), + child: const SizedBox(height: 56, child: Text('section')), + ), + if (_expanded) + SpotlightTarget( + id: SpotlightIds.settingsAppearance, + onActivate: () => Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => const _Screen())), + child: const SizedBox(height: 56, child: Text('appearance')), + ), + ], + ); + } +} + +class _Screen extends StatelessWidget { + const _Screen(); + + @override + Widget build(BuildContext context) => Scaffold( + body: ListView.builder( + itemCount: 80, + itemBuilder: (context, index) => index == 60 + ? const SpotlightTarget( + id: SpotlightIds.appearanceAnimations, + child: SizedBox(height: 64, child: Text('animations switch')), + ) + : SizedBox(height: 64, child: Text('option $index')), + ), + ); +} + +Future _play(WidgetTester tester, Future run) async { + var done = false; + run.whenComplete(() => done = true); + for (var i = 0; i < 600 && !done; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + expect(done, isTrue, reason: 'scenario finished'); + await tester.pump(const Duration(seconds: 2)); +} + +void main() { + testWidgets('a scenario presses through a section to a deep switch', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + navigatorKey: KometApp.navigatorKey, + home: const Scaffold(body: _Section()), + ), + ); + final document = WhatsNewDocument.parse(''' +#tour + tap ${SpotlightIds.settingsCustomization} + tap ${SpotlightIds.settingsAppearance} + highlight ${SpotlightIds.appearanceAnimations} + hint ${SpotlightIds.appearanceAnimations} "Turn animations off here" +'''); + expect(document.problems, isEmpty); + + await _play( + tester, + WhatsNewRunner(document).run(const WhatsNewTarget.scenario('tour')), + ); + + expect(find.byType(_Screen), findsOneWidget); + final rect = tester.getRect(find.text('animations switch')); + final screen = + Offset.zero & tester.view.physicalSize / tester.view.devicePixelRatio; + expect(screen.contains(rect.center), isTrue); + expect(find.text('Turn animations off here'), findsOneWidget); + await tester.pump(const Duration(seconds: 6)); + }); + + testWidgets('steps after open still run once the screen is pushed', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + navigatorKey: KometApp.navigatorKey, + home: const Scaffold(body: _Section()), + ), + ); + final document = WhatsNewDocument.parse(''' +#tour + open https://example.test/release + tap ${SpotlightIds.settingsCustomization} +'''); + + await _play( + tester, + WhatsNewRunner(document).run(const WhatsNewTarget.scenario('tour')), + ); + + expect(find.text('appearance'), findsOneWidget); + }); + + testWidgets('tap refuses a target without an action', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: SpotlightTarget( + id: SpotlightIds.storageLimit, + child: SizedBox(height: 40), + ), + ), + ); + var result = true; + Spotlight.tap(SpotlightIds.storageLimit).then((value) => result = value); + for (var i = 0; i < 100; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + expect(result, isFalse); + }); +} diff --git a/tool/check_git_pins.sh b/tool/check_git_pins.sh new file mode 100755 index 00000000..d8a56dd0 --- /dev/null +++ b/tool/check_git_pins.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +lock="${1:-pubspec.lock}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +pins="$(awk ' + /^ [^ ].*:$/ { name = $1; sub(/:$/, "", name); ref = ""; url = "" } + $1 == "resolved-ref:" { ref = $2; gsub(/"/, "", ref) } + $1 == "url:" { url = $2; gsub(/"/, "", url) } + $1 == "source:" && $2 == "git" { print name, url, ref } +' "$lock")" + +if [ -z "$pins" ]; then + echo "в $lock нет git-зависимостей" + exit 0 +fi + +failed=0 +while read -r name url ref; do + repo="$work/$name" + if ! GIT_TERMINAL_PROMPT=0 git clone -q --mirror "$url" "$repo"; then + echo "::error file=$lock::$name: не удалось склонировать $url без учётки" + failed=1 + elif git -C "$repo" cat-file -e "$ref^{commit}" 2>/dev/null; then + echo "$name: $ref есть в $url" + else + echo "::error file=$lock::$name: $ref нет ни в одной ветке или теге $url, pub get с чистым кэшем упадёт" + failed=1 + fi +done <<< "$pins" + +exit "$failed" diff --git a/tool/get_token.py b/tool/get_token.py index a59dd91c..0ba3acbf 100755 --- a/tool/get_token.py +++ b/tool/get_token.py @@ -48,14 +48,14 @@ USER_AGENT = { "deviceType": "ANDROID", - "appVersion": "26.20.2", + "appVersion": "26.23.2", "osVersion": "Android 14", "timezone": "Europe/Moscow", "screen": "420dpi 420dpi 1080x2340", "pushDeviceType": "GCM", "arch": "arm64-v8a", "locale": "ru", - "buildNumber": 6758, + "buildNumber": 6779, "deviceName": "Rust", "deviceLocale": "ru", } @@ -64,10 +64,10 @@ "1684414033eb263e2c615f8b7df5ed8793850a07656304997fbf07e9e21e1e93" ) DEX_DIGEST = bytes.fromhex( - "0a6265f6e5d8231b9cba641f8c40475e6f3baeb06ed41b804b9bf7307aa4214e" + "38cff46f392dc1734c308be011c2f0d8da152a390b41063dbb2c913e3032f4b3" ) SO_DIGEST = bytes.fromhex( - "90e2fb8745b17b42a10182f8d8ac590e3fca5b311e2ce2d5144fa2c18cb3090d" + "634ecc42b246784d975f180b4fecf903df235cdf0476da47163a85630eb1a6a8" ) @@ -303,9 +303,9 @@ def main(): print("=" * 60) print() print("Дальше собери payload для ревьювера:") + print(" make -C native/crypto-core shared") print(f" printf '{{\"token\":\"{login_token}\"}}' | \\") - print(" cargo run -q --manifest-path native/komet_crypto/rust/Cargo.toml \\") - print(" --features blobtool --bin review_blob -- '<номер>' '<код>'") + print(" dart run tool/review_blob.dart '<номер>' '<код>'") finally: try: sock.close() diff --git a/tool/make_minimal_ios.dart b/tool/make_minimal_ios.dart index cfd7db21..2bd15941 100644 --- a/tool/make_minimal_ios.dart +++ b/tool/make_minimal_ios.dart @@ -4,6 +4,8 @@ import 'package:image/image.dart' as img; const _sizes = { 'ios/Runner/MinimalIcon@2x.png': 120, 'ios/Runner/MinimalIcon@3x.png': 180, + 'ios/Runner/MinimalIcon-76@2x.png': 152, + 'ios/Runner/MinimalIcon-83.5@2x.png': 167, }; void main() { diff --git a/tool/make_wallpaper_patterns.py b/tool/make_wallpaper_patterns.py new file mode 100644 index 00000000..1d331851 --- /dev/null +++ b/tool/make_wallpaper_patterns.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python3 +import math +import random +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +OUT_DIR = ROOT / "assets" / "wallpapers" / "patterns" + +STROKE = 1.3 + + +def fmt(value): + text = f"{value:.2f}".rstrip("0").rstrip(".") + return "0" if text in ("-0", "") else text + + +_samples = None + + +def _sample(points): + if _samples is not None: + _samples.extend(points) + + +def _arc_points(start, end, r, large, sweep, steps=24): + x1, y1 = start + x2, y2 = end + hx, hy = (x1 - x2) / 2, (y1 - y2) / 2 + d2 = hx * hx + hy * hy + if d2 == 0: + return [] + r = max(r, math.sqrt(d2)) + coef = math.sqrt(max(0.0, (r * r - d2) / d2)) + sign = -1 if large == sweep else 1 + cx = sign * coef * hy + (x1 + x2) / 2 + cy = -sign * coef * hx + (y1 + y2) / 2 + a1 = math.atan2(y1 - cy, x1 - cx) + a2 = math.atan2(y2 - cy, x2 - cx) + delta = a2 - a1 + if sweep and delta < 0: + delta += 2 * math.pi + if not sweep and delta > 0: + delta -= 2 * math.pi + return [ + (cx + r * math.cos(a1 + delta * k / steps), cy + r * math.sin(a1 + delta * k / steps)) + for k in range(steps + 1) + ] + + +class Path2: + def __init__(self, scale): + self.s = scale + self.parts = [] + self.pen = (0.0, 0.0) + + def _p(self, x, y): + return f"{fmt(x * self.s)} {fmt(y * self.s)}" + + def _to(self, x, y): + self.pen = (x * self.s, y * self.s) + _sample([self.pen]) + + def move(self, x, y): + self.parts.append("M" + self._p(x, y)) + self._to(x, y) + return self + + def line(self, x, y): + self.parts.append("L" + self._p(x, y)) + self._to(x, y) + return self + + def quad(self, cx, cy, x, y): + p0, s = self.pen, self.s + _sample([ + ( + (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * cx * s + t * t * x * s, + (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * cy * s + t * t * y * s, + ) + for t in (k / 10 for k in range(11)) + ]) + self.parts.append("Q" + self._p(cx, cy) + " " + self._p(x, y)) + self._to(x, y) + return self + + def cubic(self, x1, y1, x2, y2, x, y): + p0, s = self.pen, self.s + _sample([ + ( + (1 - t) ** 3 * p0[0] + 3 * (1 - t) ** 2 * t * x1 * s + + 3 * (1 - t) * t * t * x2 * s + t**3 * x * s, + (1 - t) ** 3 * p0[1] + 3 * (1 - t) ** 2 * t * y1 * s + + 3 * (1 - t) * t * t * y2 * s + t**3 * y * s, + ) + for t in (k / 12 for k in range(13)) + ]) + self.parts.append( + "C" + self._p(x1, y1) + " " + self._p(x2, y2) + " " + self._p(x, y) + ) + self._to(x, y) + return self + + def arc(self, r, x, y, large=0, sweep=1, ry=None): + ry = r if ry is None else ry + _sample(_arc_points(self.pen, (x * self.s, y * self.s), r * self.s, large, sweep)) + self.parts.append( + f"A{fmt(r * self.s)} {fmt(ry * self.s)} 0 {large} {sweep} " + + self._p(x, y) + ) + self._to(x, y) + return self + + def close(self): + self.parts.append("Z") + return self + + def poly(self, points, closed=False): + first, *rest = points + self.move(*first) + for point in rest: + self.line(*point) + if closed: + self.close() + return self + + def smooth(self, points, closed=False, tension=0.5): + n = len(points) + if n < 3: + return self.poly(points, closed) + pts = points + points[:2] if closed else points + self.move(*pts[0]) + count = n if closed else n - 1 + for i in range(count): + p0 = pts[i - 1] if (i > 0 or closed) else pts[i] + p1 = pts[i] + p2 = pts[(i + 1) % len(pts)] if closed else pts[i + 1] + p3 = ( + pts[(i + 2) % len(pts)] + if closed + else (pts[i + 2] if i + 2 < n else pts[i + 1]) + ) + c1 = ( + p1[0] + (p2[0] - p0[0]) * tension / 3, + p1[1] + (p2[1] - p0[1]) * tension / 3, + ) + c2 = ( + p2[0] - (p3[0] - p1[0]) * tension / 3, + p2[1] - (p3[1] - p1[1]) * tension / 3, + ) + self.cubic(*c1, *c2, *p2) + if closed: + self.close() + return self + + def svg(self): + return f'' + + +def circle(cx, cy, r, s, filled=False): + _sample([polar(cx * s, cy * s, r * s, a) for a in range(0, 360, 15)]) + extra = ' fill="#fff" stroke="none"' if filled else "" + return f'' + + +def polar(cx, cy, r, degrees): + a = math.radians(degrees) + return (cx + r * math.cos(a), cy + r * math.sin(a)) + + +def sparkle_path(s, size=1.0, cx=0.0, cy=0.0): + r = 5 * size + pinch = 1.1 * size + p = Path2(s).move(cx, cy - r) + p.quad(cx + pinch, cy - pinch, cx + r, cy) + p.quad(cx + pinch, cy + pinch, cx, cy + r) + p.quad(cx - pinch, cy + pinch, cx - r, cy) + p.quad(cx - pinch, cy - pinch, cx, cy - r) + return p.close().svg() + + +# Every motif draws around (0, 0) inside a circle of radius ~50 units; +# the scale turns units into pixels so the stroke stays one width. + + +def comet(s): + head, radius = (13, -13), 10.5 + ux, uy = math.cos(math.radians(-45)), math.sin(math.radians(-45)) + nx, ny = -uy, ux + out = [circle(head[0], head[1], radius, s)] + out.append( + Path2(s) + .move(*polar(*head, 6.2, 190)) + .arc(6.2, *polar(*head, 6.2, 250), 0, 1) + .svg() + ) + tails = ( + (1, 46, 5.5), + (0, 30, 2.0), + (-1, 38, -4.5), + ) + for side, length, bend in tails: + if side == 0: + start = (head[0] - ux * radius, head[1] - uy * radius) + else: + start = (head[0] + nx * radius * side, head[1] + ny * radius * side) + end = (start[0] - ux * length, start[1] - uy * length) + mid = ( + (start[0] + end[0]) / 2 + nx * bend, + (start[1] + end[1]) / 2 + ny * bend, + ) + out.append(Path2(s).move(*start).quad(*mid, *end).svg()) + return out + +def crescent_path(s, r_out, r_in, shift): + d = math.hypot(*shift) + a = (r_out**2 - r_in**2 + d**2) / (2 * d) + h = math.sqrt(r_out**2 - a**2) + ux, uy = shift[0] / d, shift[1] / d + bx, by = ux * a, uy * a + p1 = (bx - uy * h, by + ux * h) + p2 = (bx + uy * h, by - ux * h) + return Path2(s).move(*p1).arc(r_out, *p2, 1, 1).arc(r_in, *p1, 1, 0).close() + + +def crescent(s): + out = [crescent_path(s, 27, 22, (11, -7)).svg()] + out.append(circle(-13, 3, 3.4, s)) + out.append(circle(-7, 15, 2.1, s)) + out.append(circle(-17, -9, 1.6, s)) + out.append(sparkle_path(s, 0.75, 22, -20)) + return out + +def ringed_planet(s): + r = 17 + tilt = math.radians(-20) + rx, ry = 36, 9.5 + gap = 2.6 + + def ring_point(t): + x, y = rx * math.cos(t), ry * math.sin(t) + return ( + x * math.cos(tilt) - y * math.sin(tilt), + x * math.sin(tilt) + y * math.cos(tilt), + ) + + def runs(samples): + result, current = [], [] + for point, visible in samples: + if visible: + current.append(point) + elif current: + result.append(current) + current = [] + if current: + result.append(current) + return result + + ring = [] + for i in range(0, 360, 2): + t = math.radians(i) + point = ring_point(t) + front = math.sin(t) > 0 + hidden = not front and math.hypot(*point) < r + gap + ring.append((point, not hidden)) + if ring[0][1] and ring[-1][1]: + k = next(i for i, (_, visible) in enumerate(ring) if not visible) + ring = ring[k:] + ring[:k] + front_points = [ + ring_point(math.radians(i)) for i in range(0, 181, 1) + ] + + def near_front(point): + return min(math.dist(point, q) for q in front_points) < gap + + planet = [] + for i in range(0, 360, 2): + point = polar(0, 0, r, i) + planet.append((point, not near_front(point))) + if planet[0][1] and planet[-1][1]: + k = next(i for i, (_, visible) in enumerate(planet) if not visible) + planet = planet[k:] + planet[:k] + + out = [] + for run in runs(ring) + runs(planet): + if len(run) > 2: + out.append(Path2(s).smooth(run[::2] + [run[-1]]).svg()) + out.append( + Path2(s).move(*polar(0, 0, r, 215)).quad(-2, -11, *polar(0, 0, r, 305)).svg() + ) + return out + +def telescope(s): + out = [] + tube = Path2(s).move(-28, 6).line(18, -12).line(22, -2).line(-24, 16).close() + out.append(tube.svg()) + out.append(Path2(s).move(18, -12).line(24, -14.5).line(28.5, -3).line(22, -2).svg()) + out.append(Path2(s).move(-28, 6).line(-34, 8.5).line(-31, 16.5).line(-24, 16).svg()) + out.append(Path2(s).move(-4, -3).line(-1, 5).svg()) + pivot = (0, 10) + out.append(circle(*pivot, 2.6, s)) + for foot in ((-16, 40), (1, 42), (17, 39)): + start = (pivot[0] + (foot[0] - pivot[0]) * 0.09, pivot[1] + 2.6) + out.append(Path2(s).move(*start).line(*foot).svg()) + out.append(Path2(s).move(-10, 28).line(10, 27).svg()) + return out + + +def satellite(s): + out = [] + out.append(Path2(s).poly([(-8, -9), (8, -9), (8, 9), (-8, 9)], closed=True).svg()) + out.append(Path2(s).move(-8, -2).line(8, -2).svg()) + for side in (-1, 1): + x0 = side * 8 + x1 = side * 13 + out.append(Path2(s).move(x0, 0).line(x1, 0).svg()) + xa, xb = side * 13, side * 39 + lo, hi = min(xa, xb), max(xa, xb) + out.append(Path2(s).poly([(lo, -8), (hi, -8), (hi, 8), (lo, 8)], closed=True).svg()) + for frac in (1 / 3, 2 / 3): + x = lo + (hi - lo) * frac + out.append(Path2(s).move(x, -8).line(x, 8).svg()) + out.append(Path2(s).move(lo, 0).line(hi, 0).svg()) + out.append(Path2(s).move(0, -9).line(0, -15).svg()) + out.append(Path2(s).move(-7, -15).quad(0, -24, 7, -15).close().svg()) + out.append(circle(0, -19.5, 1.2, s, filled=True)) + return out + + +def observatory(s): + out = [] + out.append(Path2(s).poly([(-26, 6), (26, 6), (26, 30), (-26, 30)], closed=True).svg()) + out.append(Path2(s).move(-22, 6).arc(22, 22, 6, 0, 1).svg()) + out.append(Path2(s).move(-4.5, -15.4).line(-4.5, 6).svg()) + out.append(Path2(s).move(4.5, -15.4).line(4.5, 6).svg()) + out.append(Path2(s).move(-1.8, -15.9).line(12, -33).line(17.5, -29).line(4.5, -12).svg()) + out.append( + Path2(s).move(-5, 30).line(-5, 21).arc(5, 5, 21, 0, 1).line(5, 30).svg() + ) + out.append(Path2(s).move(-31, 30).line(31, 30).svg()) + out.append(circle(-15, 17, 2.4, s)) + out.append(circle(15, 17, 2.4, s)) + return out + +def asteroid(s, seed): + rnd = random.Random(seed) + points = [] + for i in range(8): + angle = i * 45 + rnd.uniform(-12, 12) + radius = 15 * rnd.uniform(0.82, 1.1) + points.append(polar(0, 0, radius, angle)) + out = [Path2(s).smooth(points, closed=True, tension=0.9).svg()] + out.append(circle(-4, -3, 3.4, s)) + out.append(circle(5, 5, 2.2, s)) + out.append(circle(6, -6, 1.3, s)) + return out + + +def moon_phases(s): + out = [] + radius = 5.6 + step = 15.5 + for i, bulge in enumerate((0.62, 0.0, -0.62, None)): + cx = -step * 1.5 + i * step + out.append(circle(cx, 0, radius, s)) + top, bottom = (cx, -radius), (cx, radius) + if bulge is None: + out.append(circle(cx - 1.8, -1.4, 1.5, s)) + out.append(circle(cx + 2.2, 2.2, 1.0, s)) + elif bulge == 0: + out.append(Path2(s).move(*top).line(*bottom).svg()) + else: + out.append( + Path2(s).move(*top).quad(cx + bulge * radius * 2.0, 0, *bottom).svg() + ) + return out + +CONSTELLATIONS = ( + ( + [(-28, -6), (-14, -16), (0, -10), (12, -18), (26, -4), (14, 12)], + [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 2)], + ), + ( + [(-30, -8), (-16, 10), (-2, -4), (12, 12), (28, -6)], + [(0, 1), (1, 2), (2, 3), (3, 4)], + ), + ( + [(-18, -22), (16, -20), (-6, -2), (2, 0), (10, 2), (-20, 22), (18, 20), (6, 12)], + [(0, 2), (1, 4), (2, 3), (3, 4), (2, 5), (4, 6), (3, 7)], + ), +) + + +def constellation(s, variant): + stars, links = CONSTELLATIONS[variant] + rnd = random.Random(variant * 31 + 5) + stars = [(x + rnd.uniform(-1.5, 1.5), y + rnd.uniform(-1.5, 1.5)) for x, y in stars] + out = [Path2(s).move(*stars[a]).line(*stars[b]).svg() for a, b in links] + degree = [sum(i in link for link in links) for i in range(len(stars))] + for i, (x, y) in enumerate(stars): + out.append(circle(x, y, 2.1 if degree[i] >= 2 and i % 2 else 1.6, s, filled=True)) + return out + +def orbit(s): + rx, ry = 24, 9 + moon_t = math.radians(-35) + moon = (rx * math.cos(moon_t), ry * math.sin(moon_t)) + moon_r = 3 + points = [] + for i in range(0, 361, 3): + t = math.radians(i) + points.append((rx * math.cos(t), ry * math.sin(t))) + runs, current = [], [] + for point in points: + if math.dist(point, moon) < moon_r + 2.2: + if current: + runs.append(current) + current = [] + else: + current.append(point) + if current: + runs.append(current) + if len(runs) > 1: + runs[0] = runs[-1] + runs[0] + runs.pop() + out = [circle(0, 0, 6.5, s), circle(*moon, moon_r, s)] + for run in runs: + out.append(Path2(s).smooth(run[::2] + [run[-1]]).svg()) + return out + +def rocket(s): + out = [] + body = Path2(s).move(0, -30).cubic(9, -20, 9.5, 2, 7, 16).line(-7, 16) + body.cubic(-9.5, 2, -9, -20, 0, -30).close() + out.append(body.svg()) + out.append(circle(0, -10, 3.6, s)) + out.append(Path2(s).move(7.6, 4).quad(15, 9, 14, 20).line(7, 16).svg()) + out.append(Path2(s).move(-7.6, 4).quad(-15, 9, -14, 20).line(-7, 16).svg()) + out.append(Path2(s).move(-3.5, 19.5).quad(-2, 26, 0, 30).quad(2, 26, 3.5, 19.5).svg()) + return out + + +def shooting_star(s): + star = (6, -6) + ux, uy = math.cos(math.radians(-45)), math.sin(math.radians(-45)) + nx, ny = -uy, ux + out = [sparkle_path(s, 0.95, *star)] + for side, length in ((1, 15), (-1, 10)): + start = ( + star[0] - ux * 6.5 + nx * 2.4 * side, + star[1] - uy * 6.5 + ny * 2.4 * side, + ) + end = (start[0] - ux * length, start[1] - uy * length) + out.append(Path2(s).move(*start).line(*end).svg()) + return out + +def star5(s): + points = [] + for i in range(10): + radius = 5 if i % 2 == 0 else 2.3 + points.append(polar(0, 0, radius, -90 + i * 36)) + return [Path2(s).poly(points, closed=True).svg()] + + +def sparkle(s): + return [sparkle_path(s, 1.0)] + + +def dot(s): + return [circle(0, 0, 1.5, s, filled=True)] + + +def ring(s): + return [circle(0, 0, 2.6, s)] + + +def plus(s): + return [Path2(s).move(-3, 0).line(3, 0).svg(), Path2(s).move(0, -3).line(0, 3).svg()] + + +def tiny_crescent(s): + return [crescent_path(s, 5.2, 4.2, (2.2, -1.4)).svg()] + +MOTIFS = { + "comet": (comet, 42), + "crescent": (crescent, 30), + "ringed_planet": (ringed_planet, 38), + "telescope": (telescope, 44), + "satellite": (satellite, 40), + "observatory": (observatory, 38), + "asteroid_a": (lambda s: asteroid(s, 7), 17), + "asteroid_b": (lambda s: asteroid(s, 19), 17), + "asteroid_c": (lambda s: asteroid(s, 42), 17), + "moon_phases": (moon_phases, 27), + "constellation_a": (lambda s: constellation(s, 0), 30), + "constellation_b": (lambda s: constellation(s, 1), 30), + "constellation_c": (lambda s: constellation(s, 2), 30), + "orbit": (orbit, 26), + "rocket": (rocket, 32), + "shooting_star": (shooting_star, 17), + "star5": (star5, 5.5), + "sparkle": (sparkle, 5.5), + "dot": (dot, 2), + "ring": (ring, 3), + "plus": (plus, 3.5), + "tiny_crescent": (tiny_crescent, 5.5), +} + + +def group(elements, x, y, angle, mirror=False): + body = "".join(elements) + flip = " scale(-1 1)" if mirror else "" + return ( + f'' + f"{body}" + ) + + +def svg_document(width, height, body, background=None, color="#fff"): + bg = f'' if background else "" + return ( + f'' + f"{bg}{body}" + ) + + +def motif_sheet(scale=2.2): + names = list(MOTIFS) + cols = 5 + cell = 130 + rows = math.ceil(len(names) / cols) + body = [] + for i, name in enumerate(names): + fn, _ = MOTIFS[name] + cx = (i % cols) * cell + cell / 2 + cy = (i // cols) * cell + cell / 2 + size = scale if MOTIFS[name][1] > 12 else scale * 2.4 + body.append(group(fn(size * 0.5), cx, cy, 0)) + return svg_document(cols * cell, rows * cell, "".join(body), background="#15171a", color="#c8d0da") + + +TILE = 900 +UNIT = 1.2 +MEDIUM_UNIT = 1.12 +FILLER_UNIT = 1.1 + +MIRRORABLE = { + "comet", + "telescope", + "observatory", + "crescent", + "rocket", + "ringed_planet", + "constellation_a", + "constellation_b", + "constellation_c", + "asteroid_a", + "asteroid_b", + "asteroid_c", +} + + +class Piece: + def __init__(self, name, count, rotate, unit=UNIT, gap=6.0): + self.name = name + self.count = count + self.rotate = rotate + self.unit = unit + self.gap = gap + + +KOMET_PIECES = [ + Piece("comet", 7, 20, gap=4.0), + Piece("crescent", 7, 40, gap=4.0), + Piece("ringed_planet", 7, 28, gap=4.0), + Piece("telescope", 3, 14, gap=4.0), + Piece("observatory", 2, 8, gap=4.0), + Piece("satellite", 4, 35, unit=UNIT * 0.85, gap=4.0), + Piece("rocket", 6, 35, gap=4.0), + Piece("comet", 10, 20, unit=UNIT * 0.65, gap=3.5), + Piece("moon_phases", 3, 20, unit=MEDIUM_UNIT * 1.1, gap=3.5), + Piece("constellation_a", 5, 180, unit=MEDIUM_UNIT, gap=3.5), + Piece("constellation_b", 5, 180, unit=MEDIUM_UNIT, gap=3.5), + Piece("constellation_c", 4, 180, unit=MEDIUM_UNIT, gap=3.5), + Piece("orbit", 11, 35, unit=MEDIUM_UNIT, gap=3.5), + Piece("asteroid_a", 6, 180, unit=MEDIUM_UNIT, gap=3.0), + Piece("asteroid_b", 6, 180, unit=MEDIUM_UNIT, gap=3.0), + Piece("asteroid_c", 5, 180, unit=MEDIUM_UNIT, gap=3.0), + Piece("shooting_star", 32, 30, unit=MEDIUM_UNIT, gap=3.0), + Piece("tiny_crescent", 22, 180, unit=FILLER_UNIT, gap=3.0), + Piece("star5", 12, 180, unit=FILLER_UNIT, gap=3.0), + Piece("sparkle", 26, 25, unit=FILLER_UNIT, gap=3.0), + Piece("ring", 34, 0, unit=FILLER_UNIT, gap=2.5), + Piece("plus", 26, 45, unit=FILLER_UNIT, gap=2.5), + Piece("dot", 90, 0, unit=FILLER_UNIT, gap=2.0), +] + + +def measured_radius(name): + global _samples + _samples = [] + try: + MOTIFS[name][0](1.0) + points = _samples + finally: + _samples = None + return max(math.hypot(x, y) for x, y in points) + STROKE / 2 + + +SAME_MOTIF_SPACING = 70 +FILLERS = {"star5", "sparkle", "dot", "ring", "plus", "tiny_crescent"} + + +def _kin(name): + if name in FILLERS: + return None + return name.rsplit("_", 1)[0] if name[-2:] in ("_a", "_b", "_c") else name + + +def torus_distance(a, b, size): + dx = abs(a[0] - b[0]) + dy = abs(a[1] - b[1]) + return math.hypot(min(dx, size - dx), min(dy, size - dy)) + + +def compose(pieces, size, seed, candidates=140): + rnd = random.Random(seed) + placed = [] + for piece in pieces: + nominal = measured_radius(piece.name) + for _ in range(piece.count): + jitter = rnd.uniform(0.92, 1.08) + scale = piece.unit * jitter + radius = nominal * scale + best, best_clearance = None, -1e9 + kin = _kin(piece.name) + for _ in range(candidates): + point = (rnd.uniform(0, size), rnd.uniform(0, size)) + clearance = min( + ( + torus_distance(point, other[0], size) + - radius + - other[1] + - (SAME_MOTIF_SPACING if kin and kin == _kin(other[2]) else 0) + for other in placed + ), + default=size, + ) + if clearance > best_clearance: + best, best_clearance = point, clearance + if best_clearance < piece.gap: + continue + angle = rnd.uniform(-piece.rotate, piece.rotate) + mirror = piece.name in MIRRORABLE and rnd.random() < 0.5 + placed.append((best, radius, piece.name, scale, angle, mirror)) + return placed + + +def tile_body(placed, size): + body = [] + for (x, y), radius, name, scale, angle, mirror in placed: + elements = MOTIFS[name][0](scale) + for ox in (-size, 0, size): + for oy in (-size, 0, size): + cx, cy = x + ox, y + oy + if cx + radius < 0 or cx - radius > size: + continue + if cy + radius < 0 or cy - radius > size: + continue + body.append(group(elements, cx, cy, angle, mirror)) + return "".join(body) + + +def tile_svg(pieces, seed): + placed = compose(pieces, TILE, seed) + return svg_document(TILE, TILE, tile_body(placed, TILE)), placed + + +def preview(tile, width=412, height=892, theme=None): + theme = theme or KOMET_THEME + inner = tile[tile.index(">") + 1 : tile.rindex("")] + return f""" + + + + + + + + + + + + {inner} + + + + + + + + +""" + + +PATTERNS = { + "komet": (KOMET_PIECES, 1), +} + + +KOMET_THEME = { + "bg": ("#111214", "#222326"), + "ink": ("#33363B", "#44474D"), + "glow": "#6A6F78", +} + + +def single(name, scale=6.0): + fn, _ = MOTIFS[name] + return svg_document( + 700, 700, group(fn(scale), 350, 350, 0), background="#15171a", color="#c8d0da" + ) + + +def main(argv): + if len(argv) > 1 and argv[1] == "sheet": + sys.stdout.write(motif_sheet()) + return + if len(argv) > 2 and argv[1] == "single": + sys.stdout.write(single(argv[2])) + return + if len(argv) > 1 and argv[1] == "mosaic": + tile, _ = tile_svg(KOMET_PIECES, 1) + inner = tile[tile.index(">") + 1 : tile.rindex("")] + cells = "".join( + f'{inner}' + for x in (0, 1) + for y in (0, 1) + ) + seams = ( + f'' + ) + body = f'{cells}{seams}' + sys.stdout.write(svg_document(2 * TILE, 2 * TILE, body, background="#15171a", color="#c8d0da")) + return + if len(argv) > 1 and argv[1] == "preview": + seed = int(argv[2]) if len(argv) > 2 else 1 + tile, placed = tile_svg(KOMET_PIECES, seed) + sys.stderr.write(f"placed {len(placed)} of {sum(p.count for p in KOMET_PIECES)}\n") + sys.stdout.write(preview(tile)) + return + if len(argv) > 1: + raise SystemExit( + "usage: make_wallpaper_patterns.py [sheet | single NAME | mosaic | preview SEED]" + ) + OUT_DIR.mkdir(parents=True, exist_ok=True) + for name, (pieces, seed) in PATTERNS.items(): + tile, placed = tile_svg(pieces, seed) + target = OUT_DIR / f"{name}.svg" + target.write_text(tile + "\n", encoding="utf-8") + print(f"{target.relative_to(ROOT)}: {len(placed)} motifs, {len(tile) // 1024} KB") + + +if __name__ == "__main__": + main(sys.argv) diff --git a/tool/whats_new.dart b/tool/whats_new.dart new file mode 100644 index 00000000..8a74451b --- /dev/null +++ b/tool/whats_new.dart @@ -0,0 +1,78 @@ +import 'dart:io'; + +import 'package:komet/core/whats_new/whats_new_document.dart'; + +const int _playLimit = 500; +const String _dir = 'assets/whats_new'; + +void main(List args) { + if (args.length == 2 && args.first == 'play') { + exit(_play(args[1])); + } + if (args.isNotEmpty) { + stderr.writeln( + 'dart run tool/whats_new.dart проверить все языки', + ); + stderr.writeln( + 'dart run tool/whats_new.dart play текст для Google Play', + ); + exit(64); + } + exit(_checkAll()); +} + +WhatsNewDocument? _load(String language) { + final file = File('$_dir/$language.txt'); + if (!file.existsSync()) { + stderr.writeln('нет файла ${file.path}'); + return null; + } + return WhatsNewDocument.parse(file.readAsStringSync()); +} + +int _play(String language) { + final document = _load(language); + if (document == null) return 1; + final text = document.plainText; + stdout.writeln(text); + final length = text.runes.length; + if (length > _playLimit) { + stderr.writeln( + '\n$length символов — Google Play примет не больше $_playLimit', + ); + return 1; + } + return 0; +} + +int _checkAll() { + final files = + Directory(_dir) + .listSync() + .whereType() + .where((file) => file.path.endsWith('.txt')) + .toList() + ..sort((a, b) => a.path.compareTo(b.path)); + var failed = false; + for (final file in files) { + final language = file.uri.pathSegments.last.replaceAll('.txt', ''); + final document = WhatsNewDocument.parse(file.readAsStringSync()); + final length = document.plainText.runes.length; + final links = document.notes + .where( + (note) => + note.target != null || + note.spans.any((s) => s is WhatsNewLinkSpan), + ) + .length; + stdout.writeln( + '$language: ${document.notes.length} пунктов, $links с переходом, ' + '${document.scenarios.length} сценариев, $length/$_playLimit символов для Play', + ); + for (final problem in document.problems) { + stdout.writeln(' ✗ $problem'); + failed = true; + } + } + return failed ? 1 : 0; +}