diff --git a/.github/actions/prepare-build/action.yml b/.github/actions/prepare-build/action.yml
index d64d579520..13871a25b8 100644
--- a/.github/actions/prepare-build/action.yml
+++ b/.github/actions/prepare-build/action.yml
@@ -10,21 +10,19 @@ inputs:
github_ref:
required: true
description: "Git reference"
- os:
- required: true
- description: "Target OS"
- cache_path:
- required: false
- default: "~/.cabal/store"
- description: "Cache path"
cabal_ver:
required: false
default: 3.10.2.0
description: "GHC version to install"
+outputs:
+ cabal-store:
+ description: "Cabal store path"
+ value: ${{ steps.setup.outputs.cabal-store }}
runs:
using: "composite"
steps:
- name: Setup Haskell
+ id: setup
uses: simplex-chat/setup-haskell-action@v2
with:
ghc-version: ${{ inputs.ghc_ver }}
@@ -37,11 +35,3 @@ runs:
distribution: 'corretto'
java-version: ${{ inputs.java_ver }}
cache: 'gradle'
-
- - name: Restore cached build
- uses: actions/cache@v4
- with:
- path: |
- ${{ inputs.cache_path }}
- dist-newstyle
- key: ${{ inputs.os }}-ghc${{ inputs.ghc_ver }}-${{ hashFiles('cabal.project', 'simplex-chat.cabal') }}
diff --git a/.github/workflows/android-emu.yml b/.github/workflows/android-emu.yml
new file mode 100644
index 0000000000..7617693b2b
--- /dev/null
+++ b/.github/workflows/android-emu.yml
@@ -0,0 +1,499 @@
+name: android-emu
+
+on:
+ workflow_dispatch:
+ inputs:
+ claude:
+ description: Also run the Claude job, which spends the Claude subscription's usage limits
+ type: boolean
+ default: false
+ backend:
+ description: Also start the test backend
+ type: boolean
+ default: false
+ release:
+ description: Also test the latest released app, to tell a branch's failure from the runner's
+ type: boolean
+ default: false
+ armv7a:
+ description: Also build the core library for 32-bit Arm (armeabi-v7a)
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: android-emu-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ GHC_VER: 9.6.3
+ CABAL_VER: 3.10.2.0
+ JAVA_VER: 17
+ CORE_PKG: android-core-arm64-v8a.tar.gz
+ BACKEND_PKG: desktop-linux-backend.tar.gz
+ APK: android-foss-arm64-v8a-debug.apk
+
+jobs:
+ plan:
+ name: choose jobs, find earlier builds
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ outputs:
+ run-claude: ${{ steps.jobs.outputs.claude }}
+ run-backend: ${{ steps.jobs.outputs.backend }}
+ run-release: ${{ steps.jobs.outputs.release }}
+ run-armv7a: ${{ steps.jobs.outputs.armv7a }}
+ claude-backend: ${{ steps.scope.outputs.backend }}
+ core: ${{ steps.names.outputs.core }}
+ core-run: ${{ steps.core.outputs.run-id }}
+ backend: ${{ steps.names.outputs.backend }}
+ backend-run: ${{ steps.backend.outputs.run-id }}
+ steps:
+ - name: Choose jobs
+ id: jobs
+ env:
+ CLAUDE: ${{ inputs.claude }}
+ BACKEND: ${{ inputs.backend }}
+ RELEASE: ${{ inputs.release }}
+ ARMV7A: ${{ inputs.armv7a }}
+ run: |
+ echo "claude=$CLAUDE" | tee -a "$GITHUB_OUTPUT"
+ echo "backend=$BACKEND" | tee -a "$GITHUB_OUTPUT"
+ echo "release=$RELEASE" | tee -a "$GITHUB_OUTPUT"
+ echo "armv7a=$ARMV7A" | tee -a "$GITHUB_OUTPUT"
+
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Claude scope
+ id: scope
+ if: steps.jobs.outputs.claude == 'true'
+ env:
+ BACKEND: ${{ steps.jobs.outputs.backend }}
+ run: |
+ backend=$(sed -n 's/^backend: *//p' scripts/ci/android/claude-scope)
+ case "$backend" in
+ yes | no) echo "backend=$backend" | tee -a "$GITHUB_OUTPUT" ;;
+ *)
+ echo "::error::claude-scope must say backend: yes or backend: no"
+ exit 1
+ ;;
+ esac
+ if [ "$backend" = yes ] && [ "$BACKEND" != true ]; then
+ echo "::error::claude-scope says the Claude session uses the test backend: ask for it too"
+ exit 1
+ fi
+
+ # artifacts are named after the sources they are built from, so a run uses one that an earlier run uploaded;
+ # the backend has desktop-linux's name and sources, so each workflow reuses the other's
+ - name: Artifact names
+ id: names
+ run: |
+ echo "core=android-core-${{ hashFiles('src/**', 'cabal.project', 'simplex-chat.cabal', 'PRIVACY.md', 'flake.nix', 'flake.lock', 'scripts/nix/**', 'scripts/ci/android/build-core.sh') }}" >> "$GITHUB_OUTPUT"
+ echo "backend=desktop-linux-backend-${{ hashFiles('src/**', 'apps/simplex-chat/**', 'apps/simplex-directory-service/Main.hs', 'apps/simplex-directory-service/src/**', 'cabal.project', 'simplex-chat.cabal', 'scripts/ci/desktop-linux/build-backend.sh') }}" >> "$GITHUB_OUTPUT"
+
+ - name: Find core library
+ id: core
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/desktop-linux/earlier-run.sh "${{ steps.names.outputs.core }}"
+
+ - name: Find backend
+ id: backend
+ if: steps.jobs.outputs.backend == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/desktop-linux/earlier-run.sh "${{ steps.names.outputs.backend }}"
+
+ backend:
+ name: test backend for the app
+ needs: plan
+ if: needs.plan.outputs.run-backend == 'true' && needs.plan.outputs.backend-run == ''
+ runs-on: ubuntu-24.04
+ timeout-minutes: 150
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+
+ - name: Setup Haskell
+ uses: simplex-chat/setup-haskell-action@v2
+ with:
+ ghc-version: ${{ env.GHC_VER }}
+ cabal-version: ${{ env.CABAL_VER }}
+
+ - name: Install libraries
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libffi-dev libgmp-dev libnuma-dev libssl-dev zlib1g-dev
+
+ - name: Build backend
+ run: scripts/ci/desktop-linux/build-backend.sh ~/backend/${{ env.BACKEND_PKG }}
+
+ - name: Upload backend
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend/${{ env.BACKEND_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ core:
+ name: core library for Android arm64
+ needs: plan
+ if: needs.plan.outputs.core-run == ''
+ runs-on: ubuntu-24.04
+ timeout-minutes: 150
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ filter: tree:0
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+
+ - name: Build core library
+ run: scripts/ci/android/build-core.sh ~/core/${{ env.CORE_PKG }}
+
+ - name: Upload core library
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/core/${{ env.CORE_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ core-armv7a:
+ name: core library for Android armv7a
+ needs: plan
+ if: needs.plan.outputs.run-armv7a == 'true'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 150
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ filter: tree:0
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+
+ - name: Build core library
+ run: scripts/ci/android/build-core.sh ~/core/android-core-armeabi-v7a.tar.gz armv7a
+
+ app:
+ name: Android app in the emulator
+ needs: [plan, core, backend]
+ # core and backend are skipped when an earlier run built them, and backend also when the run doesn't start it
+ if: ${{ !cancelled() && !failure() && needs.plan.result == 'success' && needs.core.result != 'cancelled' && needs.backend.result != 'cancelled' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 75
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ submodules: recursive
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+ echo "ANDROID_HOME=$ANDROID_HOME"
+ ls "$ANDROID_HOME/platforms" "$ANDROID_HOME/build-tools" "$ANDROID_HOME/ndk" || true
+
+ # the emulator's qemu needs libpulse0 and libegl1; the backend's avatars and checks need the rest
+ - name: Install tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libpulse0 libegl1 imagemagick sqlite3 fonts-dejavu-core
+ dpkg-query -W libpulse0 libegl1 imagemagick sqlite3 fonts-dejavu-core
+
+ - name: Download core library
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/core
+ run-id: ${{ needs.plan.outputs.core-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Install core library
+ id: core
+ run: scripts/ci/android/install-core.sh ~/core/${{ env.CORE_PKG }}
+
+ - name: Download backend
+ if: needs.plan.outputs.run-backend == 'true'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend
+ run-id: ${{ needs.plan.outputs.backend-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ id: backend
+ if: needs.plan.outputs.run-backend == 'true'
+ timeout-minutes: 30
+ run: scripts/ci/desktop-linux/backend.sh start ~/backend/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ # the app and its tests are still built when the backend fails
+ - name: Setup Java
+ if: ${{ !cancelled() && steps.core.outcome == 'success' }}
+ uses: actions/setup-java@v5
+ with:
+ distribution: corretto
+ java-version: ${{ env.JAVA_VER }}
+
+ # the injected ABI builds only arm64-v8a, whose core the job has, and puts the APK under build/intermediates
+ - name: Build app
+ id: build
+ if: ${{ !cancelled() && steps.core.outcome == 'success' }}
+ working-directory: apps/multiplatform
+ run: |
+ ./gradlew --no-daemon --console=plain -Psimplex.assets.dir=../../assets -Pandroid.injected.build.abi=arm64-v8a :android:assembleFossDebug
+ mkdir -p "$RUNNER_TEMP/apk"
+ cp "android/build/intermediates/apk/foss/debug/$APK" "$RUNNER_TEMP/apk"
+ ls -la "$RUNNER_TEMP/apk"
+ unzip -l "$RUNNER_TEMP/apk/$APK" | grep -E ' lib/'
+
+ - name: Upload app
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-app
+ path: ${{ runner.temp }}/apk/${{ env.APK }}
+ compression-level: 0
+ retention-days: 14
+ if-no-files-found: error
+
+ - name: Install emulator and system image
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ run: scripts/ci/android/install-sdk.sh "$RUNNER_TEMP/android-sdk"
+
+ - name: Boot emulator
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ run: scripts/ci/android/emulator.sh start "$RUNNER_TEMP/smoke-test"
+
+ # the test SMP server's addresses have the runner's 127.0.0.1, which adb reverse forwards from the emulator's
+ - name: Reach the test backend
+ id: reach
+ if: ${{ !cancelled() && steps.build.outcome == 'success' && steps.backend.outcome == 'success' }}
+ run: scripts/ci/android/emulator.sh reverse 5223
+
+ - name: Run smoke test
+ if: ${{ !cancelled() && steps.build.outcome == 'success' && steps.backend.outcome != 'failure' && steps.reach.outcome != 'failure' }}
+ env:
+ BACKEND: ${{ steps.reach.outcome }}
+ run: |
+ if [ "$BACKEND" = success ]; then
+ export NAMES_SERVER=$(cat "$RUNNER_TEMP/backend/names-server")
+ cases=backend
+ fi
+ scripts/ci/android/smoke-test.sh "$RUNNER_TEMP/apk/$APK" "$RUNNER_TEMP/smoke-test" ${cases:-}
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload smoke test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-smoke-test
+ path: ${{ runner.temp }}/smoke-test
+ retention-days: 3
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-backend-logs
+ path: ${{ runner.temp }}/backend/*.log
+ retention-days: 3
+ if-no-files-found: warn
+
+ # Claude Code repeats the smoke test with the ui helper. Each run spends the Claude subscription's usage
+ # limits, so it runs only when asked for. The app-sim-claude environment's branch rule decides which branches
+ # may use the token.
+ claude:
+ name: Claude tests the Android app
+ needs: [plan, app]
+ if: ${{ !cancelled() && needs.plan.outputs.run-claude == 'true' && needs.app.result == 'success' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ environment:
+ name: app-sim-claude
+ deployment: false
+ concurrency:
+ group: android-emu-claude-${{ github.ref }}
+ cancel-in-progress: true
+ env:
+ # the same in all app workflows
+ CLAUDE_CODE_VERSION: 2.1.300
+ CLAUDE_MODEL: claude-haiku-5-5
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ persist-credentials: false
+
+ - name: Install tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libpulse0 libegl1 imagemagick sqlite3 fonts-dejavu-core
+ dpkg-query -W libpulse0 libegl1 imagemagick sqlite3 fonts-dejavu-core
+
+ - name: Download app
+ uses: actions/download-artifact@v8
+ with:
+ name: android-app
+ path: ${{ runner.temp }}/apk
+
+ - name: Download backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend
+ run-id: ${{ needs.plan.outputs.backend-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ id: backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ timeout-minutes: 30
+ run: scripts/ci/desktop-linux/backend.sh start ~/backend/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ - name: Install emulator and system image
+ run: scripts/ci/android/install-sdk.sh "$RUNNER_TEMP/android-sdk"
+
+ - name: Boot emulator
+ run: scripts/ci/android/emulator.sh start "$RUNNER_TEMP/claude-test/screens"
+
+ - name: Add test images
+ run: |
+ adb push tests/fixtures/test.jpg /sdcard/Pictures/test-card.jpg
+ adb push tests/fixtures/logo-large-rgba.png /sdcard/Pictures/simplex-logo.png
+ for image in test-card.jpg simplex-logo.png; do
+ adb shell am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d "file:///sdcard/Pictures/$image"
+ done
+
+ - name: Reach the test backend
+ if: steps.backend.outcome == 'success'
+ run: scripts/ci/android/emulator.sh reverse 5223
+
+ # ui goes on every shell's PATH, where Claude's Bash tool finds it whatever environment it builds
+ - name: Install Claude Code and the ui command
+ run: |
+ npm install --prefix "$RUNNER_TEMP/claude-code" "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
+ echo "$RUNNER_TEMP/claude-code/node_modules/.bin" >> "$GITHUB_PATH"
+ printf '#!/bin/sh\nexec %s/scripts/ci/android/ui "$@"\n' "$PWD" | sudo tee /usr/local/bin/ui
+ sudo chmod +x /usr/local/bin/ui
+
+ - name: Start the app
+ run: scripts/ci/android/smoke-test.sh "$RUNNER_TEMP/apk/$APK" "$RUNNER_TEMP/claude-test/screens" start
+
+ # Claude's Bash is limited to single ui commands by the guard hook in claude-test.sh. Claude Code's credential
+ # scrub stays off: on Linux it forces its whole Bash sandbox (bubblewrap, socat), which ui isn't set up for.
+ - name: Run Claude
+ id: claude
+ env:
+ CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: 1
+ run: scripts/ci/desktop-linux/claude-test.sh "$RUNNER_TEMP/claude-test" "$RUNNER_TEMP/claude-transcript.jsonl" scripts/ci/android/claude-test.md
+
+ - name: Report Claude usage
+ if: ${{ !cancelled() && steps.claude.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/claude-usage.py "$RUNNER_TEMP/claude-transcript.jsonl" "$RUNNER_TEMP/claude-usage.json"
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload Claude test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-claude-test
+ path: |
+ ${{ runner.temp }}/claude-test
+ ${{ runner.temp }}/claude-transcript.jsonl
+ ${{ runner.temp }}/claude-transcript.jsonl.stderr
+ ${{ runner.temp }}/claude-transcript.jsonl.guard.log
+ ${{ runner.temp }}/claude-usage.json
+ retention-days: 7
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-claude-backend-logs
+ path: ${{ runner.temp }}/backend/*.log
+ retention-days: 3
+ if-no-files-found: warn
+
+ # the latest release's onboarding, to tell a branch's own failure from the runner's
+ release:
+ name: released app in the emulator
+ needs: plan
+ if: needs.plan.outputs.run-release == 'true'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ filter: tree:0
+
+ - name: Install tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libpulse0 libegl1
+ dpkg-query -W libpulse0 libegl1
+
+ - name: Download released app
+ run: scripts/ci/android/release-apk.sh "$RUNNER_TEMP/release"
+
+ - name: Install emulator and system image
+ run: scripts/ci/android/install-sdk.sh "$RUNNER_TEMP/android-sdk"
+
+ - name: Boot emulator
+ run: scripts/ci/android/emulator.sh start "$RUNNER_TEMP/smoke-test"
+
+ - name: Run smoke test
+ run: scripts/ci/android/smoke-test.sh "$RUNNER_TEMP/release/simplex-aarch64.apk" "$RUNNER_TEMP/smoke-test" onboarding
+
+ - name: Upload smoke test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: android-release-smoke-test
+ path: ${{ runner.temp }}/smoke-test
+ retention-days: 3
+ if-no-files-found: warn
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 348413fc1f..459d5b7e51 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -15,20 +15,53 @@ on:
- "apps/simplex-chat/**"
- "apps/simplex-bot/**"
- "apps/simplex-bot-advanced/**"
+ - "apps/simplex-badge-service/**"
- "apps/simplex-broadcast-bot/**"
- "apps/simplex-directory-service/**"
+ - "apps/multiplatform/**"
+ - "apps/ios/**"
- "tests/**"
- "bots/src/**"
- "simplex-chat.cabal"
- "cabal.project"
- "Dockerfile*"
- - "scripts/ci/**"
+ - "scripts/ci/*.sh"
+ - "scripts/ci/ios-stub-libs.sh"
- "scripts/desktop/**"
- - ".github/**"
+ - ".github/workflows/build.yml"
+ - ".github/actions/**"
+ - ".github/changelog_conf.json"
+ - "packages/simplex-chat-nodejs/**"
+ - "packages/simplex-chat-client/types/typescript/**"
+ - "packages/simplex-chat-python/**"
+ - "scripts/ci/package-tests.sh"
+ - "apps/simplex-badge-service/web/**"
+ - "scripts/ci/packages_release.py"
+ - "scripts/ci/test_packages_release.py"
+ - "website/src/js/simplex-lib.jsc"
+ - "website/test/**"
+ - "website/package.json"
+ - "packages/simplex-chat-mcp/**"
+ types: [opened, synchronize, reopened, ready_for_review]
+ workflow_dispatch:
+ inputs:
+ tests:
+ description: "hspec match patterns, one per line; / runs all tests, empty runs none"
+ type: string
+ default: ""
+ base:
+ description: the branch that the changes are compared with
+ type: string
+ default: master
-concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/v') }}
+env:
+ opt: ${{ github.event_name == 'push' && 'O2' || 'O0' }}
+ ghc_options: ${{ github.event_name != 'push' && '--ghc-options=-O0' || '' }}
+ release: ${{ startsWith(github.ref, 'refs/tags/v') }}
+ branch: ${{ github.base_ref || github.ref_name }}
+ cache_o0: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/stable') }}
+ release_branch: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/stable') && github.repository == 'simplex-chat/simplex-chat' && github.ref_name || '' }}
+ ZSTD_CLEVEL: 9
# This workflow uses custom actions (prepare-build and prepare-release) defined in:
#
@@ -69,14 +102,73 @@ jobs:
# =============================
# Create release, but only if it's triggered by tag push.
-# On pull requests/commits push, this job will always complete.
+# On pushes to master or stable: claim the simplex-chat-libs release core- for the branch
+# and create its draft, create the draft of a missing add-on release, and find the package versions to publish.
+# On pull requests and other pushes, this job will always complete.
+
+# Secrets:
+# -------
+# NODEJS_REPO_TOKEN
+# Only select repositories: simplex-chat-libs
+# Permissions:
+# * Contents (Read and Write)
maybe-release:
runs-on: ubuntu-latest
+ outputs:
+ libs_tag: ${{ steps.libs.outputs.tag }}
+ core_changed: ${{ steps.changes.outputs.core }}
+ haskell: ${{ steps.changes.outputs.haskell }}
+ kotlin: ${{ steps.changes.outputs.kotlin }}
+ ios: ${{ steps.changes.outputs.ios }}
+ addon_tag: ${{ steps.addon.outputs.tag }}
+ addon_draft: ${{ steps.addon.outputs.draft }}
+ libs_latest: ${{ steps.latest_libs.outputs.tag }}
+ publish_types: ${{ steps.libs.outputs.tag && steps.publish.outputs.types_version || '' }}
+ publish_nodejs: ${{ steps.publish.outputs.nodejs_version }}
+ publish_python: ${{ steps.publish.outputs.python_version }}
+ publish_mcp: ${{ steps.publish.outputs.mcp_version }}
+ publish: ${{ steps.publish.outputs.nodejs_version || steps.publish.outputs.python_version }}
+ packages: ${{ steps.changes.outputs.packages }}
+ scopes: ${{ steps.changes.outputs.scopes }}
+ reduced: ${{ github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == true || (github.event_name == 'push' && github.ref_type == 'branch' && github.repository != 'simplex-chat/simplex-chat') }}
steps:
+ - name: Reject a manual run on a tag
+ if: github.event_name == 'workflow_dispatch' && github.ref_type == 'tag'
+ run: |
+ echo "::error::A manual run starts on a branch; to retry a release, re-run the jobs of its tag push."
+ exit 1
+
- name: Clone project
- if: startsWith(github.ref, 'refs/tags/v')
uses: actions/checkout@v3
+ with:
+ fetch-depth: 2
+
+ - name: Check changes
+ id: changes
+ shell: bash
+ env:
+ BASE_BRANCH: ${{ inputs.base }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ case "$GITHUB_EVENT_NAME" in
+ pull_request)
+ python3 scripts/ci/packages_release.py changes HEAD^1
+ ;;
+ workflow_dispatch)
+ base=$(gh api "repos/$GITHUB_REPOSITORY/compare/$BASE_BRANCH...$GITHUB_REF_NAME" --jq .merge_base_commit.sha)
+ git fetch -q --depth=1 origin "$base"
+ python3 scripts/ci/packages_release.py changes "$base"
+ ;;
+ *)
+ echo "haskell=true"
+ if [ -n "$release_branch" ]; then
+ echo "kotlin=true"
+ echo "ios=true"
+ python3 scripts/ci/packages_release.py scopes
+ fi
+ ;;
+ esac >> "$GITHUB_OUTPUT"
- name: Build changelog
id: build_changelog
@@ -102,6 +194,69 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ - name: Library release
+ id: libs
+ if: env.release_branch
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ run: |
+ version=$(sed -n 's/^version: *//p' simplex-chat.cabal)
+ tag=core-$version
+ claim_output=$(python3 scripts/ci/packages_release.py claim-core "$version" "$GITHUB_SHA" "$release_branch")
+ eval "$claim_output"
+ if [ "$claim" = skip ]; then
+ echo "::notice title=Library release::core $version is recorded for another commit"
+ exit 0
+ fi
+ status_output=$(python3 scripts/ci/packages_release.py release-status "$tag")
+ eval "$status_output"
+ if [ "$status" = absent ]; then
+ gh release create "$tag" --repo "$LIBS_REPOSITORY" --draft --title "$tag" --notes "" ${commit:+--target "$commit"}
+ fi
+ if [ "$status" != published ]; then
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Add-on release
+ id: addon
+ if: env.release_branch
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ run: |
+ addon_output=$(python3 scripts/ci/packages_release.py addon-release)
+ eval "$addon_output"
+ if [ "$status" = absent ]; then
+ tag=nodejs-addon-${GITHUB_SHA::7}
+ gh release create "$tag" --repo "$LIBS_REPOSITORY" --draft --title "$tag" --notes "$notes"
+ fi
+ if [ "$status" != published ]; then
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "draft=true" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Latest library
+ id: latest_libs
+ if: steps.addon.outputs.draft
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ run: python3 scripts/ci/packages_release.py latest-libs --branch "$release_branch" >> "$GITHUB_OUTPUT"
+
+ - name: Versions to publish
+ id: publish
+ if: env.release_branch
+ env:
+ GH_TOKEN: ${{ github.token }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ NPM_SCOPE: ${{ vars.NPM_SCOPE }}
+ PYPI_PROJECT: ${{ vars.PYPI_PROJECT }}
+ PYPI_URL: ${{ vars.PYPI_URL }}
+ run: python3 scripts/ci/packages_release.py publish-plan >> "$GITHUB_OUTPUT"
+
# =========================
# Linux Build
# =========================
@@ -109,7 +264,17 @@ jobs:
build-linux:
name: "ubuntu-${{ matrix.os }}-${{ matrix.arch }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
needs: [maybe-release, variables]
+ if: needs.maybe-release.outputs.haskell == 'true' || needs.maybe-release.outputs.scopes != '' || (needs.maybe-release.outputs.reduced == 'true' && (needs.maybe-release.outputs.kotlin == 'true' || needs.maybe-release.outputs.packages == 'true'))
runs-on: ${{ matrix.runner }}
+ permissions:
+ contents: write
+ packages: write
+ env:
+ image_cache: ghcr.io/${{ github.repository_owner }}/simplex-chat-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}
+ source_hashes: dist-newstyle/sources.sha256
+ concurrency: &linux-concurrency
+ group: ${{ github.workflow }}-${{ github.ref }}-linux-${{ matrix.os }}-${{ matrix.arch }}-${{ matrix.ghc }}-${{ needs.maybe-release.outputs.libs_tag }}
+ cancel-in-progress: ${{ github.event_name != 'push' }}
strategy:
fail-fast: false
matrix:
@@ -118,40 +283,16 @@ jobs:
os_underscore: 22_04
arch: x86_64
runner: "ubuntu-22.04"
- ghc: "8.10.7"
- hash: 'sha256:5c8b2c0a6c745bc177669abfaa716b4bc57d58e2ea3882fb5da67f4d59e3dda5'
- should_run: ${{ !(github.ref == 'refs/heads/stable' || startsWith(github.ref, 'refs/tags/v')) }}
- - os: 22.04
- os_underscore: 22_04
- arch: x86_64
- runner: "ubuntu-22.04"
- should_run: true
+ should_run: ${{ needs.maybe-release.outputs.haskell == 'true' }}
ghc: ${{ needs.variables.outputs.GHC_VER }}
hash: 'sha256:5c8b2c0a6c745bc177669abfaa716b4bc57d58e2ea3882fb5da67f4d59e3dda5'
- - os: 24.04
- os_underscore: 24_04
- arch: x86_64
- runner: "ubuntu-24.04"
- should_run: true
- ghc: ${{ needs.variables.outputs.GHC_VER }}
- hash: 'sha256:98ff7968124952e719a8a69bb3cccdd217f5fe758108ac4f21ad22e1df44d237'
- - os: 22.04
- os_underscore: 22_04
- arch: aarch64
- runner: "ubuntu-22.04-arm"
- should_run: true
- ghc: ${{ needs.variables.outputs.GHC_VER }}
- hash: 'sha256:6a62a4157b8775eaf4959cb629e757d32d39d1f4c8ac1b0ddc2510b555cf72f3'
- - os: 24.04
- os_underscore: 24_04
- arch: aarch64
- runner: "ubuntu-24.04-arm"
- should_run: true
- ghc: ${{ needs.variables.outputs.GHC_VER }}
- hash: 'sha256:68434214381cb38287104e629fe8ee720167dd98cbb36ab1cbbab342515fa6ab'
- steps:
+ libs: true
+ kotlin: ${{ needs.maybe-release.outputs.reduced == 'true' && needs.maybe-release.outputs.kotlin == 'true' }}
+ packages: ${{ needs.maybe-release.outputs.reduced == 'true' && needs.maybe-release.outputs.packages == 'true' }}
+ scope_tests: ${{ needs.maybe-release.outputs.scopes != '' }}
+ steps: &linux-steps
- name: Checkout Code
- if: matrix.should_run == true
+ if: matrix.should_run == true || matrix.kotlin == true || matrix.packages == true || matrix.scope_tests == true
uses: actions/checkout@v3
with:
submodules: recursive
@@ -170,25 +311,28 @@ jobs:
# Otherwise we run out of disk space with Docker build
- name: Free disk space
- if: matrix.should_run == true
+ if: (matrix.should_run == true || matrix.kotlin == true) && needs.maybe-release.outputs.reduced != 'true'
shell: bash
run: ./scripts/ci/linux_util_free_space.sh
- - name: Restore cached build
- if: matrix.should_run == true
- uses: actions/cache@v4
- with:
- path: |
- ~/.cabal/store
- dist-newstyle
- key: ubuntu-${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}-${{ hashFiles('cabal.project', 'simplex-chat.cabal') }}
-
- name: Set up Docker Buildx
- if: matrix.should_run == true
+ if: matrix.should_run == true || matrix.kotlin == true
uses: simplex-chat/docker-setup-buildx-action@v3
+ - name: Log in to GitHub Container Registry
+ if: (matrix.should_run == true || matrix.kotlin == true) && env.release != 'true'
+ shell: bash
+ env:
+ GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ run: echo "$GHCR_TOKEN" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
+
+ - name: Compute image cache week
+ id: week
+ if: (matrix.should_run == true || matrix.kotlin == true) && env.release != 'true'
+ run: echo "week=$(date -u +%G-W%V)" >> "$GITHUB_OUTPUT"
+
- name: Build and cache Docker image
- if: matrix.should_run == true
+ if: matrix.should_run == true || matrix.kotlin == true
uses: simplex-chat/docker-build-push-action@v6
with:
context: .
@@ -201,25 +345,105 @@ jobs:
GHC=${{ matrix.ghc }}
USER_UID=${{ steps.ids.outputs.uid }}
USER_GID=${{ steps.ids.outputs.gid }}
+ cache-from: ${{ env.release != 'true' && format('type=registry,ref={0}-{1}', env.image_cache, steps.week.outputs.week) || '' }}
+ cache-to: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' && format('type=registry,ref={0}-{1},mode=max,ignore-error=true', env.image_cache, steps.week.outputs.week) || '' }}
# Docker needs these flags for AppImage build:
# --device /dev/fuse
# --cap-add SYS_ADMIN
# --security-opt apparmor:unconfined
- name: Start container
- if: matrix.should_run == true
+ if: matrix.should_run == true || matrix.kotlin == true
shell: bash
run: |
+ mkdir -p ~/.cabal
docker run -t -d \
--device /dev/fuse \
--cap-add SYS_ADMIN \
--security-opt apparmor:unconfined \
--name builder \
- -v ~/.cabal:/root/.cabal \
+ -e CABAL_DIR=/home/builder/.cabal \
+ -v ~/.cabal:/home/builder/.cabal \
-v /home/runner/work/_temp:/home/runner/work/_temp \
-v ${{ github.workspace }}:/project \
build/${{ matrix.os }}:latest
+ - name: Compute cache key prefixes
+ id: keys
+ if: matrix.should_run == true && env.release != 'true'
+ run: |
+ toolchain=$(docker exec builder dpkg-query -W -f '${db:Status-Status} ${binary:Package} ${Version}\n' 'binutils*' 'cpp*' 'gcc*' '*-dev' | grep '^installed ' | sha256sum | cut -c1-16)
+ target=ubuntu-${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}-$toolchain
+ echo "deps=deps-$target" >> "$GITHUB_OUTPUT"
+ echo "dist=dist-$target" >> "$GITHUB_OUTPUT"
+ echo "dist_lib=dist-lib-$target" >> "$GITHUB_OUTPUT"
+
+ - name: Restore dependencies from cache
+ id: restore-deps
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: ~/.cabal/store
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.deps }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.deps }}-
+
+ - name: Warn if dependencies not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-deps.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.deps }}-${{ env.branch }}"
+
+ - name: Restore source repositories from cache
+ id: restore-src
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+ restore-keys: src-${{ runner.os }}-
+
+ - name: Warn if source repositories not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-src.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::src-${{ runner.os }}"
+
+ - name: Restore build directory from cache
+ id: restore-build
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-
+
+ - name: Warn if build directory not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-build.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}"
+
+ - name: Restore library build directory from cache
+ id: restore-build-lib
+ if: env.release != 'true' && matrix.libs && needs.maybe-release.outputs.core_changed && matrix.arch == 'x86_64' && (needs.maybe-release.outputs.reduced != 'true' || matrix.packages == true)
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-lib/*
+ !dist-lib/src
+ key: ${{ steps.keys.outputs.dist_lib }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist_lib }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist_lib }}-
+
+ - name: Warn if library build directory not in cache
+ if: steps.restore-build-lib.outcome == 'success' && steps.restore-build-lib.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.dist_lib }}-${{ env.branch }}"
+
+ - name: Set old timestamps on unchanged sources (GHC 8.10.7)
+ if: matrix.ghc == '8.10.7' && steps.restore-build.outputs.cache-matched-key != '' && hashFiles(env.source_hashes) != ''
+ run: scripts/ci/source-timestamps.sh restore ${{ env.source_hashes }}
+
- name: Prepare cabal.project.local
if: matrix.should_run == true
shell: bash
@@ -228,22 +452,89 @@ jobs:
echo "package direct-sqlcipher" >> cabal.project.local
echo " flags: +openssl" >> cabal.project.local
- # chmod/git commands are used to workaround permission issues when cache is restored
- name: Build CLI
+ id: build-cli
if: matrix.should_run == true
shell: docker exec -t builder sh -eu {0}
run: |
- cabal clean
+ scripts/ci/prune-old-builds.sh dist-newstyle
cabal update
- cabal build -j --enable-tests
+ cabal build -j --enable-tests ${{ env.ghc_options }}
mkdir -p /out
for i in simplex-chat simplex-chat-test; do
bin=$(find /project/dist-newstyle -name "$i" -type f -executable)
chmod +x "$bin"
- mv "$bin" /out/
+ cp "$bin" /out/
done
strip /out/simplex-chat
+ # Also for pull requests that change the chat core, for the package tests.
+ - name: Build library
+ id: build-lib
+ if: matrix.libs && (needs.maybe-release.outputs.libs_tag || (needs.maybe-release.outputs.core_changed && matrix.arch == 'x86_64' && (needs.maybe-release.outputs.reduced != 'true' || matrix.packages == true)))
+ shell: docker exec -t builder sh -eu {0}
+ run: |
+ scripts/ci/prune-old-builds.sh dist-lib
+ mkdir -p dist-lib
+ rm -rf dist-lib/src
+ ln -s ../dist-newstyle/src dist-lib/src
+ DIST_DIR=dist-lib SKIP_VLC=1 scripts/desktop/build-lib-linux.sh
+ name=simplex-chat-libs-linux-${{ matrix.arch }}
+ mkdir -p release-libs/$name/libs
+ find apps/multiplatform/common/src/commonMain/cpp/desktop/libs/linux-${{ matrix.arch }} -maxdepth 1 -type f -exec cp {} release-libs/$name/libs/ \;
+ (cd release-libs/$name && zip -r ../$name.zip libs)
+
+ - name: Record source hashes (GHC 8.10.7)
+ if: matrix.should_run == true && matrix.ghc == '8.10.7'
+ shell: docker exec -t builder sh -eu {0}
+ run: scripts/ci/source-timestamps.sh record ${{ env.source_hashes }}
+
+ - name: Compute dependency cache key
+ id: hash-deps
+ if: matrix.should_run == true && env.release != 'true'
+ shell: bash
+ run: echo "hash=$(ls ~/.cabal/store/ghc-*/ | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
+
+ - name: Save dependencies to cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-deps.outputs.cache-matched-key != format('{0}-{1}-{2}', steps.keys.outputs.deps, env.branch, steps.hash-deps.outputs.hash)
+ uses: actions/cache/save@v4
+ with:
+ path: ~/.cabal/store
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ steps.hash-deps.outputs.hash }}
+
+ - name: Save source repositories to cache
+ if: matrix.should_run == true && env.release != 'true' && matrix.libs && matrix.arch == 'x86_64' && steps.restore-src.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+
+ - name: Save build directory to cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-build.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+
+ - name: Save library build directory to cache
+ if: steps.build-lib.outcome == 'success' && env.release != 'true' && steps.restore-build-lib.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-lib/*
+ !dist-lib/src
+ key: ${{ steps.keys.outputs.dist_lib }}-${{ env.branch }}-${{ github.sha }}
+
+ - name: Upload library
+ if: needs.maybe-release.outputs.libs_tag && matrix.libs
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ TAG: ${{ needs.maybe-release.outputs.libs_tag }}
+ run: gh release upload "$TAG" release-libs/*.zip --clobber --repo "${{ github.repository }}-libs"
+
- name: Build CLI deb
if: startsWith(github.ref, 'refs/tags/v') && matrix.should_run == true
shell: docker exec -t builder sh -eu {0}
@@ -352,34 +643,236 @@ jobs:
github_ref: ${{ github.ref }}
github_token: ${{ secrets.GITHUB_TOKEN }}
- - name: Fix permissions for cache
- if: matrix.should_run == true
+ - name: Mount RAM disk for tests
+ if: matrix.should_run == true && matrix.arch == 'x86_64'
shell: bash
run: |
- sudo chmod -R 777 dist-newstyle ~/.cabal
- sudo chown -R $(id -u):$(id -g) dist-newstyle ~/.cabal
+ mkdir -p tests/tmp
+ sudo mount -t tmpfs -o size=2G tmpfs tests/tmp
+ sudo chown $(id -u):$(id -g) tests/tmp
- name: Run tests
if: matrix.should_run == true && matrix.arch == 'x86_64'
timeout-minutes: 120
shell: bash
+ env:
+ REDUCED: ${{ needs.maybe-release.outputs.reduced }}
+ TESTS: ${{ github.event_name == 'workflow_dispatch' && inputs.tests || '' }}
+ PR_BODY: ${{ github.event.pull_request.draft == true && github.event.pull_request.body || '' }}
+ ATTEMPTS: ${{ (github.ref == 'refs/heads/stable' || startsWith(github.ref, 'refs/tags/v')) && 3 || 1 }}
+ run: scripts/ci/run-tests.sh timeout 35m ./simplex-chat-test
+
+ # Compiling the desktop and Android targets of :common in parallel exceeds the 2 GB Kotlin daemon heap.
+ # cmakeBuildAndCopy links the JNI library against libsimplex, which this job does not build.
+ - name: Build and test Kotlin apps
+ if: ${{ !cancelled() && matrix.kotlin == true }}
+ timeout-minutes: 90
+ shell: docker exec -t builder sh -eu {0}
run: |
- i=1
- attempts=1
- ${{ (github.ref == 'refs/heads/stable' || startsWith(github.ref, 'refs/tags/v')) }} && attempts=3
- while [ "$i" -le "$attempts" ]; do
- if ./simplex-chat-test; then
- break
- else
- echo "Attempt $i failed, retrying..."
- i=$((i + 1))
- sleep 1
- fi
+ cd apps/multiplatform
+ ./gradlew --no-daemon --max-workers=1 \
+ :common:desktopTest \
+ :desktop:compileKotlinJvm -x :desktop:cmakeBuildAndCopy \
+ :android:compileGoogleDebugKotlin \
+ :android:testFossDebugUnitTest
+
+ - name: Setup Node.js
+ id: setup-node
+ if: ${{ !cancelled() && (matrix.packages == true || matrix.scope_tests == true || (matrix.should_run == true && matrix.libs && ((github.event_name == 'pull_request' && needs.maybe-release.outputs.reduced != 'true') || needs.maybe-release.outputs.addon_draft || needs.maybe-release.outputs.publish))) }}
+ uses: actions/setup-node@v7
+ with:
+ node-version: 22
+
+ - name: Setup Python
+ id: setup-python
+ if: ${{ !cancelled() && steps.setup-node.outcome == 'success' }}
+ uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ - name: Package tests (pull request)
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && github.event_name != 'push' && steps.build-lib.outcome != 'failure' && ((needs.maybe-release.outputs.reduced != 'true' && matrix.should_run == true) || matrix.packages == true) }}
+ timeout-minutes: 30
+ shell: bash
+ env:
+ SIMPLEX_LIBS_DIR: ${{ steps.build-lib.outcome == 'success' && format('{0}/release-libs/simplex-chat-libs-linux-{1}/libs', github.workspace, matrix.arch) || '' }}
+ run: |
+ scripts/ci/package-tests.sh build linux-${{ matrix.arch }}
+ scripts/ci/package-tests.sh test
+
+ - name: Add-on
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.addon_draft }}
+ timeout-minutes: 30
+ shell: bash
+ env:
+ LIBS_RELEASE: ${{ needs.maybe-release.outputs.libs_latest }}
+ ADDON_TAG: ${{ needs.maybe-release.outputs.addon_tag }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ run: scripts/ci/package-tests.sh addon linux-${{ matrix.arch }}
+
+ - name: Package tests
+ id: package-tests
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.publish }}
+ timeout-minutes: 30
+ shell: bash
+ run: |
+ scripts/ci/package-tests.sh publish linux-${{ matrix.arch }} ${{ needs.maybe-release.outputs.publish_nodejs && 'nodejs' || '' }} ${{ needs.maybe-release.outputs.publish_python && 'python' || '' }}
+ echo "linux-${{ matrix.arch }}" > "$RUNNER_TEMP/package-tests"
+
+ - name: Package tests result
+ if: ${{ !cancelled() && steps.package-tests.outcome == 'success' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: package-tests-linux-${{ matrix.arch }}
+ path: ${{ runner.temp }}/package-tests
+
+ - name: Test changed scopes
+ if: ${{ !cancelled() && matrix.scope_tests == true && steps.setup-python.outcome == 'success' }}
+ timeout-minutes: 30
+ shell: bash
+ env:
+ SCOPES: ${{ needs.maybe-release.outputs.scopes }}
+ run: |
+ for scope in $SCOPES; do
+ scripts/ci/scope-tests.sh "$scope"
done
- if [ "$i" -gt "$attempts" ]; then
- echo "All "$attempts" attempts failed."
- exit 1
- fi
+
+ - name: Remove -O2 build directory
+ id: remove-o2
+ if: env.cache_o0 == 'true' && !cancelled() && steps.build-cli.outcome == 'success'
+ shell: docker exec -t builder sh -eu {0}
+ run: find dist-newstyle -mindepth 1 -maxdepth 1 ! -name src -exec rm -rf {} +
+
+ - name: Restore -O0 build directory from cache
+ id: restore-build-o0
+ if: ${{ !cancelled() && steps.remove-o2.outcome == 'success' }}
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-O0-
+
+ - name: Set old timestamps on unchanged sources for -O0 build (GHC 8.10.7)
+ if: ${{ !cancelled() && matrix.ghc == '8.10.7' && steps.restore-build-o0.outputs.cache-matched-key != '' && hashFiles(env.source_hashes) != '' }}
+ run: scripts/ci/source-timestamps.sh restore ${{ env.source_hashes }}
+
+ - name: Build at -O0 for pull request caches
+ id: build-o0
+ if: ${{ !cancelled() && steps.remove-o2.outcome == 'success' }}
+ shell: docker exec -t builder sh -eu {0}
+ run: |
+ scripts/ci/prune-old-builds.sh dist-newstyle
+ cabal build -j --enable-tests --ghc-options=-O0
+
+ - name: Record source hashes for -O0 build (GHC 8.10.7)
+ if: ${{ !cancelled() && matrix.ghc == '8.10.7' && steps.build-o0.outcome == 'success' }}
+ shell: docker exec -t builder sh -eu {0}
+ run: scripts/ci/source-timestamps.sh record ${{ env.source_hashes }}
+
+ - name: Save -O0 build directory to cache
+ if: ${{ !cancelled() && steps.build-o0.outcome == 'success' && steps.restore-build-o0.outputs.cache-hit != 'true' }}
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+
+ build-linux-full:
+ name: "ubuntu-${{ matrix.os }}-${{ matrix.arch }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
+ needs: [maybe-release, variables]
+ if: needs.maybe-release.outputs.reduced != 'true' && (needs.maybe-release.outputs.haskell == 'true' || needs.maybe-release.outputs.kotlin == 'true')
+ runs-on: ${{ matrix.runner }}
+ permissions:
+ contents: write
+ packages: write
+ env:
+ image_cache: ghcr.io/${{ github.repository_owner }}/simplex-chat-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}
+ source_hashes: dist-newstyle/sources.sha256
+ concurrency: *linux-concurrency
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: 24.04
+ os_underscore: 24_04
+ arch: x86_64
+ runner: "ubuntu-24.04"
+ should_run: ${{ needs.maybe-release.outputs.haskell == 'true' }}
+ ghc: ${{ needs.variables.outputs.GHC_VER }}
+ hash: 'sha256:98ff7968124952e719a8a69bb3cccdd217f5fe758108ac4f21ad22e1df44d237'
+ kotlin: ${{ needs.maybe-release.outputs.kotlin == 'true' }}
+ steps: *linux-steps
+
+ build-linux-push:
+ name: "ubuntu-${{ matrix.os }}-${{ matrix.arch }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
+ needs: [maybe-release, variables]
+ if: needs.maybe-release.outputs.reduced != 'true' && github.event_name == 'push'
+ runs-on: ${{ matrix.runner }}
+ permissions:
+ contents: write
+ packages: write
+ env:
+ image_cache: ghcr.io/${{ github.repository_owner }}/simplex-chat-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}
+ source_hashes: dist-newstyle/sources.sha256
+ cache_o0: false
+ concurrency: *linux-concurrency
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: 22.04
+ os_underscore: 22_04
+ arch: aarch64
+ runner: "ubuntu-22.04-arm"
+ should_run: true
+ ghc: ${{ needs.variables.outputs.GHC_VER }}
+ hash: 'sha256:6a62a4157b8775eaf4959cb629e757d32d39d1f4c8ac1b0ddc2510b555cf72f3'
+ libs: true
+ kotlin: false
+ - os: 24.04
+ os_underscore: 24_04
+ arch: aarch64
+ runner: "ubuntu-24.04-arm"
+ should_run: true
+ ghc: ${{ needs.variables.outputs.GHC_VER }}
+ hash: 'sha256:68434214381cb38287104e629fe8ee720167dd98cbb36ab1cbbab342515fa6ab'
+ kotlin: false
+ steps: *linux-steps
+
+ build-linux-ghc8:
+ name: "ubuntu-${{ matrix.os }}-${{ matrix.arch }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
+ needs: [maybe-release, variables]
+ if: ${{ needs.maybe-release.outputs.reduced != 'true' && needs.maybe-release.outputs.haskell == 'true' && !(github.ref == 'refs/heads/stable' || startsWith(github.ref, 'refs/tags/v')) }}
+ runs-on: ${{ matrix.runner }}
+ permissions:
+ contents: write
+ packages: write
+ env:
+ image_cache: ghcr.io/${{ github.repository_owner }}/simplex-chat-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}
+ source_hashes: dist-newstyle/sources.sha256
+ opt: O0
+ ghc_options: --ghc-options=-O0
+ cache_o0: false
+ concurrency: *linux-concurrency
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: 22.04
+ os_underscore: 22_04
+ arch: x86_64
+ runner: "ubuntu-22.04"
+ ghc: "8.10.7"
+ hash: 'sha256:5c8b2c0a6c745bc177669abfaa716b4bc57d58e2ea3882fb5da67f4d59e3dda5'
+ should_run: true
+ kotlin: false
+ steps: *linux-steps
# =================================
# Linux PostgreSQL Library Build
@@ -389,7 +882,7 @@ jobs:
name: "ubuntu-22.04-x86_64 (Postgres lib), GHC: ${{ needs.variables.outputs.GHC_VER }}"
needs: [maybe-release, variables]
runs-on: ubuntu-22.04
- if: startsWith(github.ref, 'refs/tags/v')
+ if: needs.maybe-release.outputs.libs_tag
steps:
- name: Checkout Code
uses: actions/checkout@v3
@@ -404,14 +897,6 @@ jobs:
shell: bash
run: ./scripts/ci/linux_util_free_space.sh
- - name: Restore cached build
- uses: actions/cache@v4
- with:
- path: |
- ~/.cabal/store
- dist-newstyle
- key: ubuntu-22.04-x86_64-postgres-ghc${{ needs.variables.outputs.GHC_VER }}-${{ hashFiles('cabal.project', 'simplex-chat.cabal') }}
-
- name: Set up Docker Buildx
uses: simplex-chat/docker-setup-buildx-action@v3
@@ -432,13 +917,35 @@ jobs:
- name: Start container
shell: bash
run: |
+ mkdir -p ~/.cabal
docker run -t -d \
--name builder \
- -v ~/.cabal:/root/.cabal \
+ -e CABAL_DIR=/home/builder/.cabal \
+ -v ~/.cabal:/home/builder/.cabal \
-v /home/runner/work/_temp:/home/runner/work/_temp \
-v ${{ github.workspace }}:/project \
build/22.04:latest
+ - name: Compute cache key prefix
+ id: keys
+ run: |
+ toolchain=$(docker exec builder dpkg-query -W -f '${db:Status-Status} ${binary:Package} ${Version}\n' 'binutils*' 'cpp*' 'gcc*' '*-dev' | grep '^installed ' | sha256sum | cut -c1-16)
+ echo "deps=deps-ubuntu-22.04-x86_64-postgres-ghc${{ needs.variables.outputs.GHC_VER }}-$toolchain" >> "$GITHUB_OUTPUT"
+
+ - name: Restore dependencies from cache
+ id: restore-deps
+ uses: actions/cache/restore@v4
+ with:
+ path: ~/.cabal/store
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.deps }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.deps }}-
+
+ - name: Warn if dependencies not in cache
+ if: steps.restore-deps.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.deps }}-${{ env.branch }}"
+
- name: Prepare cabal.project.local
shell: bash
run: |
@@ -449,31 +956,38 @@ jobs:
- name: Build postgres library
shell: docker exec -t builder sh -eu {0}
run: |
- cabal clean
cabal update
scripts/desktop/build-lib-linux.sh postgres
+ - name: Compute dependency cache key
+ id: hash-deps
+ shell: bash
+ run: echo "hash=$(ls ~/.cabal/store/ghc-*/ | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
+
+ - name: Save dependencies to cache
+ if: steps.restore-deps.outputs.cache-matched-key != format('{0}-{1}-{2}', steps.keys.outputs.deps, env.branch, steps.hash-deps.outputs.hash)
+ uses: actions/cache/save@v4
+ with:
+ path: ~/.cabal/store
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ steps.hash-deps.outputs.hash }}
+
- name: Copy libs from container
shell: bash
run: |
ARCH=x86_64
GHC_VER=${{ needs.variables.outputs.GHC_VER }}
BUILD_DIR=$(echo dist-newstyle/build/${ARCH}-linux/ghc-${GHC_VER}/simplex-chat-*)
- mkdir -p postgres-libs
- cp ${BUILD_DIR}/build/libsimplex.so postgres-libs/
- cp ${BUILD_DIR}/build/deps/* postgres-libs/
+ mkdir -p postgres-libs/libs
+ cp ${BUILD_DIR}/build/libsimplex.so postgres-libs/libs/
+ cp ${BUILD_DIR}/build/deps/* postgres-libs/libs/
+ (cd postgres-libs && zip -r simplex-chat-libs-linux-x86_64-postgres.zip libs)
- - name: Upload postgres libs artifact
- uses: actions/upload-artifact@v4
- with:
- name: simplex-libs-linux-postgres-x86_64
- path: postgres-libs/
-
- - name: Fix permissions for cache
+ - name: Upload postgres library
shell: bash
- run: |
- sudo chmod -R 777 dist-newstyle ~/.cabal
- sudo chown -R $(id -u):$(id -g) dist-newstyle ~/.cabal
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ TAG: ${{ needs.maybe-release.outputs.libs_tag }}
+ run: gh release upload "$TAG" postgres-libs/*.zip --clobber --repo "${{ github.repository }}-libs"
# =========================
# MacOS Build
@@ -482,44 +996,92 @@ jobs:
build-macos:
name: "${{ matrix.os }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
needs: [maybe-release, variables]
+ if: needs.maybe-release.outputs.reduced != 'true' && needs.maybe-release.outputs.haskell == 'true'
runs-on: ${{ matrix.os }}
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}-macos-${{ matrix.os }}-${{ needs.maybe-release.outputs.libs_tag }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
strategy:
fail-fast: false
matrix:
include:
- os: macos-latest
+ arch: aarch64
ghc: ${{ needs.variables.outputs.GHC_VER }}
cli_asset_name: simplex-chat-macos-aarch64
desktop_asset_name: simplex-desktop-macos-aarch64.dmg
openssl_dir: "/opt/homebrew/opt"
+ should_run: ${{ needs.maybe-release.outputs.haskell == 'true' }}
- os: macos-15-intel
+ arch: x86_64
ghc: ${{ needs.variables.outputs.GHC_VER }}
cli_asset_name: simplex-chat-macos-x86-64
desktop_asset_name: simplex-desktop-macos-x86_64.dmg
openssl_dir: "/usr/local/opt"
+ should_run: ${{ needs.maybe-release.outputs.haskell == 'true' }}
steps:
- name: Checkout Code
+ if: matrix.should_run == true
uses: actions/checkout@v3
with:
submodules: recursive
+ - name: Point Command Line Tools SDK to Xcode SDK
+ if: matrix.should_run == true
+ shell: bash
+ run: sudo ln -sfn "$(xcrun --sdk macosx --show-sdk-path)" /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk
+
+ - name: Compute toolchain cache key
+ id: toolchain-key
+ if: matrix.should_run == true && env.release != 'true'
+ shell: bash
+ run: echo "key=ghcup-${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}-cabal3.10.2.0-$({ sw_vers -productVersion; clang --version; } | shasum -a 256 | cut -c1-16)" >> "$GITHUB_OUTPUT"
+
+ - name: Restore toolchain from cache
+ id: restore-toolchain
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ ~/.ghcup/ghc/${{ matrix.ghc }}
+ ~/.ghcup/bin/*-${{ matrix.ghc }}
+ ~/.ghcup/bin/cabal-3.10.2.0
+ key: ${{ steps.toolchain-key.outputs.key }}
+
+ - name: Warn if toolchain not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-toolchain.outputs.cache-hit != 'true'
+ run: echo "::warning title=Cache miss::${{ steps.toolchain-key.outputs.key }}"
+
- name: Prepare build
+ id: prepare
+ if: matrix.should_run == true
uses: ./.github/actions/prepare-build
with:
java_ver: ${{ needs.variables.outputs.JAVA_VER }}
ghc_ver: ${{ matrix.ghc }}
- os: ${{ matrix.os }}
github_ref: ${{ github.ref }}
+ - name: Save toolchain to cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-toolchain.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ ~/.ghcup/ghc/${{ matrix.ghc }}
+ ~/.ghcup/bin/*-${{ matrix.ghc }}
+ ~/.ghcup/bin/cabal-3.10.2.0
+ key: ${{ steps.toolchain-key.outputs.key }}
+
- name: Install OpenSSL
+ if: matrix.should_run == true
run: brew install openssl@3.0
- name: Prepare cabal.project.local
+ if: matrix.should_run == true
shell: bash
run: |
echo "ignore-project: False" >> cabal.project.local
echo "package simplexmq" >> cabal.project.local
- echo " extra-include-dirs: ${{ matrix.opnessl_dir }}/openssl@3.0/include" >> cabal.project.local
+ echo " extra-include-dirs: ${{ matrix.openssl_dir }}/openssl@3.0/include" >> cabal.project.local
echo " extra-lib-dirs: ${{ matrix.openssl_dir}}/openssl@3.0/lib" >> cabal.project.local
echo "" >> cabal.project.local
echo "package direct-sqlcipher" >> cabal.project.local
@@ -527,17 +1089,103 @@ jobs:
echo " extra-lib-dirs: ${{ matrix.openssl_dir }}/openssl@3.0/lib" >> cabal.project.local
echo " flags: +openssl" >> cabal.project.local
- - name: Build CLI
- id: mac_cli_build
+ - name: Compute cache key prefixes
+ id: keys
+ if: matrix.should_run == true && env.release != 'true'
shell: bash
run: |
- cabal build -j --enable-tests
- path=$(cabal list-bin simplex-chat)
+ toolchain=$({ sw_vers -productVersion; clang --version; } | shasum -a 256 | cut -c1-16)
+ target=${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }}-$toolchain
+ echo "deps=deps-$target" >> "$GITHUB_OUTPUT"
+ echo "dist=dist-$target" >> "$GITHUB_OUTPUT"
+
+ - name: Restore dependencies from cache
+ id: restore-deps
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: ${{ steps.prepare.outputs.cabal-store }}
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.deps }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.deps }}-
+
+ - name: Warn if dependencies not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-deps.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.deps }}-${{ env.branch }}"
+
+ - name: Restore source repositories from cache
+ id: restore-src
+ if: matrix.should_run == true && env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+ restore-keys: src-${{ runner.os }}-
+
+ - name: Warn if source repositories not in cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-src.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::src-${{ runner.os }}"
+
+ - name: Restore build directory from cache
+ id: restore-build
+ if: matrix.should_run == true && env.release != 'true' && !needs.maybe-release.outputs.libs_tag
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-
+
+ - name: Warn if build directory not in cache
+ if: matrix.should_run == true && steps.restore-build.outcome == 'success' && steps.restore-build.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}"
+
+ - name: Build CLI
+ id: mac_cli_build
+ if: matrix.should_run == true
+ shell: bash
+ run: |
+ scripts/ci/prune-old-builds.sh dist-newstyle
+ cabal build -j --enable-tests ${{ env.ghc_options }}
+ path=$(cabal list-bin simplex-chat | tail -n 1)
echo "bin_path=$path" >> $GITHUB_OUTPUT
echo "bin_hash=$(echo SHA2-256\(${{ matrix.cli_asset_name }}\)= $(openssl sha256 $path | cut -d' ' -f 2))" >> $GITHUB_OUTPUT
+ - name: Compute dependency cache key
+ id: hash-deps
+ if: matrix.should_run == true && env.release != 'true'
+ shell: bash
+ run: echo "hash=$(ls '${{ steps.prepare.outputs.cabal-store }}'/ghc-*/ | shasum -a 256 | cut -c1-16)" >> "$GITHUB_OUTPUT"
+
+ - name: Save dependencies to cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-deps.outputs.cache-matched-key != format('{0}-{1}-{2}', steps.keys.outputs.deps, env.branch, steps.hash-deps.outputs.hash)
+ uses: actions/cache/save@v4
+ with:
+ path: ${{ steps.prepare.outputs.cabal-store }}
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ steps.hash-deps.outputs.hash }}
+
+ - name: Save source repositories to cache
+ if: matrix.should_run == true && env.release != 'true' && matrix.arch == 'x86_64' && steps.restore-src.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+
+ - name: Save build directory to cache
+ if: matrix.should_run == true && env.release != 'true' && steps.restore-build.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+
- name: Upload CLI
- if: startsWith(github.ref, 'refs/tags/v')
+ if: matrix.should_run == true && startsWith(github.ref, 'refs/tags/v')
uses: ./.github/actions/prepare-release
with:
bin_path: ${{ steps.mac_cli_build.outputs.bin_path }}
@@ -548,7 +1196,7 @@ jobs:
- name: Build Desktop
id: mac_desktop_build
- if: startsWith(github.ref, 'refs/tags/v')
+ if: matrix.should_run == true && startsWith(github.ref, 'refs/tags/v')
shell: bash
env:
APPLE_SIMPLEX_SIGNING_KEYCHAIN: ${{ secrets.APPLE_SIMPLEX_SIGNING_KEYCHAIN }}
@@ -562,7 +1210,7 @@ jobs:
echo "package_hash=$(echo SHA2-256\(${{ matrix.desktop_asset_name }}\)= $(openssl sha256 $path | cut -d' ' -f 2))" >> $GITHUB_OUTPUT
- name: Upload Desktop
- if: startsWith(github.ref, 'refs/tags/v')
+ if: matrix.should_run == true && startsWith(github.ref, 'refs/tags/v')
uses: ./.github/actions/prepare-release
with:
bin_path: ${{ steps.mac_desktop_build.outputs.package_path }}
@@ -571,7 +1219,16 @@ jobs:
github_ref: ${{ github.ref }}
github_token: ${{ secrets.GITHUB_TOKEN }}
+ - name: Mount RAM disk for tests
+ if: matrix.should_run == true && matrix.arch == 'aarch64'
+ shell: bash
+ run: |
+ disk=$(hdiutil attach -nomount ram://4194304 | tr -d '[:space:]')
+ diskutil erasevolume APFS tests "$disk"
+ ln -s /Volumes/tests tests/tmp
+
- name: Run tests
+ if: matrix.should_run == true && matrix.arch == 'aarch64'
timeout-minutes: 120
shell: bash
run: |
@@ -579,7 +1236,7 @@ jobs:
attempts=1
${{ (github.ref == 'refs/heads/stable' || startsWith(github.ref, 'refs/tags/v')) }} && attempts=3
while [ "$i" -le "$attempts" ]; do
- if cabal test --test-show-details=direct; then
+ if cabal test --test-show-details=direct ${{ env.ghc_options }}; then
break
else
echo "Attempt $i failed, retrying..."
@@ -592,6 +1249,151 @@ jobs:
exit 1
fi
+ - name: Build library
+ id: mac_lib_build
+ if: ${{ !cancelled() && matrix.should_run == true && needs.maybe-release.outputs.libs_tag && steps.mac_cli_build.outcome == 'success' }}
+ shell: bash
+ env:
+ APPLE_SIMPLEX_SIGNING_KEYCHAIN: ${{ secrets.APPLE_SIMPLEX_SIGNING_KEYCHAIN }}
+ APPLE_SIMPLEX_NOTARIZATION_APPLE_ID: ${{ secrets.APPLE_SIMPLEX_NOTARIZATION_APPLE_ID }}
+ APPLE_SIMPLEX_NOTARIZATION_PASSWORD: ${{ secrets.APPLE_SIMPLEX_NOTARIZATION_PASSWORD }}
+ run: |
+ SKIP_VLC=1 scripts/desktop/build-lib-mac.sh
+ name=simplex-chat-libs-macos-${{ matrix.arch }}
+ mkdir -p release-libs/$name/libs
+ find apps/multiplatform/common/src/commonMain/cpp/desktop/libs/mac-${{ matrix.arch }} -maxdepth 1 -type f -exec cp {} release-libs/$name/libs/ \;
+ scripts/ci/sign-libs-mac.sh release-libs/$name/libs
+ (cd release-libs/$name && zip -r ../$name.zip libs)
+
+ - name: Upload library
+ if: ${{ !cancelled() && matrix.should_run == true && steps.mac_lib_build.outcome == 'success' }}
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ TAG: ${{ needs.maybe-release.outputs.libs_tag }}
+ run: gh release upload "$TAG" release-libs/*.zip --clobber --repo "${{ github.repository }}-libs"
+
+ - name: Setup Node.js
+ id: setup-node
+ if: ${{ !cancelled() && matrix.should_run == true && (github.event_name == 'pull_request' || needs.maybe-release.outputs.addon_draft || needs.maybe-release.outputs.publish) }}
+ uses: actions/setup-node@v7
+ with:
+ node-version: 22
+
+ - name: Setup Python
+ id: setup-python
+ if: ${{ !cancelled() && matrix.should_run == true && steps.setup-node.outcome == 'success' }}
+ uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ - name: Package tests (pull request)
+ if: ${{ !cancelled() && matrix.should_run == true && steps.setup-python.outcome == 'success' && github.event_name == 'pull_request' }}
+ timeout-minutes: 30
+ shell: bash
+ run: |
+ scripts/ci/package-tests.sh build macos-${{ matrix.arch }}
+ scripts/ci/package-tests.sh test
+
+ - name: Add-on
+ if: ${{ !cancelled() && matrix.should_run == true && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.addon_draft }}
+ timeout-minutes: 30
+ shell: bash
+ env:
+ LIBS_RELEASE: ${{ needs.maybe-release.outputs.libs_latest }}
+ ADDON_TAG: ${{ needs.maybe-release.outputs.addon_tag }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ run: scripts/ci/package-tests.sh addon macos-${{ matrix.arch }}
+
+ - name: Package tests
+ id: package-tests
+ if: ${{ !cancelled() && matrix.should_run == true && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.publish }}
+ timeout-minutes: 30
+ shell: bash
+ run: |
+ scripts/ci/package-tests.sh publish macos-${{ matrix.arch }} ${{ needs.maybe-release.outputs.publish_nodejs && 'nodejs' || '' }} ${{ needs.maybe-release.outputs.publish_python && 'python' || '' }}
+ echo "macos-${{ matrix.arch }}" > "$RUNNER_TEMP/package-tests"
+
+ - name: Package tests result
+ if: ${{ !cancelled() && matrix.should_run == true && steps.package-tests.outcome == 'success' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: package-tests-macos-${{ matrix.arch }}
+ path: ${{ runner.temp }}/package-tests
+
+ - name: Remove -O2 build directory
+ id: remove-o2
+ if: matrix.should_run == true && env.cache_o0 == 'true' && !cancelled() && steps.mac_cli_build.outcome == 'success'
+ shell: bash
+ run: find dist-newstyle -mindepth 1 -maxdepth 1 ! -name src -exec rm -rf {} +
+
+ - name: Restore -O0 build directory from cache
+ id: restore-build-o0
+ if: ${{ !cancelled() && matrix.should_run == true && steps.remove-o2.outcome == 'success' }}
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-O0-
+
+ - name: Build at -O0 for pull request caches
+ id: build-o0
+ if: ${{ !cancelled() && matrix.should_run == true && steps.remove-o2.outcome == 'success' }}
+ shell: bash
+ run: |
+ scripts/ci/prune-old-builds.sh dist-newstyle
+ cabal build -j --enable-tests --ghc-options=-O0
+
+ - name: Save -O0 build directory to cache
+ if: ${{ !cancelled() && matrix.should_run == true && steps.build-o0.outcome == 'success' && steps.restore-build-o0.outputs.cache-hit != 'true' }}
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+
+ build-ios:
+ name: "macos-latest (iOS)"
+ needs: maybe-release
+ if: needs.maybe-release.outputs.ios == 'true'
+ runs-on: macos-latest
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}-ios
+ cancel-in-progress: ${{ github.event_name != 'push' }}
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v3
+
+ - name: Point Command Line Tools SDK to Xcode SDK
+ shell: bash
+ run: sudo ln -sfn "$(xcrun --sdk macosx --show-sdk-path)" /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk
+
+ - name: Check the previews listed in the snapshot tests
+ shell: bash
+ run: python3 "apps/ios/SimpleX Snapshots/check-previews.py"
+
+ - name: Build iOS app
+ timeout-minutes: 60
+ shell: bash
+ run: |
+ scripts/ci/ios-stub-libs.sh
+ xcodebuild build -quiet \
+ -project apps/ios/SimpleX.xcodeproj \
+ -scheme "SimpleX (iOS)" \
+ -configuration Debug \
+ -destination "generic/platform=iOS Simulator" \
+ -onlyUsePackageVersionsFromResolvedFile \
+ -skipPackagePluginValidation \
+ -skipMacroValidation \
+ ARCHS=arm64 \
+ CODE_SIGNING_ALLOWED=NO
+
# =========================
# Windows Build
# =========================
@@ -599,7 +1401,11 @@ jobs:
build-windows:
name: "${{ matrix.os }} (CLI,Desktop), GHC: ${{ matrix.ghc }}"
needs: [maybe-release, variables]
+ if: needs.maybe-release.outputs.reduced != 'true' && needs.maybe-release.outputs.haskell == 'true'
runs-on: ${{ matrix.os }}
+ concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}-windows-${{ matrix.os }}-${{ needs.maybe-release.outputs.libs_tag }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
strategy:
fail-fast: false
matrix:
@@ -615,12 +1421,11 @@ jobs:
submodules: recursive
- name: Prepare build
+ id: prepare
uses: ./.github/actions/prepare-build
with:
java_ver: ${{ needs.variables.outputs.JAVA_VER }}
ghc_ver: ${{ matrix.ghc }}
- os: ${{ matrix.os }}
- cache_path: "C:/cabal"
github_ref: ${{ github.ref }}
- name: Configure pagefile (Windows)
@@ -639,12 +1444,68 @@ jobs:
git
perl
make
+ zip
pacboy: >-
toolchain:p
cmake:p
- # rm -rf dist-newstyle/src/{direct-sq,simplexmq}* is here because of the bug in cabal's dependency which prevents second build from finishing
- # (simplexmq is removed because cabal cannot delete its read-only git submodule pack files - blst, libbbs - on Windows)
+ - name: Compute cache key prefixes
+ id: keys
+ if: env.release != 'true'
+ shell: msys2 {0}
+ run: |
+ toolchain=$(gcc --version | sha256sum | cut -c1-16)
+ target=windows-x86_64-ghc${{ matrix.ghc }}-$toolchain
+ echo "deps=deps-$target" >> "$GITHUB_OUTPUT"
+ echo "dist=dist-$target" >> "$GITHUB_OUTPUT"
+
+ - name: Restore dependencies from cache
+ id: restore-deps
+ if: env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: ${{ steps.prepare.outputs.cabal-store }}
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.deps }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.deps }}-
+
+ - name: Warn if dependencies not in cache
+ if: env.release != 'true' && steps.restore-deps.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.deps }}-${{ env.branch }}"
+
+ - name: Restore source repositories from cache
+ id: restore-src
+ if: env.release != 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+ restore-keys: src-${{ runner.os }}-
+
+ - name: Warn if source repositories not in cache
+ if: env.release != 'true' && steps.restore-src.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::src-${{ runner.os }}"
+
+ - name: Restore build directory from cache
+ id: restore-build
+ if: env.release != 'true' && !needs.maybe-release.outputs.libs_tag
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-${{ env.opt }}-
+
+ - name: Warn if build directory not in cache
+ if: steps.restore-build.outcome == 'success' && steps.restore-build.outputs.cache-matched-key == ''
+ run: echo "::warning title=Cache miss::${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}"
+
+ # rm -rf dist-newstyle/src/{direct-sq,simplexmq,hs-jpeg-t,JuicyPixe}* is here because of the bug in cabal's dependency which prevents second build from finishing
+ # (simplexmq, hs-jpeg-turbo and JuicyPixels-stbir are removed because cabal cannot delete their read-only git submodule pack files - blst, libbbs, mozjpeg, stb - on Windows)
- name: Build CLI
id: windows_cli_build
shell: msys2 {0}
@@ -659,14 +1520,114 @@ jobs:
echo " extra-include-dirs: $openssl_windows_style_path\include" >> cabal.project.local
echo " extra-lib-dirs: $openssl_windows_style_path" >> cabal.project.local
- rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq*
+ scripts/ci/prune-old-builds.sh dist-newstyle
+ rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq* dist-newstyle/src/hs-jpeg-t* dist-newstyle/src/JuicyPixe*
sed -i "s/, unix /--, unix /" simplex-chat.cabal
- cabal build -j --enable-tests
- rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq*
+ cabal build -j --enable-tests ${{ env.ghc_options }}
+ rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq* dist-newstyle/src/hs-jpeg-t* dist-newstyle/src/JuicyPixe*
path=$(cabal list-bin simplex-chat | tail -n 1)
echo "bin_path=$path" >> $GITHUB_OUTPUT
echo "bin_hash=$(echo SHA2-256\(${{ matrix.cli_asset_name }}\)= $(openssl sha256 $path | cut -d' ' -f 2))" >> $GITHUB_OUTPUT
+ - name: Compute dependency cache key
+ id: hash-deps
+ if: env.release != 'true'
+ shell: msys2 {0}
+ run: echo "hash=$(ls "$(cygpath -u '${{ steps.prepare.outputs.cabal-store }}')"/ghc-*/ | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
+
+ - name: Save dependencies to cache
+ if: env.release != 'true' && steps.restore-deps.outputs.cache-matched-key != format('{0}-{1}-{2}', steps.keys.outputs.deps, env.branch, steps.hash-deps.outputs.hash)
+ uses: actions/cache/save@v4
+ with:
+ path: ${{ steps.prepare.outputs.cabal-store }}
+ key: ${{ steps.keys.outputs.deps }}-${{ env.branch }}-${{ steps.hash-deps.outputs.hash }}
+
+ - name: Save source repositories to cache
+ if: env.release != 'true' && steps.restore-src.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: dist-newstyle/src
+ key: src-${{ runner.os }}-${{ hashFiles('cabal.project') }}
+
+ - name: Save build directory to cache
+ if: env.release != 'true' && steps.restore-build.outputs.cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-${{ env.opt }}-${{ env.branch }}-${{ github.sha }}
+
+ - name: Build library
+ if: needs.maybe-release.outputs.libs_tag
+ shell: msys2 {0}
+ run: |
+ export PATH=$PATH:/c/ghcup/bin:$(echo /c/tools/ghc-*/bin || echo)
+ SKIP_VLC=1 scripts/desktop/build-lib-windows.sh
+ dlltool -d libsimplex.dll.def -l libsimplex.lib -D libsimplex.dll
+ name=simplex-chat-libs-windows-x86_64
+ mkdir -p release-libs/$name/libs
+ find apps/multiplatform/common/src/commonMain/cpp/desktop/libs/windows-x86_64 -maxdepth 1 -type f -exec cp {} release-libs/$name/libs/ \;
+ cp libsimplex.lib release-libs/$name/libs/
+ (cd release-libs/$name && zip -r ../$name.zip libs)
+
+ - name: Upload library
+ if: needs.maybe-release.outputs.libs_tag
+ shell: bash
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ TAG: ${{ needs.maybe-release.outputs.libs_tag }}
+ run: gh release upload "$TAG" release-libs/*.zip --clobber --repo "${{ github.repository }}-libs"
+
+ - name: Setup Node.js
+ id: setup-node
+ if: ${{ !cancelled() && (github.event_name == 'pull_request' || needs.maybe-release.outputs.addon_draft || needs.maybe-release.outputs.publish) }}
+ uses: actions/setup-node@v7
+ with:
+ node-version: 22
+
+ - name: Setup Python
+ id: setup-python
+ if: ${{ !cancelled() && steps.setup-node.outcome == 'success' }}
+ uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ - name: Package tests (pull request)
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && github.event_name == 'pull_request' }}
+ timeout-minutes: 30
+ shell: bash
+ run: |
+ scripts/ci/package-tests.sh build windows-x86_64
+ scripts/ci/package-tests.sh test
+
+ - name: Add-on
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.addon_draft }}
+ timeout-minutes: 30
+ shell: bash
+ env:
+ LIBS_RELEASE: ${{ needs.maybe-release.outputs.libs_latest }}
+ ADDON_TAG: ${{ needs.maybe-release.outputs.addon_tag }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ run: scripts/ci/package-tests.sh addon windows-x86_64
+
+ - name: Package tests
+ id: package-tests
+ if: ${{ !cancelled() && steps.setup-python.outcome == 'success' && needs.maybe-release.outputs.publish }}
+ timeout-minutes: 30
+ shell: bash
+ run: |
+ scripts/ci/package-tests.sh publish windows-x86_64 ${{ needs.maybe-release.outputs.publish_nodejs && 'nodejs' || '' }} ${{ needs.maybe-release.outputs.publish_python && 'python' || '' }}
+ echo "windows-x86_64" > "$RUNNER_TEMP/package-tests"
+
+ - name: Package tests result
+ if: ${{ !cancelled() && steps.package-tests.outcome == 'success' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: package-tests-windows-x86_64
+ path: ${{ runner.temp }}/package-tests
+
- name: Upload CLI
if: startsWith(github.ref, 'refs/tags/v')
uses: ./.github/actions/prepare-release
@@ -686,7 +1647,7 @@ jobs:
scripts/desktop/build-lib-windows.sh
cd apps/multiplatform
./gradlew -Psimplex.assets.dir=../../assets packageMsi
- rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq*
+ rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq* dist-newstyle/src/hs-jpeg-t* dist-newstyle/src/JuicyPixe*
path=$(echo $PWD/release/main/msi/*imple*.msi | sed 's#/\([a-z]\)#\1:#' | sed 's#/#\\#g')
echo "package_path=$path" >> $GITHUB_OUTPUT
echo "package_hash=$(echo SHA2-256\(${{ matrix.desktop_asset_name }}\)= $(openssl sha256 $path | cut -d' ' -f 2))" >> $GITHUB_OUTPUT
@@ -701,109 +1662,232 @@ jobs:
github_ref: ${{ github.ref }}
github_token: ${{ secrets.GITHUB_TOKEN }}
+ - name: Remove -O2 build directory
+ id: remove-o2
+ if: env.cache_o0 == 'true' && !needs.maybe-release.outputs.libs_tag && !cancelled() && steps.windows_cli_build.outcome == 'success'
+ shell: msys2 {0}
+ run: find dist-newstyle -mindepth 1 -maxdepth 1 ! -name src -exec rm -rf {} +
+
+ - name: Restore -O0 build directory from cache
+ id: restore-build-o0
+ if: ${{ !cancelled() && steps.remove-o2.outcome == 'success' }}
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+ restore-keys: |
+ ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-
+ ${{ steps.keys.outputs.dist }}-O0-
+
+ - name: Build at -O0 for pull request caches
+ id: build-o0
+ if: ${{ !cancelled() && steps.remove-o2.outcome == 'success' }}
+ shell: msys2 {0}
+ run: |
+ export PATH=$PATH:/c/ghcup/bin:$(echo /c/tools/ghc-*/bin || echo)
+ scripts/desktop/prepare-openssl-windows.sh
+ scripts/ci/prune-old-builds.sh dist-newstyle
+ rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq* dist-newstyle/src/hs-jpeg-t* dist-newstyle/src/JuicyPixe*
+ cabal build -j --enable-tests --ghc-options=-O0
+ rm -rf dist-newstyle/src/direct-sq* dist-newstyle/src/simplexmq* dist-newstyle/src/hs-jpeg-t* dist-newstyle/src/JuicyPixe*
+
+ - name: Save -O0 build directory to cache
+ if: ${{ !cancelled() && steps.build-o0.outcome == 'success' && steps.restore-build-o0.outputs.cache-hit != 'true' }}
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ dist-newstyle/*
+ !dist-newstyle/src
+ key: ${{ steps.keys.outputs.dist }}-O0-${{ env.branch }}-${{ github.sha }}
+
# =========================
-# NodeJS libs release
+# Releases and packages
# =========================
-# Downloads Desktop builds, extracts and archives libraries for NodeJS addon.
-# Depends on Linux/MacOS, executes only on release.
-
-# Secrets:
-# -------
-# NODEJS_REPO_TOKEN
-# Only select repositories: simplex-chat-libs
-# Permissions:
-# * Contents (Read and Write)
-
- release-nodejs-libs:
+ releases:
+ needs: [maybe-release, build-linux, build-linux-full, build-linux-push, build-linux-postgres, build-macos, build-ios, build-windows]
+ if: ${{ !cancelled() && (needs.maybe-release.outputs.libs_tag || needs.maybe-release.outputs.addon_draft) }}
runs-on: ubuntu-latest
- needs: [build-linux, build-linux-postgres, build-macos]
- if: startsWith(github.ref, 'refs/tags/v') && (!cancelled())
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
steps:
- - name: Checkout current repository
+ - name: Checkout Code
uses: actions/checkout@v6
- - name: Install packages for archiving
- run: sudo apt install -y msitools gcc-mingw-w64
+ - name: Publish library release
+ if: needs.maybe-release.outputs.libs_tag
+ run: python3 scripts/ci/packages_release.py publish-release "${{ needs.maybe-release.outputs.libs_tag }}"
- - name: Download postgres libs artifact
- if: needs.build-linux-postgres.result == 'success'
- uses: actions/download-artifact@v4
+ - name: Publish add-on release
+ if: ${{ !cancelled() && needs.maybe-release.outputs.addon_draft }}
+ run: python3 scripts/ci/packages_release.py publish-release "${{ needs.maybe-release.outputs.addon_tag }}"
+
+# Publishing uses trusted publishing (OIDC) for this workflow on npm and PyPI,
+# or the NPM_TOKEN and PYPI_API_TOKEN secrets when they are set.
+# Test repositories: variables NPM_SCOPE, PYPI_PROJECT and PYPI_URL / PYPI_UPLOAD_URL (TestPyPI)
+# publish under other names.
+
+ publish:
+ needs: [maybe-release, build-linux, build-linux-full, build-linux-push, build-macos, build-ios, build-windows, releases]
+ if: ${{ !cancelled() && (needs.maybe-release.outputs.publish || needs.maybe-release.outputs.publish_types || needs.maybe-release.outputs.publish_mcp) }}
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write
+ # set by a publish step after it succeeds, so a failed publish still reports the earlier ones
+ outputs:
+ types: ${{ steps.types.outputs.version }}
+ nodejs: ${{ steps.nodejs.outputs.version }}
+ mcp: ${{ steps.mcp.outputs.version }}
+ python: ${{ steps.python.outputs.version }}
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+ NPM_SCOPE: ${{ vars.NPM_SCOPE }}
+ PYPI_PROJECT: ${{ vars.PYPI_PROJECT }}
+ PYPI_URL: ${{ vars.PYPI_URL }}
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v6
+
+ - name: Download package tests results
+ if: needs.maybe-release.outputs.publish
+ uses: actions/download-artifact@v8
with:
- name: simplex-libs-linux-postgres-x86_64
- path: ${{ runner.temp }}/postgres-libs
+ pattern: package-tests-*
+ path: ${{ runner.temp }}/package-tests
- - name: Build archives
+ - name: Check package tests and pins
+ if: needs.maybe-release.outputs.publish
+ env:
+ GH_TOKEN: ${{ github.token }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
run: |
- INIT_DIR='${{ runner.temp }}/artifacts'
- RELEASE_DIR='${{ runner.temp }}/release-assets'
- TAG='${{ github.ref_name }}'
- URL='https://github.com/${{ github.repository }}/releases/download'
- PREFIX='${{ github.event.repository.name }}-libs'
- # Windows-specific
- FILE_URL='https://raw.githubusercontent.com/${{ github.repository }}/refs/tags/${{ github.ref_name }}'
-
- # Setup directories
- mkdir "$INIT_DIR" "$RELEASE_DIR" && cd "$INIT_DIR"
-
- # Downlaod desktop release
- curl --proto '=https' --tlsv1.2 -sSf -L "${URL}/${TAG}/simplex-desktop-ubuntu-22_04-x86_64.deb" -o linux.deb
- curl --proto '=https' --tlsv1.2 -sSf -L "${URL}/${TAG}/simplex-desktop-macos-aarch64.dmg" -o macos-aarch64.dmg
- curl --proto '=https' --tlsv1.2 -sSf -L "${URL}/${TAG}/simplex-desktop-macos-x86_64.dmg" -o macos-x86_64.dmg
- curl --proto '=https' --tlsv1.2 -sSf -L "${URL}/${TAG}/simplex-desktop-windows-x86_64.msi" -o windows-x86_64.msi
-
- # Linux
- # -----
- # Extract libraries
- dpkg-deb -R linux.deb linux-out/ && cd linux-out/opt/simplex/lib/app/resources
- # Preprare directory
- mkdir libs && cp *.so libs/
- # Archive
- zip -r "${PREFIX}-linux-x86_64.zip" libs
- # Back to original dir
- mv "${PREFIX}-linux-x86_64.zip" "$RELEASE_DIR" && cd "$INIT_DIR"
-
- # MacOS: aarch64
- # --------------
- 7z x macos-aarch64.dmg -omacos1-out/ && cd macos1-out/SimpleX/SimpleX.app/Contents/app/resources/
- mkdir libs && cp *.dylib libs/
- zip -r "${PREFIX}-macos-aarch64.zip" libs
- mv "${PREFIX}-macos-aarch64.zip" "$RELEASE_DIR" && cd "$INIT_DIR"
-
- # Macos: x86_64
- # -------------
- 7z x macos-x86_64.dmg -omacos2-out/ && cd macos2-out/SimpleX/SimpleX.app/Contents/app/resources/
- mkdir libs && cp *.dylib libs/
- zip -r "${PREFIX}-macos-x86_64.zip" libs
- mv "${PREFIX}-macos-x86_64.zip" "$RELEASE_DIR" && cd "$INIT_DIR"
-
- # Windows: x86_64
- # ---------------
- msiextract windows-x86_64.msi -C windows-out && cd windows-out/SimpleX/app/resources
-
- # We need to generate library that exports symbols from Windows dll
- curl --proto '=https' --tlsv1.2 -sSf -LO "${FILE_URL}/libsimplex.dll.def"
- x86_64-w64-mingw32-dlltool -d libsimplex.dll.def -l libsimplex.lib -D libsimplex.dll
-
- mkdir libs && cp *.dll *.lib libs/
- zip -r "${PREFIX}-windows-x86_64.zip" libs
- mv "${PREFIX}-windows-x86_64.zip" "$RELEASE_DIR" && cd "$INIT_DIR"
-
- # Linux PostgreSQL (only if postgres build succeeded)
- # -------------------------------------------------
- POSTGRES_LIBS='${{ runner.temp }}/postgres-libs'
- if [ -d "$POSTGRES_LIBS" ]; then
- mkdir -p linux-postgres/libs
- cp "${POSTGRES_LIBS}"/*.so linux-postgres/libs/
- cd linux-postgres
- zip -r "${PREFIX}-linux-x86_64-postgres.zip" libs
- mv "${PREFIX}-linux-x86_64-postgres.zip" "$RELEASE_DIR" && cd "$INIT_DIR"
+ passed=$(find "$RUNNER_TEMP/package-tests" -mindepth 1 -maxdepth 1 -type d -name 'package-tests-*' | wc -l)
+ if [ "$passed" -ne 5 ]; then
+ echo "::error::package tests passed on $passed of 5 platforms"
+ exit 1
fi
+ python3 scripts/ci/packages_release.py check-pins
- - name: Create release in libs repo and upload artifacts
- uses: softprops/action-gh-release@v2
+ - name: Versions to publish
+ id: plan
+ env:
+ GH_TOKEN: ${{ github.token }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ run: python3 scripts/ci/packages_release.py publish-plan >> "$GITHUB_OUTPUT"
+
+ - name: Setup Node.js
+ if: steps.plan.outputs.types_version || steps.plan.outputs.nodejs_version || steps.plan.outputs.mcp_version
+ uses: actions/setup-node@v7
with:
- repository: ${{ github.repository }}-libs
- tag_name: ${{ github.ref_name }}
- files: ${{ runner.temp }}/release-assets/*
- token: ${{ secrets.NODEJS_REPO_TOKEN }}
+ node-version: 24
+ registry-url: https://registry.npmjs.org
+
+ - name: Setup Python
+ if: steps.plan.outputs.python_version
+ uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ # Before the test names: the build installs @simplex-chat/types from this repository.
+ - name: Build and test simplex-chat (npm)
+ if: steps.plan.outputs.nodejs_version
+ working-directory: packages/simplex-chat-nodejs
+ run: |
+ (cd ../simplex-chat-client/types/typescript && npm install --no-audit --no-fund && npx tsc)
+ npm install --ignore-scripts --no-save --no-audit --no-fund ../simplex-chat-client/types/typescript
+ npx tsc && cp src/simplex.* dist
+ npx jest tests/libs.test.ts tests/api.unit.test.ts
+
+ - name: Use test package names
+ if: vars.NPM_SCOPE || vars.PYPI_PROJECT
+ run: python3 scripts/ci/packages_release.py test-names
+
+ - name: Publish @simplex-chat/types
+ id: types
+ if: steps.plan.outputs.types_version && needs.maybe-release.outputs.publish_types && needs.releases.result == 'success'
+ working-directory: packages/simplex-chat-client/types/typescript
+ env:
+ VERSION: ${{ steps.plan.outputs.types_version }}
+ DIST_TAG: ${{ steps.plan.outputs.types_dist_tag }}
+ run: |
+ npm install --no-audit --no-fund
+ npm publish --provenance --access public --tag "$DIST_TAG"
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+
+ - name: Publish simplex-chat (npm)
+ id: nodejs
+ if: steps.plan.outputs.nodejs_version
+ working-directory: packages/simplex-chat-nodejs
+ env:
+ VERSION: ${{ steps.plan.outputs.nodejs_version }}
+ DIST_TAG: ${{ steps.plan.outputs.nodejs_dist_tag }}
+ run: |
+ npm publish --provenance --access public --tag "$DIST_TAG"
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+
+ - name: Build and test simplex-chat (PyPI)
+ if: steps.plan.outputs.python_version
+ working-directory: packages/simplex-chat-python
+ run: |
+ python -m pip install build -e ".[test]"
+ python -m pytest -q
+ python -m build
+
+ - name: Publish simplex-chat (PyPI)
+ if: steps.plan.outputs.python_version
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ packages-dir: packages/simplex-chat-python/dist
+ repository-url: ${{ vars.PYPI_UPLOAD_URL || 'https://upload.pypi.org/legacy/' }}
+ password: ${{ secrets.PYPI_API_TOKEN }}
+
+ - name: Report the published PyPI version
+ id: python
+ if: steps.plan.outputs.python_version
+ env:
+ VERSION: ${{ steps.plan.outputs.python_version }}
+ run: echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+
+ - name: Build and test @simplex-chat/mcp
+ if: steps.plan.outputs.mcp_version
+ working-directory: packages/simplex-chat-mcp
+ run: |
+ npm ci --no-audit --no-fund
+ npx tsc
+ npx tsc -p test/tsconfig.json --noEmit
+ npm test
+
+ - name: Publish @simplex-chat/mcp
+ id: mcp
+ if: steps.plan.outputs.mcp_version
+ working-directory: packages/simplex-chat-mcp
+ env:
+ VERSION: ${{ steps.plan.outputs.mcp_version }}
+ DIST_TAG: ${{ steps.plan.outputs.mcp_dist_tag }}
+ run: |
+ npm publish --provenance --access public --tag "$DIST_TAG"
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+
+ record:
+ needs: publish
+ if: ${{ !cancelled() && (needs.publish.outputs.types || needs.publish.outputs.nodejs || needs.publish.outputs.mcp || needs.publish.outputs.python) }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v6
+
+ - name: Record published versions
+ env:
+ GH_TOKEN: ${{ secrets.NODEJS_REPO_TOKEN }}
+ LIBS_REPOSITORY: ${{ github.repository }}-libs
+ TYPES: ${{ needs.publish.outputs.types }}
+ NODEJS: ${{ needs.publish.outputs.nodejs }}
+ MCP: ${{ needs.publish.outputs.mcp }}
+ PYTHON: ${{ needs.publish.outputs.python }}
+ run: |
+ python3 scripts/ci/packages_release.py record --commit "$GITHUB_SHA" \
+ --types "$TYPES" --nodejs "$NODEJS" --mcp "$MCP" --python "$PYTHON"
diff --git a/.github/workflows/desktop-linux.yml b/.github/workflows/desktop-linux.yml
new file mode 100644
index 0000000000..21c51967ad
--- /dev/null
+++ b/.github/workflows/desktop-linux.yml
@@ -0,0 +1,489 @@
+name: desktop-linux
+
+on:
+ workflow_dispatch:
+ inputs:
+ claude:
+ description: Also run the Claude job, which spends the Claude subscription's usage limits
+ type: boolean
+ default: false
+ backend:
+ description: Also start the test backend
+ type: boolean
+ default: false
+ release:
+ description: Also test the latest released app, to tell a branch's failure from the runner's
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: desktop-linux-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ GHC_VER: 9.6.3
+ CABAL_VER: 3.10.2.0
+ JAVA_VER: 17
+ CORE_PKG: desktop-core-linux-x86_64.tar.gz
+ BACKEND_PKG: desktop-linux-backend.tar.gz
+
+jobs:
+ plan:
+ name: choose jobs, find earlier builds
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ outputs:
+ run-claude: ${{ steps.jobs.outputs.claude }}
+ run-backend: ${{ steps.jobs.outputs.backend }}
+ run-release: ${{ steps.jobs.outputs.release }}
+ claude-backend: ${{ steps.scope.outputs.backend }}
+ core: ${{ steps.names.outputs.core }}
+ core-run: ${{ steps.core.outputs.run-id }}
+ backend: ${{ steps.names.outputs.backend }}
+ backend-run: ${{ steps.backend.outputs.run-id }}
+ steps:
+ - name: Choose jobs
+ id: jobs
+ env:
+ CLAUDE: ${{ inputs.claude }}
+ BACKEND: ${{ inputs.backend }}
+ RELEASE: ${{ inputs.release }}
+ run: |
+ echo "claude=$CLAUDE" | tee -a "$GITHUB_OUTPUT"
+ echo "backend=$BACKEND" | tee -a "$GITHUB_OUTPUT"
+ echo "release=$RELEASE" | tee -a "$GITHUB_OUTPUT"
+
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Claude scope
+ id: scope
+ if: steps.jobs.outputs.claude == 'true'
+ env:
+ BACKEND: ${{ steps.jobs.outputs.backend }}
+ run: |
+ backend=$(sed -n 's/^backend: *//p' scripts/ci/desktop-linux/claude-scope)
+ case "$backend" in
+ yes | no) echo "backend=$backend" | tee -a "$GITHUB_OUTPUT" ;;
+ *)
+ echo "::error::claude-scope must say backend: yes or backend: no"
+ exit 1
+ ;;
+ esac
+ if [ "$backend" = yes ] && [ "$BACKEND" != true ]; then
+ echo "::error::claude-scope says the Claude session uses the test backend: ask for it too"
+ exit 1
+ fi
+
+ # artifacts are named after the sources they are built from, so a run uses one that an earlier run uploaded
+ - name: Artifact names
+ id: names
+ run: |
+ echo "core=desktop-linux-core-${{ hashFiles('src/**', 'cabal.project', 'simplex-chat.cabal', 'PRIVACY.md', 'scripts/desktop/build-lib-linux.sh', 'scripts/ci/desktop-linux/build-core.sh') }}" >> "$GITHUB_OUTPUT"
+ echo "backend=desktop-linux-backend-${{ hashFiles('src/**', 'apps/simplex-chat/**', 'apps/simplex-directory-service/Main.hs', 'apps/simplex-directory-service/src/**', 'cabal.project', 'simplex-chat.cabal', 'scripts/ci/desktop-linux/build-backend.sh') }}" >> "$GITHUB_OUTPUT"
+
+ - name: Find core library
+ id: core
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/desktop-linux/earlier-run.sh "${{ steps.names.outputs.core }}"
+
+ - name: Find backend
+ id: backend
+ if: steps.jobs.outputs.backend == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/desktop-linux/earlier-run.sh "${{ steps.names.outputs.backend }}"
+
+ backend:
+ name: test backend for the app
+ needs: plan
+ if: needs.plan.outputs.run-backend == 'true' && needs.plan.outputs.backend-run == ''
+ runs-on: ubuntu-24.04
+ timeout-minutes: 150
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+
+ - name: Setup Haskell
+ uses: simplex-chat/setup-haskell-action@v2
+ with:
+ ghc-version: ${{ env.GHC_VER }}
+ cabal-version: ${{ env.CABAL_VER }}
+
+ - name: Install libraries
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libffi-dev libgmp-dev libnuma-dev libssl-dev zlib1g-dev
+
+ - name: Build backend
+ run: scripts/ci/desktop-linux/build-backend.sh ~/backend/${{ env.BACKEND_PKG }}
+
+ - name: Upload backend
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend/${{ env.BACKEND_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ core:
+ name: core library for Linux
+ needs: plan
+ if: needs.plan.outputs.core-run == ''
+ runs-on: ubuntu-24.04
+ timeout-minutes: 150
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+
+ - name: Setup Haskell
+ uses: simplex-chat/setup-haskell-action@v2
+ with:
+ ghc-version: ${{ env.GHC_VER }}
+ cabal-version: ${{ env.CABAL_VER }}
+
+ - name: Install libraries
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libffi-dev libgmp-dev libnuma-dev libssl-dev zlib1g-dev patchelf
+
+ - name: Build core library
+ run: scripts/ci/desktop-linux/build-core.sh ~/core/${{ env.CORE_PKG }}
+
+ - name: Upload core library
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/core/${{ env.CORE_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ app:
+ name: desktop app under Xvfb
+ needs: [plan, core, backend]
+ # core and backend are skipped when an earlier run built them, and backend also when the run doesn't start it
+ if: ${{ !cancelled() && !failure() && needs.plan.result == 'success' && needs.core.result != 'cancelled' && needs.backend.result != 'cancelled' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 60
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ submodules: recursive
+
+ - name: Show runner
+ run: |
+ lsb_release -ds
+ nproc
+ free -h
+ df -h /
+ echo "ANDROID_HOME=$ANDROID_HOME"
+ ls "$ANDROID_HOME/platforms" "$ANDROID_HOME/build-tools" || true
+
+ - name: Install tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y xvfb xdotool openbox imagemagick tesseract-ocr sqlite3 fonts-dejavu-core
+ dpkg-query -W xvfb xdotool openbox imagemagick tesseract-ocr sqlite3 fonts-dejavu-core
+
+ - name: Download core library
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/core
+ run-id: ${{ needs.plan.outputs.core-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Install core library
+ id: core
+ run: scripts/ci/desktop-linux/install-core.sh ~/core/${{ env.CORE_PKG }}
+
+ - name: Download backend
+ if: needs.plan.outputs.run-backend == 'true'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend
+ run-id: ${{ needs.plan.outputs.backend-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ id: backend
+ if: needs.plan.outputs.run-backend == 'true'
+ timeout-minutes: 30
+ run: scripts/ci/desktop-linux/backend.sh start ~/backend/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ # the app and its tests are still built when the backend fails
+ - name: Setup Java
+ if: ${{ !cancelled() && steps.core.outcome == 'success' }}
+ uses: actions/setup-java@v5
+ with:
+ distribution: corretto
+ java-version: ${{ env.JAVA_VER }}
+
+ # the Kotlin compiler daemon otherwise gets gradle.properties' 2 GB, which compiling :common runs out of
+ - name: Build app
+ id: build
+ if: ${{ !cancelled() && steps.core.outcome == 'success' }}
+ working-directory: apps/multiplatform
+ run: |
+ ./gradlew --no-daemon --console=plain -Psimplex.assets.dir=../../assets -Pkotlin.daemon.jvmargs=-Xmx4g :desktop:createDistributable
+ app=release/main/app/simplex
+ ls -la "$app/bin" "$app/lib/app/resources"
+ du -sh "$app"
+ LD_LIBRARY_PATH="$app/lib/app/resources" ldd "$app/lib/app/resources/libapp-lib.so"
+
+ # a tarball keeps the app's file modes, which an artifact drops
+ - name: Pack app
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ run: tar -czf "$RUNNER_TEMP/desktop-app.tar.gz" -C apps/multiplatform/release/main/app simplex
+
+ - name: Upload app
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-app
+ path: ${{ runner.temp }}/desktop-app.tar.gz
+ compression-level: 0
+ retention-days: 14
+ if-no-files-found: error
+
+ - name: Run desktop tests
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ working-directory: apps/multiplatform
+ env:
+ SNAPSHOT_DIR: ${{ runner.temp }}/snapshots
+ run: ./gradlew --no-daemon --console=plain -Psimplex.assets.dir=../../assets -Pkotlin.daemon.jvmargs=-Xmx4g :common:desktopTest
+
+ - name: Report desktop tests
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ run: scripts/ci/desktop-linux/test-summary.py apps/multiplatform/common/build/test-results/desktopTest
+
+ - name: Compare snapshots
+ if: ${{ !cancelled() && steps.build.outcome == 'success' }}
+ run: python3 scripts/ci/snapshots-compare.py apps/multiplatform/common/src/desktopTest/snapshots "$RUNNER_TEMP/snapshots" "$RUNNER_TEMP/snapshots-diff"
+
+ - name: Run smoke test
+ if: ${{ !cancelled() && steps.build.outcome == 'success' && steps.backend.outcome != 'failure' }}
+ env:
+ BACKEND: ${{ steps.backend.outcome }}
+ run: |
+ if [ "$BACKEND" = success ]; then
+ export NAMES_SERVER=$(cat "$RUNNER_TEMP/backend/names-server")
+ cases=backend
+ fi
+ scripts/ci/desktop-linux/smoke-test.sh apps/multiplatform/release/main/app/simplex "$RUNNER_TEMP/smoke-test" ${cases:-}
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload smoke test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-smoke-test
+ path: ${{ runner.temp }}/smoke-test
+ retention-days: 3
+ if-no-files-found: warn
+
+ - name: Upload desktop test report
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-test-report
+ path: |
+ apps/multiplatform/common/build/reports/tests/desktopTest
+ apps/multiplatform/common/build/test-results/desktopTest
+ retention-days: 3
+ if-no-files-found: warn
+
+ - name: Upload snapshots
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-snapshots
+ path: |
+ ${{ runner.temp }}/snapshots
+ ${{ runner.temp }}/snapshots-diff
+ retention-days: 3
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-backend-logs
+ path: ${{ runner.temp }}/backend/*.log
+ retention-days: 3
+ if-no-files-found: warn
+
+ # Claude Code repeats the smoke test with the ui helper. Each run spends the Claude subscription's usage
+ # limits, so it runs only when asked for. The app-sim-claude environment's branch rule decides which branches
+ # may use the token.
+ claude:
+ name: Claude tests the desktop app
+ needs: [plan, app]
+ if: ${{ !cancelled() && needs.plan.outputs.run-claude == 'true' && needs.app.result == 'success' }}
+ runs-on: ubuntu-24.04
+ timeout-minutes: 120
+ environment:
+ name: app-sim-claude
+ deployment: false
+ concurrency:
+ group: desktop-linux-claude-${{ github.ref }}
+ cancel-in-progress: true
+ env:
+ # the same in both app workflows
+ CLAUDE_CODE_VERSION: 2.1.300
+ CLAUDE_MODEL: claude-haiku-5-5
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ persist-credentials: false
+
+ - name: Install tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y xvfb xdotool openbox imagemagick tesseract-ocr sqlite3 fonts-dejavu-core
+ dpkg-query -W xvfb xdotool openbox imagemagick tesseract-ocr sqlite3 fonts-dejavu-core
+
+ - name: Download app
+ uses: actions/download-artifact@v8
+ with:
+ name: desktop-app
+ path: ${{ runner.temp }}
+
+ - name: Unpack app
+ run: |
+ mkdir -p "$RUNNER_TEMP/app"
+ tar -xzf "$RUNNER_TEMP/desktop-app.tar.gz" -C "$RUNNER_TEMP/app"
+
+ - name: Download backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/backend
+ run-id: ${{ needs.plan.outputs.backend-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ id: backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ timeout-minutes: 30
+ run: scripts/ci/desktop-linux/backend.sh start ~/backend/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ # ui goes on every shell's PATH, where Claude's Bash tool finds it whatever environment it builds
+ - name: Install Claude Code and the ui command
+ run: |
+ npm install --prefix "$RUNNER_TEMP/claude-code" "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
+ echo "$RUNNER_TEMP/claude-code/node_modules/.bin" >> "$GITHUB_PATH"
+ printf '#!/bin/sh\nexec %s/scripts/ci/desktop-linux/ui "$@"\n' "$PWD" | sudo tee /usr/local/bin/ui
+ sudo chmod +x /usr/local/bin/ui
+
+ - name: Start the app
+ run: scripts/ci/desktop-linux/smoke-test.sh "$RUNNER_TEMP/app/simplex" "$RUNNER_TEMP/claude-test/screens" start
+
+ - name: Add test images
+ run: |
+ mkdir -p "$RUNNER_TEMP/claude-test/images"
+ cp tests/fixtures/test.jpg "$RUNNER_TEMP/claude-test/images/test-card.jpg"
+ cp tests/fixtures/logo-large-rgba.png "$RUNNER_TEMP/claude-test/images/simplex-logo.png"
+
+ # Claude's Bash is limited to single ui commands by the guard hook in claude-test.sh. Claude Code's credential
+ # scrub stays off: on Linux it forces its whole Bash sandbox (bubblewrap, socat), which ui isn't set up for.
+ - name: Run Claude
+ id: claude
+ env:
+ CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: 1
+ run: scripts/ci/desktop-linux/claude-test.sh "$RUNNER_TEMP/claude-test" "$RUNNER_TEMP/claude-transcript.jsonl"
+
+ - name: Report Claude usage
+ if: ${{ !cancelled() && steps.claude.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/claude-usage.py "$RUNNER_TEMP/claude-transcript.jsonl" "$RUNNER_TEMP/claude-usage.json"
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ run: scripts/ci/desktop-linux/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload Claude test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-claude-test
+ path: |
+ ${{ runner.temp }}/claude-test
+ ${{ runner.temp }}/claude-transcript.jsonl
+ ${{ runner.temp }}/claude-transcript.jsonl.stderr
+ ${{ runner.temp }}/claude-transcript.jsonl.guard.log
+ ${{ runner.temp }}/claude-usage.json
+ retention-days: 7
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-claude-backend-logs
+ path: ${{ runner.temp }}/backend/*.log
+ retention-days: 3
+ if-no-files-found: warn
+
+ # the latest release's onboarding, to tell a branch's own failure from the runner's
+ release:
+ name: released app under Xvfb
+ needs: plan
+ if: needs.plan.outputs.run-release == 'true'
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 0
+ filter: tree:0
+
+ - name: Download released app
+ run: scripts/ci/desktop-linux/release-app.sh "$RUNNER_TEMP/release"
+
+ - name: Install UI tools
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y xvfb xdotool openbox imagemagick tesseract-ocr
+ dpkg-query -W xvfb xdotool openbox imagemagick tesseract-ocr
+
+ - name: Run smoke test
+ run: scripts/ci/desktop-linux/smoke-test.sh "$RUNNER_TEMP/release/app/opt/simplex" "$RUNNER_TEMP/smoke-test" onboarding
+
+ - name: Upload smoke test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: desktop-release-smoke-test
+ path: ${{ runner.temp }}/smoke-test
+ retention-days: 3
+ if-no-files-found: warn
diff --git a/.github/workflows/ios-sim.yml b/.github/workflows/ios-sim.yml
new file mode 100644
index 0000000000..4ddfabc6e1
--- /dev/null
+++ b/.github/workflows/ios-sim.yml
@@ -0,0 +1,359 @@
+name: ios-sim
+
+on:
+ workflow_dispatch:
+ inputs:
+ claude:
+ description: Also run the Claude session
+ type: boolean
+ default: false
+ backend:
+ description: Start the test backend
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+ actions: read
+
+concurrency:
+ group: ios-sim-${{ github.ref }}
+ cancel-in-progress: true
+
+env:
+ GHC_VER: 9.6.3
+ CABAL_VER: 3.10.2.0
+ CORE_PKG: pkg-ios-aarch64-swift-json.zip
+ BACKEND_PKG: ios-sim-backend.zip
+ HOMEBREW_NO_AUTO_UPDATE: 1
+ HOMEBREW_NO_INSTALL_CLEANUP: 1
+ # newer images add Command Line Tools whose macOS SDK the default Xcode's linker cannot read
+ DEVELOPER_DIR: /Applications/Xcode.app/Contents/Developer
+
+jobs:
+ plan:
+ name: choose jobs, find earlier builds
+ runs-on: ubuntu-24.04
+ timeout-minutes: 10
+ outputs:
+ run-claude: ${{ steps.jobs.outputs.claude }}
+ run-backend: ${{ steps.jobs.outputs.backend }}
+ claude-backend: ${{ steps.scope.outputs.backend }}
+ core: ${{ steps.names.outputs.core }}
+ core-run: ${{ steps.core.outputs.run-id }}
+ backend: ${{ steps.names.outputs.backend }}
+ backend-run: ${{ steps.backend.outputs.run-id }}
+ steps:
+ - name: Choose jobs
+ id: jobs
+ env:
+ CLAUDE: ${{ inputs.claude }}
+ BACKEND: ${{ inputs.backend }}
+ run: |
+ echo "claude=$CLAUDE" | tee -a "$GITHUB_OUTPUT"
+ echo "backend=$BACKEND" | tee -a "$GITHUB_OUTPUT"
+
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Claude scope
+ id: scope
+ if: steps.jobs.outputs.claude == 'true'
+ env:
+ BACKEND: ${{ steps.jobs.outputs.backend }}
+ run: |
+ backend=$(sed -n 's/^backend: *//p' scripts/ci/ios-sim/claude-scope)
+ case "$backend" in
+ yes | no) echo "backend=$backend" | tee -a "$GITHUB_OUTPUT" ;;
+ *)
+ echo "::error::claude-scope must say backend: yes or backend: no"
+ exit 1
+ ;;
+ esac
+ if [ "$backend" = yes ] && [ "$BACKEND" != true ]; then
+ echo "::error::claude-scope says the Claude sessions use the test backend: ask for it too"
+ exit 1
+ fi
+
+ # artifacts are named after the sources they are built from, so a run uses one that an earlier run uploaded
+ - name: Artifact names
+ id: names
+ run: |
+ echo "core=ios-sim-core-${{ hashFiles('src/**', 'cabal.project', 'simplex-chat.cabal', 'scripts/ci/ios-sim/build-core.sh') }}" >> "$GITHUB_OUTPUT"
+ echo "backend=ios-sim-backend-${{ hashFiles('src/**', 'apps/simplex-chat/**', 'apps/simplex-directory-service/Main.hs', 'apps/simplex-directory-service/src/**', 'cabal.project', 'simplex-chat.cabal', 'scripts/ci/ios-sim/build-backend.sh') }}" >> "$GITHUB_OUTPUT"
+
+ - name: Find core library
+ id: core
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/ios-sim/earlier-run.sh "${{ steps.names.outputs.core }}"
+
+ - name: Find backend
+ id: backend
+ if: steps.jobs.outputs.backend == 'true'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: scripts/ci/ios-sim/earlier-run.sh "${{ steps.names.outputs.backend }}"
+
+ app:
+ name: app in the iOS simulator
+ needs: plan
+ runs-on: macos-26
+ timeout-minutes: 360
+ env:
+ START_BACKEND: ${{ needs.plan.outputs.run-backend }}
+ BUILD_CORE: ${{ needs.plan.outputs.core-run == '' }}
+ BUILD_BACKEND: ${{ needs.plan.outputs.run-backend == 'true' && needs.plan.outputs.backend-run == '' }}
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Show runner
+ run: |
+ sw_vers
+ sysctl -n hw.ncpu hw.memsize
+ df -h /
+ xcodebuild -version
+ xcrun --show-sdk-path
+ ls /Library/Developer/CommandLineTools/SDKs || true
+ xcrun simctl list runtimes
+
+ - name: Use the macOS 26 SDK
+ run: scripts/ci/ios-sim/use-macos26-sdk.sh
+
+ - name: Setup Haskell
+ if: env.BUILD_CORE == 'true' || env.BUILD_BACKEND == 'true'
+ uses: simplex-chat/setup-haskell-action@v2
+ with:
+ ghc-version: ${{ env.GHC_VER }}
+ cabal-version: ${{ env.CABAL_VER }}
+
+ - name: Install libraries
+ if: env.BUILD_CORE == 'true'
+ run: brew install openssl@3 libffi gmp
+
+ - name: Build core library
+ if: env.BUILD_CORE == 'true'
+ run: scripts/ci/ios-sim/build-core.sh ~/Downloads/${{ env.CORE_PKG }}
+
+ - name: Upload core library
+ if: env.BUILD_CORE == 'true'
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/Downloads/${{ env.CORE_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ - name: Download core library
+ if: env.BUILD_CORE != 'true'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.core }}
+ path: ~/Downloads
+ run-id: ${{ needs.plan.outputs.core-run }}
+ github-token: ${{ github.token }}
+
+ - name: Prepare libraries
+ run: |
+ scripts/ci/ios-sim/prepare-libs.sh
+ scripts/ios/update-pbxproj.sh
+
+ - name: Build backend
+ if: env.BUILD_BACKEND == 'true'
+ run: scripts/ci/ios-sim/build-backend.sh ~/Downloads/${{ env.BACKEND_PKG }}
+
+ - name: Upload backend
+ if: env.BUILD_BACKEND == 'true'
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/Downloads/${{ env.BACKEND_PKG }}
+ compression-level: 0
+ retention-days: 30
+ if-no-files-found: error
+
+ - name: Download backend
+ if: env.START_BACKEND == 'true' && env.BUILD_BACKEND != 'true'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/Downloads
+ run-id: ${{ needs.plan.outputs.backend-run }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ if: env.START_BACKEND == 'true'
+ timeout-minutes: 30
+ run: scripts/ci/ios-sim/backend.sh start ~/Downloads/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ - name: Build app
+ run: |
+ xcodebuild build -quiet \
+ -project apps/ios/SimpleX.xcodeproj \
+ -scheme "SimpleX (iOS)" \
+ -configuration Debug \
+ -destination 'generic/platform=iOS Simulator' \
+ -derivedDataPath "$RUNNER_TEMP/DerivedData" \
+ -onlyUsePackageVersionsFromResolvedFile \
+ -skipPackagePluginValidation \
+ -skipMacroValidation \
+ ARCHS=arm64 \
+ CODE_SIGN_STYLE=Manual \
+ CODE_SIGN_IDENTITY=- \
+ DEVELOPMENT_TEAM= \
+ PROVISIONING_PROFILE_SPECIFIER=
+
+ # a tarball keeps the app's file modes, which an artifact drops
+ - name: Pack app
+ run: tar -czf "$RUNNER_TEMP/SimpleX.app.tar.gz" -C "$RUNNER_TEMP/DerivedData/Build/Products/Debug-iphonesimulator" SimpleX.app
+
+ - name: Upload app
+ uses: actions/upload-artifact@v7
+ with:
+ name: ios-sim-app
+ path: ${{ runner.temp }}/SimpleX.app.tar.gz
+ compression-level: 0
+ retention-days: 14
+ if-no-files-found: error
+
+ - name: Install AXe
+ run: scripts/ci/ios-sim/install-axe.sh
+
+ - name: Run smoke test
+ run: scripts/ci/ios-sim/smoke-test.sh "$RUNNER_TEMP/DerivedData/Build/Products/Debug-iphonesimulator/SimpleX.app" "$RUNNER_TEMP/smoke-test" images
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && env.START_BACKEND == 'true' }}
+ run: scripts/ci/ios-sim/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload smoke test results
+ if: ${{ !cancelled() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: ios-sim-smoke-test
+ path: ${{ runner.temp }}/smoke-test
+ retention-days: 3
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && env.START_BACKEND == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: ios-sim-backend-logs
+ path: |
+ ${{ runner.temp }}/backend/*.log
+ ${{ runner.temp }}/backend/seed.md
+ retention-days: 3
+ if-no-files-found: warn
+
+ # The app-sim-claude environment's branch rule decides which branches may use the token.
+ claude:
+ name: Claude tests the iOS app
+ needs: [plan, app]
+ if: ${{ !cancelled() && needs.plan.outputs.run-claude == 'true' && needs.app.result == 'success' }}
+ runs-on: macos-26
+ timeout-minutes: 330
+ environment:
+ name: app-sim-claude
+ deployment: false
+ concurrency:
+ group: ios-sim-claude-${{ github.ref }}
+ cancel-in-progress: true
+ env:
+ # the same in both app workflows
+ CLAUDE_CODE_VERSION: 2.1.300
+ steps:
+ # the job holds the Claude token, so the checkout's GitHub token is not left in .git/config
+ - name: Checkout code
+ uses: actions/checkout@v6
+ with:
+ persist-credentials: false
+
+ - name: Show runner
+ run: |
+ sw_vers
+ xcodebuild -version
+ xcrun simctl list runtimes
+
+ - name: Use the macOS 26 SDK
+ run: scripts/ci/ios-sim/use-macos26-sdk.sh
+
+ - name: Download app
+ uses: actions/download-artifact@v8
+ with:
+ name: ios-sim-app
+ path: ${{ runner.temp }}
+
+ - name: Unpack app
+ run: tar -xzf "$RUNNER_TEMP/SimpleX.app.tar.gz" -C "$RUNNER_TEMP"
+
+ - name: Download backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ uses: actions/download-artifact@v8
+ with:
+ name: ${{ needs.plan.outputs.backend }}
+ path: ~/Downloads
+ run-id: ${{ needs.plan.outputs.backend-run || github.run_id }}
+ github-token: ${{ github.token }}
+
+ - name: Start test backend
+ id: backend
+ if: needs.plan.outputs.claude-backend == 'yes'
+ timeout-minutes: 30
+ run: scripts/ci/ios-sim/backend.sh start ~/Downloads/${{ env.BACKEND_PKG }} "$RUNNER_TEMP/backend"
+
+ - name: Install AXe
+ run: scripts/ci/ios-sim/install-axe.sh
+
+ - name: Run smoke test
+ run: scripts/ci/ios-sim/smoke-test.sh "$RUNNER_TEMP/SimpleX.app" "$RUNNER_TEMP/claude-test/smoke-test"
+
+ - name: Add test images
+ run: |
+ images=(tests/fixtures/test.jpg tests/fixtures/logo-large-rgba.png)
+ if sips -r 90 -s format heic tests/fixtures/test.jpg --out "$RUNNER_TEMP/test-card-portrait.heic"; then
+ images+=("$RUNNER_TEMP/test-card-portrait.heic")
+ fi
+ xcrun simctl addmedia "$SIM_UDID" "${images[@]}"
+
+ - name: Install Claude Code
+ run: |
+ npm install -g "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
+ claude --version
+
+ - name: Run the device test plan with Claude
+ timeout-minutes: 240
+ env:
+ CLAUDE_CODE_OAUTH_TOKEN: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
+ BACKEND_DIR: ${{ steps.backend.outcome == 'success' && format('{0}/backend', runner.temp) || '' }}
+ run: scripts/ci/ios-sim/claude-test.sh "$RUNNER_TEMP/claude-test"
+
+ - name: Report Claude usage
+ if: ${{ always() }}
+ run: scripts/ci/ios-sim/claude-usage.sh "$RUNNER_TEMP/claude-test"
+
+ - name: Stop test backend
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ run: scripts/ci/ios-sim/backend.sh stop "$RUNNER_TEMP/backend"
+
+ - name: Upload Claude test results
+ if: ${{ always() }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: ios-sim-claude-test
+ path: ${{ runner.temp }}/claude-test
+ retention-days: 14
+ if-no-files-found: warn
+
+ - name: Upload backend logs
+ if: ${{ !cancelled() && steps.backend.outcome != 'skipped' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: ios-sim-claude-backend-logs
+ path: |
+ ${{ runner.temp }}/backend/*.log
+ ${{ runner.temp }}/backend/seed.md
+ retention-days: 3
+ if-no-files-found: warn
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
new file mode 100644
index 0000000000..12fc5f5862
--- /dev/null
+++ b/.github/workflows/packages.yml
@@ -0,0 +1,72 @@
+name: packages
+
+on:
+ pull_request:
+ paths:
+ - "packages/simplex-chat-nodejs/**"
+ - "packages/simplex-chat-client/types/typescript/**"
+ - "packages/simplex-chat-python/**"
+ - ".github/workflows/packages.yml"
+ types: [opened, synchronize, reopened, ready_for_review]
+
+concurrency:
+ # build.yml and this workflow both run for a pull request that changes the core and the packages
+ group: ${{ github.workflow }}-packages-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+env:
+ NPM_SCOPE: ${{ vars.NPM_SCOPE }}
+ PYPI_PROJECT: ${{ vars.PYPI_PROJECT }}
+ PYPI_URL: ${{ vars.PYPI_URL }}
+
+jobs:
+ addon:
+ if: github.event.pull_request.draft == false
+ runs-on: ubuntu-latest
+ outputs:
+ platforms: ${{ steps.plan.outputs.platforms }}
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v6
+ with:
+ fetch-depth: 2
+
+ - name: Build plan
+ id: plan
+ run: python3 scripts/ci/packages_release.py build-plan --base HEAD^1 >> "$GITHUB_OUTPUT"
+
+ build:
+ name: "build ${{ matrix.platform }}"
+ needs: addon
+ if: needs.addon.outputs.platforms != '[]'
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
+ strategy:
+ fail-fast: false
+ matrix:
+ include: ${{ fromJSON(needs.addon.outputs.platforms) }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v6
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v7
+ with:
+ node-version: 22
+
+ - name: Setup Python
+ uses: actions/setup-python@v7
+ with:
+ python-version: "3.12"
+
+ - name: Build simplex-chat (npm) and add-on
+ run: scripts/ci/package-tests.sh build ${{ matrix.platform }}
+
+ - name: Test simplex-chat (npm and PyPI)
+ run: scripts/ci/package-tests.sh test
diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml
index 5fbe8293bc..7628eb1f9a 100644
--- a/.github/workflows/web.yml
+++ b/.github/workflows/web.yml
@@ -33,6 +33,7 @@ jobs:
./website/web.sh
- name: Deploy
+ if: github.repository == 'simplex-chat/simplex-chat'
uses: simplex-chat/actions-gh-pages@v3
with:
publish_dir: ./website/_site
diff --git a/.gitignore b/.gitignore
index 035d24c6cd..1bb18ef356 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,6 +56,7 @@ website/src/images/
website/src/js/lottie.min.js
website/src/js/ethers.*
website/src/js/directory.js
+website/src/js/page.js
website/src/js/channel-preview.js
website/src/js/simplex-lib.js
website/src/file-assets/
@@ -86,4 +87,5 @@ website/.cache
website/test/stubs-layout-cache/_includes/*.js
apps/android/app/release
apps/multiplatform/.kotlin/sessions
-
+# anywhere in the tree: this file holds a real BTCPay api_key and webhook_secret
+badge_service.ini
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000000..2c3cceced7
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,4 @@
+@docs/CONTRIBUTING.md
+@docs/contributing/PROJECT.md
+@docs/contributing/CODE.md
+@scripts/ci/README.md
diff --git a/Dockerfile.build b/Dockerfile.build
index 89f8c25101..f18f608612 100644
--- a/Dockerfile.build
+++ b/Dockerfile.build
@@ -5,11 +5,17 @@ FROM ubuntu:${TAG}@${HASH} AS build
### Build stage
+# Ubuntu archive state that all apt packages are installed from; bump it to pick up package updates
+ARG UBUNTU_SNAPSHOT=20261021T000000Z
ARG GHC=9.6.3
ARG CABAL=3.10.2.0
-ARG JAVA_VER=17.0.17.10.1
-ARG JAVA_HASH_AMD64=e3e11daa5c22a45153bbeff1a0c21bf08631791e4e8d8ed14deba31c7cf9af1a
-ARG JAVA_HASH_ARM64=2b460859b681757b33a7591b6238ecaf51569d05d2684984e5f0a89c6514acbc
+ARG GHCUP_VER=0.2.6.2
+ARG GHCUP_HASH_AMD64=9ed5da5449b48043a0d17e767c05d2ef585e25a639bb934329496c6d2fad9cf8
+ARG GHCUP_HASH_ARM64=65a5f05120288ee4f1a81d28825374b6af317456a351a586adfce90c6dc29e3b
+ARG GHCUP_METADATA=https://raw.githubusercontent.com/haskell/ghcup-metadata/ff5a77f2ee34afd9c49b970a45abfb7dac01cb8a/ghcup-0.1.0.yaml
+ARG JAVA_VER=17.0.21.0.10
+ARG JAVA_HASH_AMD64=8e7577ddeb5b17a13c73a6fe80b592f6e70299cd19f54d06976986b0bc7ada87
+ARG JAVA_HASH_ARM64=c400e8ae70ee9565c23667bc3b4dd0fe5f7c403629ebb2cf9648c1d756b6b926
ENV TZ=Etc/UTC \
DEBIAN_FRONTEND=noninteractive
@@ -18,8 +24,15 @@ ARG USER_UID=1000
ARG USER_GID=1000
ARG USER_NAME=builder
+# The base image has no CA certificates, so they are fetched without TLS peer verification;
+# apt still verifies every index against the GPG-signed InRelease files.
+RUN sed -i -E "s#http://(archive|security|ports)\.ubuntu\.com/ubuntu(-ports)?/?#https://snapshot.ubuntu.com/ubuntu/${UBUNTU_SNAPSHOT}/#" \
+ $(grep -rlsE 'http://(archive|security|ports)\.ubuntu\.com' /etc/apt/sources.list /etc/apt/sources.list.d) && \
+ apt-get -o Acquire::https::Verify-Peer=false update --error-on=any && \
+ apt-get -o Acquire::https::Verify-Peer=false install -y ca-certificates
+
# Install curl, git and and simplex-chat dependencies
-RUN apt-get update && \
+RUN apt-get update --error-on=any && \
apt-get install -y curl \
libpq-dev \
git \
@@ -58,7 +71,7 @@ RUN apt-get update && \
# to fix this :(
RUN export JAVA_FILENAME='java-corretto.deb' \
JAVA_VER_MAJOR=$(printf "${JAVA_VER}" | awk -F. '{print $1}') \
- JAVA_VER_DEB=$(printf "${JAVA_VER}" | sed 's/\.1$/-1/') && \
+ JAVA_VER_DEB="${JAVA_VER}-1" && \
case "$(uname -m)" in \
x86_64) export JAVA_ARCH='amd64' JAVA_HASH="$JAVA_HASH_AMD64" ;; \
aarch64) export JAVA_ARCH='arm64' JAVA_HASH="$JAVA_HASH_ARM64" ;; \
@@ -83,35 +96,38 @@ RUN mkdir /nix /out && chown ${USER_NAME}:${USER_NAME} /nix /out
USER ${USER_NAME}
WORKDIR /home/${USER_NAME}
-# Specify bootstrap Haskell versions
-ENV BOOTSTRAP_HASKELL_GHC_VERSION=${GHC}
-ENV BOOTSTRAP_HASKELL_CABAL_VERSION=${CABAL}
-
-# Do not install Stack
-ENV BOOTSTRAP_HASKELL_INSTALL_NO_STACK=true
-ENV BOOTSTRAP_HASKELL_INSTALL_NO_STACK_HOOK=true
-
-# Install ghcup
-RUN curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | BOOTSTRAP_HASKELL_NONINTERACTIVE=1 sh
-
# Setup basic env variables (required)
ENV HOME="/home/${USER_NAME}" USER="${USER_NAME}"
# Adjust PATH
ENV PATH="$HOME/.cabal/bin:$HOME/.ghcup/bin:$PATH"
-# Set both as default
-RUN ghcup set ghc "${GHC}" && \
- ghcup set cabal "${CABAL}"
+# Install ghcup, GHC and cabal
+RUN case "$(uname -m)" in \
+ x86_64) export GHCUP_HASH="$GHCUP_HASH_AMD64" ;; \
+ aarch64) export GHCUP_HASH="$GHCUP_HASH_ARM64" ;; \
+ *) echo "unknown arch $(uname -m)" && exit 1 ;; \
+ esac && \
+ mkdir -p "$HOME/.ghcup/bin" && \
+ curl --proto '=https' --tlsv1.2 -sSf \
+ "https://downloads.haskell.org/~ghcup/${GHCUP_VER}/$(uname -m)-linux-ghcup-${GHCUP_VER}" \
+ -o "$HOME/.ghcup/bin/ghcup" && \
+ echo "${GHCUP_HASH} $HOME/.ghcup/bin/ghcup" | sha256sum -c - && \
+ chmod +x "$HOME/.ghcup/bin/ghcup" && \
+ ghcup config set url-source "${GHCUP_METADATA}" && \
+ ghcup install ghc "${GHC}" --set && \
+ ghcup install cabal "${CABAL}" --set
#=====================
# Install Android SDK
#=====================
ARG SDK_VERSION=13114758
+ARG SDK_HASH=7ec965280a073311c339e571cd5de778b9975026cfcbe79f2b1cdcb1e15317ee
ENV SDK_VERSION="$SDK_VERSION" \
ANDROID_HOME="$HOME"
RUN curl -L -o tools.zip "https://dl.google.com/android/repository/commandlinetools-linux-${SDK_VERSION}_latest.zip" && \
+ echo "${SDK_HASH} tools.zip" | sha256sum -c - && \
unzip tools.zip && rm tools.zip && \
mv cmdline-tools tools && mkdir "$ANDROID_HOME/cmdline-tools" && mv tools "$ANDROID_HOME/cmdline-tools/" && \
ln -s "$ANDROID_HOME/cmdline-tools/tools" "$ANDROID_HOME/cmdline-tools/latest"
@@ -128,7 +144,13 @@ ENV PATH="$PATH:$ANDROID_HOME/platform-tools:$ANDROID_HOME/build-tools"
# Android reproducibility scripts
RUN python3 -m venv "$HOME/.venv"
-RUN "$HOME/.venv/bin/pip" install apksigcopier repro-apk
+RUN printf '%s\n' \
+ 'apksigcopier==1.1.1 --hash=sha256:0834bb7d6f3607bb0994cf8cd2e26b8f0c9d481e13b75872e0fa9cec052e519b' \
+ 'repro-apk==0.3.0 --hash=sha256:09091a5e6d725d73ad418aa98ec72d0737452d3ce3803b56dd5c270b887fceb9' \
+ 'click==8.5.0 --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360' \
+ > /tmp/requirements.txt && \
+ "$HOME/.venv/bin/pip" install --require-hashes --only-binary=:all: -r /tmp/requirements.txt && \
+ rm /tmp/requirements.txt
ENV PATH="$HOME/.venv/bin:$PATH"
diff --git a/PRIVACY.md b/PRIVACY.md
index 5713f8e134..7d312cf5a6 100644
--- a/PRIVACY.md
+++ b/PRIVACY.md
@@ -15,7 +15,7 @@ permalink: /privacy/index.html
- [undelivered messages and files](#storage-of-messages-and-files-on-the-servers) stored on the servers.
- [how users connect](#connections-with-other-users) without any user profile identifiers.
- [iOS push notifications](#ios-push-notifications) privacy limitations.
-- [user support](#user-support), [SimpleX directory](#simplex-directory) and [any other data](#another-information-stored-on-the-servers) that may be stored on the servers.
+- [user support](#user-support), [SimpleX directory](#simplex-directory), [supporter badges](#supporter-badges) and [any other data](#another-information-stored-on-the-servers) that may be stored on the servers.
- [preset server operators](#preset-server-operators) and the [information they may share](#information-preset-server-operators-may-share).
- [source code license](#source-code-license) and [updates to this document](#updates).
@@ -87,7 +87,7 @@ The messages are irreversibly removed from the preset relay servers as soon as t
Other relay servers may use message logs that would result in longer storage of delivered messages, until the log file is rotated, which normally should happen within one month if servers use the same code as preset servers.
-The files are stored on file relay servers for the time configured in the relay servers you use (48 hours for preset file servers).
+The files are stored on file relay servers for the time configured in the relay servers you use (48 hours for preset file servers, and 7 or 21 days for files sent with a supporter or legend badge, respectively).
#### Connections with other users
@@ -149,6 +149,14 @@ Public addresses contain profile name, picture and other profile details. This d
The app includes support contact operated by SimpleX Chat Ltd. If you contact support, any personal data you share is kept only for the purposes of researching the issue and contacting you about your case. We recommend contacting support [via chat](https://smp6.simplex.im/a#lrdvu2d8A1GumSmoKb2krQmtKhWXq-tyGpHuM7aMwsw) when it is possible, and avoid sharing any personal information.
+#### Supporter badges
+
+A badge is a credential from the SimpleX Chat Ltd store service, kept on your device and presented as zero-knowledge proofs in chats, except incognito ones, and to your file servers. Only the badge type, the expiry date, rounded to a week, and the number of the signing key are disclosed. The store service's public keys are preset in the app; the service signs all badges of all users with one key and may periodically switch to the next one, so no user can be identified by the key. Nothing else in a proof can be linked to other proofs or to the purchase.
+
+The store service has no user accounts: purchases are identified by random keys or codes from your device. The app sends requests end-to-end encrypted and without your profile. The store service never receives your IP address with these requests, and with private routing (the default), its servers do not see it either. Stripe (card), App Store and Google Play process payments; cryptocurrency payments are accepted directly to SimpleX Chat Ltd's addresses.
+
+For tax purposes, the store service keeps for 6 years each order's keys, badge type, months, dates, credentials and payment: amount, currency, reference, code hash, cryptocurrency address or store transaction.
+
### Preset Server Operators
Preset server operators will not share the information or any metadata on their servers with each other, other than aggregate usage statistics.
@@ -204,7 +212,7 @@ Client applications must not include any code that could compromise the security
**Accessing the infrastructure**. For the efficiency of the network access, the client Software by default accesses all queues your app creates on any relay server within one user profile via the same network (TCP/IP) connection. At the cost of additional traffic this configuration can be changed to use different transport session for each connection. Relay servers do not collect information about which queues were created or accessed via the same connection, so the relay servers cannot establish which queues belong to the same user profile. Whoever might observe your network traffic would know which relay servers you use, and how much data you send, but not to whom it is sent - the data that leaves the servers is always different from the data they receive - there are no identifiers or ciphertext in common, even inside TLS encryption layer. Please refer to the [technical design document](https://github.com/simplex-chat/simplexmq/blob/master/protocol/overview-tjr.md) for more information about the privacy model and known security and privacy risks.
-**Privacy of user data**. Servers do not retain any data you transmit for any longer than necessary to deliver the messages between apps. Preset server operators collect aggregate statistics across all their servers, as supported by published code and can be enabled by any infrastructure operator, but not any statistics per-user, or per geographic location, or per IP address, or per transport session. SimpleX Chat Ltd does not have information about how many people use SimpleX Chat applications, it only knows an approximate number of app installations and the aggregate traffic through the preset servers. In any case, preset server operators do not and will not sell or in any way monetize user data. The future business model assumes charging for some optional Software features instead, in a transparent and fair way.
+**Privacy of user data**. Servers do not retain any data you transmit for any longer than necessary to deliver the messages between apps. Preset server operators collect aggregate statistics across all their servers, as supported by published code and can be enabled by any infrastructure operator, but not any statistics per-user, or per geographic location, or per IP address, or per transport session. SimpleX Chat Ltd does not have information about how many people use SimpleX Chat applications, it only knows an approximate number of app installations, the aggregate traffic through the preset servers and the number of issued supporter badges. In any case, preset server operators do not and will not sell or in any way monetize user data. The business model assumes charging for some optional Software features instead, such as supporter badges, in a transparent and fair way.
**Operating Infrastructure**. For the purpose of using SimpleX Chat Software, if you continue using preset servers, you agree that your end-to-end encrypted messages are transferred via the preset servers in any countries where preset server operators have or use facilities and service providers or partners. The information about geographic location and hosting providers of the preset messaging servers is available on server pages.
@@ -257,4 +265,4 @@ Client applications must not include any code that could compromise the security
**Ending these conditions**. You may end these Conditions with SimpleX Chat Ltd and preset server operators at any time by deleting the Applications from your devices and discontinuing use of the Infrastructure of SimpleX Chat Ltd and preset server operators. The provisions related to Licenses, Disclaimers, Limitation of Liability, Resolving dispute, Availability, Changes to the conditions, Enforcing the conditions, and Ending these conditions will survive termination of your relationship with SimpleX Chat Ltd and/or preset server operators.
-Updated April 18, 2026
+Updated November 1, 2026
diff --git a/README.md b/README.md
index f7c2ccd514..cb792e84f5 100644
--- a/README.md
+++ b/README.md
@@ -179,6 +179,7 @@ SimpleX Chat founder
- [Privacy and security: technical details and limitations](#privacy-and-security-technical-details-and-limitations)
- [For developers](#for-developers)
- [Develop a chat bot](#develop-a-chat-bot)
+- [Agents](#agents)
- [Roadmap](#roadmap)
- [Disclaimers, Security contact, License](#disclaimers)
@@ -220,6 +221,8 @@ You can use SimpleX with your own servers and still communicate with people usin
Recent and important updates:
+[Sep 19, 2026. SimpleX Supporter Badges — Send Larger Files That Stay Available Longer, Without Being Identified](./blog/20260919-simplex-supporter-badges.md)
+
[Aug 20, 2026. Equity Crowdfunding Launched - You Can Get a Stake in SimpleX Chat](./blog/20260819-simplex-chat-crowdfunding.md)
[Jul 22, 2026. SimpleX Public Names — a Name Nobody Can Take From You](./blog/20260722-simplex-public-names.md)
@@ -329,6 +332,18 @@ See [our new bot API reference](./bots/README.md). Most of it is automatically g
Also see [TypeScript SimpleX Chat client](./packages/simplex-chat-client/) and [JavaScript chat bot example](./packages/simplex-chat-client/typescript/examples/squaring-bot.js).
+## Agents
+
+- For AI assistants: [simplex.chat/llms.txt](https://simplex.chat/llms.txt), an index of the documentation in Markdown, and [SimpleX for AI agents and developers](https://simplex.chat/llms/agents.md).
+- Every page of simplex.chat is also available as Markdown: replace `.html` with `.md` ([simplex.chat/docs/simplex.md](https://simplex.chat/docs/simplex.md)), or add `.md` to the path ([simplex.chat/why.md](https://simplex.chat/why.md)).
+- Libraries: [Node.js](./packages/simplex-chat-nodejs/) ([npm](https://www.npmjs.com/package/simplex-chat)) and [Python](./packages/simplex-chat-python/) ([PyPI](https://pypi.org/project/simplex-chat/)).
+- [Bot API guide](./bots/README.md) and [API reference](./bots/api/README.md): commands, events and types.
+- Example bots: [support bot](./apps/simplex-support-bot/) and [calculator](./apps/simplex-calculator-bot/) in TypeScript, [support bot light](./apps/simplex-support-bot-light/) in Python, [directory service](./apps/simplex-directory-service/) and [broadcast bot](./apps/simplex-broadcast-bot/) in Haskell.
+- [Terminal client](./docs/CLI.md): installation, building from source and usage.
+- Servers: [SMP](./docs/SERVER.md), [XFTP](./docs/XFTP-SERVER.md) and [chat relay](./docs/CHAT-RELAY.md).
+- Protocols: [SimpleX network](https://github.com/simplex-chat/simplexmq/blob/stable/protocol/overview-tjr.md), [chat](./docs/protocol/simplex-chat.md), [channels](./docs/protocol/channels-overview.md) and [public names](./docs/protocol/names-overview.md).
+- For coding agents working in this repository: [project structure](./docs/contributing/PROJECT.md) and [coding and building](./docs/contributing/CODE.md).
+
## Roadmap
- ✅ Easy to deploy SimpleX server with in-memory message storage, without any dependencies.
diff --git a/apps/ios/BadgeTestProducts.storekit b/apps/ios/BadgeTestProducts.storekit
new file mode 100644
index 0000000000..f32c2c8dc3
--- /dev/null
+++ b/apps/ios/BadgeTestProducts.storekit
@@ -0,0 +1,230 @@
+{
+ "appPolicies" : {
+ "eula" : "",
+ "policies" : [
+ {
+ "locale" : "en_US",
+ "policyText" : "",
+ "policyURL" : ""
+ }
+ ]
+ },
+ "identifier" : "B4D6E1A0",
+ "nonRenewingSubscriptions" : [
+
+ ],
+ "products" : [
+ {
+ "displayPrice" : "7.00",
+ "familyShareable" : false,
+ "internalID" : "3010000001",
+ "localizations" : [
+ {
+ "description" : "Supporter badge for one month",
+ "displayName" : "SimpleX Supporter Badge",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "BADGE_SUPPORTER_01",
+ "referenceName" : "SimpleX Supporter Badge",
+ "type" : "Consumable"
+ },
+ {
+ "displayPrice" : "70.00",
+ "familyShareable" : false,
+ "internalID" : "3010000002",
+ "localizations" : [
+ {
+ "description" : "Legend badge for one month",
+ "displayName" : "SimpleX Legend Badge",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "BADGE_LEGEND_01",
+ "referenceName" : "SimpleX Legend Badge",
+ "type" : "Consumable"
+ }
+ ],
+ "settings" : {
+ "_applicationInternalID" : "",
+ "_developerTeamID" : "",
+ "_failTransactionsEnabled" : false,
+ "_lastSynchronizedDate" : 0,
+ "_locale" : "en_US",
+ "_storefront" : "USA",
+ "_storeKitErrors" : [
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Load Products"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Purchase"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Verification"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "App Store Sync"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Subscription Status"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "App Transaction"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Manage Subscriptions Sheet"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Refund Request Sheet"
+ },
+ {
+ "current" : null,
+ "enabled" : false,
+ "name" : "Offer Code Redeem Sheet"
+ }
+ ]
+ },
+ "subscriptionGroups" : [
+ {
+ "id" : "3020000001",
+ "localizations" : [
+
+ ],
+ "name" : "SimpleX Badge Subscription",
+ "subscriptions" : [
+ {
+ "adHocOffers" : [
+
+ ],
+ "codeOffers" : [
+
+ ],
+ "displayPrice" : "7.00",
+ "familyShareable" : false,
+ "groupNumber" : 2,
+ "internalID" : "3020000011",
+ "introductoryOffer" : null,
+ "localizations" : [
+ {
+ "description" : "Supporter badge, renews monthly",
+ "displayName" : "SimpleX Supporter Badge (Month)",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "SUBSCR_BADGE_SUPPORTER_MONTH_01",
+ "recurringSubscriptionPeriod" : "P1M",
+ "referenceName" : "SimpleX Supporter Badge (Month)",
+ "subscriptionGroupID" : "3020000001",
+ "type" : "RecurringSubscription",
+ "winbackOffers" : [
+
+ ]
+ },
+ {
+ "adHocOffers" : [
+
+ ],
+ "codeOffers" : [
+
+ ],
+ "displayPrice" : "42.00",
+ "familyShareable" : false,
+ "groupNumber" : 2,
+ "internalID" : "3020000012",
+ "introductoryOffer" : null,
+ "localizations" : [
+ {
+ "description" : "Supporter badge, renews yearly",
+ "displayName" : "SimpleX Supporter Badge (Year)",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "SUBSCR_BADGE_SUPPORTER_YEAR_01",
+ "recurringSubscriptionPeriod" : "P1Y",
+ "referenceName" : "SimpleX Supporter Badge (Year)",
+ "subscriptionGroupID" : "3020000001",
+ "type" : "RecurringSubscription",
+ "winbackOffers" : [
+
+ ]
+ },
+ {
+ "adHocOffers" : [
+
+ ],
+ "codeOffers" : [
+
+ ],
+ "displayPrice" : "70.00",
+ "familyShareable" : false,
+ "groupNumber" : 1,
+ "internalID" : "3020000013",
+ "introductoryOffer" : null,
+ "localizations" : [
+ {
+ "description" : "Legend badge, renews monthly",
+ "displayName" : "SimpleX Legend Badge (Month)",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "SUBSCR_BADGE_LEGEND_MONTH_01",
+ "recurringSubscriptionPeriod" : "P1M",
+ "referenceName" : "SimpleX Legend Badge (Month)",
+ "subscriptionGroupID" : "3020000001",
+ "type" : "RecurringSubscription",
+ "winbackOffers" : [
+
+ ]
+ },
+ {
+ "adHocOffers" : [
+
+ ],
+ "codeOffers" : [
+
+ ],
+ "displayPrice" : "420.00",
+ "familyShareable" : false,
+ "groupNumber" : 1,
+ "internalID" : "3020000014",
+ "introductoryOffer" : null,
+ "localizations" : [
+ {
+ "description" : "Legend badge, renews yearly",
+ "displayName" : "SimpleX Legend Badge (Year)",
+ "locale" : "en_US"
+ }
+ ],
+ "productID" : "SUBSCR_BADGE_LEGEND_YEAR_01",
+ "recurringSubscriptionPeriod" : "P1Y",
+ "referenceName" : "SimpleX Legend Badge (Year)",
+ "subscriptionGroupID" : "3020000001",
+ "type" : "RecurringSubscription",
+ "winbackOffers" : [
+
+ ]
+ }
+ ]
+ }
+ ],
+ "version" : {
+ "major" : 4,
+ "minor" : 0
+ }
+}
diff --git a/apps/ios/CLAUDE.md b/apps/ios/CLAUDE.md
new file mode 100644
index 0000000000..a75cbe027a
--- /dev/null
+++ b/apps/ios/CLAUDE.md
@@ -0,0 +1,13 @@
+@README.md
+
+## Swift code
+
+- An extension is written only where Swift has no other form:
+ - a SwiftUI environment value, which SwiftUI requires as a property of EnvironmentValues;
+ - a conformance, required by an API, of a type declared in another module.
+- Members of a type declared in this project are declared in the body of that type, not in an extension.
+- A member of a SimpleXChat type is declared in that type; a value it needs from the app is passed as a parameter.
+- A view modifier is a ViewModifier type applied with `.modifier(_:)`.
+- A custom alignment is a static constant of a non-generic type that uses it.
+- Functions and constants at file scope are kept at file scope.
+- A new member is declared in its type even when the file already extends that type. Existing extensions are moved only in a task that concerns them.
diff --git a/apps/ios/CODE.md b/apps/ios/CODE.md
index 5a8356f656..e6372a9e33 100644
--- a/apps/ios/CODE.md
+++ b/apps/ios/CODE.md
@@ -166,6 +166,7 @@ After completing all changes (code + documentation), you MUST run an adversarial
| Shared/SimpleXApp.swift | spec/architecture.md | product/flows/onboarding.md |
| Shared/AppDelegate.swift | spec/services/notifications.md | product/flows/onboarding.md |
| Shared/Views/ChatList/ChatListView.swift | spec/client/chat-list.md | product/views/chat-list.md |
+| Shared/Views/ChatList/GetStakeBanner.swift | spec/client/chat-list.md | product/views/chat-list.md |
| Shared/Views/Chat/ChatView.swift | spec/client/chat-view.md | product/views/chat.md |
| Shared/Views/Chat/ComposeMessage/ComposeView.swift | spec/client/compose.md | product/views/chat.md |
| Shared/Views/Chat/ChatItem/ | spec/client/chat-view.md | product/views/chat.md |
diff --git a/apps/ios/Shared/AppDelegate.swift b/apps/ios/Shared/AppDelegate.swift
index 0a401f9bf3..8cc6d816b5 100644
--- a/apps/ios/Shared/AppDelegate.swift
+++ b/apps/ios/Shared/AppDelegate.swift
@@ -123,6 +123,7 @@ class AppDelegate: NSObject, UIApplicationDelegate {
private func prepareForLaunch() {
try? FileManager.default.createDirectory(at: getWallpaperDirectory(), withIntermediateDirectories: true)
+ excludeAppDataFromBackup()
}
static func keepScreenOn(_ on: Bool) {
diff --git a/apps/ios/Shared/ContentView.swift b/apps/ios/Shared/ContentView.swift
index 22d0da3829..f789037aa7 100644
--- a/apps/ios/Shared/ContentView.swift
+++ b/apps/ios/Shared/ContentView.swift
@@ -461,9 +461,14 @@ struct ContentView: View {
}
func connectViaUrl_(_ url: URL) {
+ // an app link must not tear down a redemption in flight
+ if isAppLink(url) && isBadgeLinkIssuing() { return }
dismissAllSheets() {
var path = url.path
- if path == "/r" {
+ if isAppLink(url) {
+ // branched on the scheme before the connection dispatch, which an app link must never reach
+ openAppLink(url)
+ } else if path == "/r" {
showAlert(
NSLocalizedString("Relay address", comment: "alert title"),
message: NSLocalizedString("This is a chat relay address, it cannot be used to connect.", comment: "alert message")
@@ -498,6 +503,24 @@ struct ContentView: View {
}
}
+// the app's own scheme, for every link that is not a connection link, which stays on simplex:
+private let appLinkScheme = "simplexchat"
+private let badgeLinkPath = "/badge/code/"
+
+func isAppLink(_ url: URL) -> Bool {
+ url.scheme?.lowercased() == appLinkScheme
+}
+
+// a link type added in a later version reaches this build too, so an unknown path asks for an update
+private func openAppLink(_ url: URL) {
+ let path = url.path
+ if path.hasPrefix(badgeLinkPath) {
+ openBadgeLink(String(path.dropFirst(badgeLinkPath.count)))
+ } else {
+ AlertManager.shared.showAlert(Alert(title: Text("Update the app to open this link.")))
+ }
+}
+
final class AlertManager: ObservableObject {
static let shared = AlertManager()
@Published var presentAlert = false
diff --git a/apps/ios/Shared/Model/AppAPITypes.swift b/apps/ios/Shared/Model/AppAPITypes.swift
index db70511a5a..a490756228 100644
--- a/apps/ios/Shared/Model/AppAPITypes.swift
+++ b/apps/ios/Shared/Model/AppAPITypes.swift
@@ -191,6 +191,14 @@ enum ChatCommand: ChatCmdProtocol {
case apiUploadStandaloneFile(userId: Int64, file: CryptoFile)
case apiDownloadStandaloneFile(userId: Int64, url: String, file: CryptoFile)
case apiStandaloneFileInfo(url: String)
+ // badges
+ case apiRedeemBadgeCode(userId: Int64, code: String)
+ case apiPurchaseBadge(userId: Int64, echoedInvoiceId: String?, origin: StoreReceiptOrigin, payment: ServicePayment)
+ case apiSetBadgeSubscriptionStatus(status: BadgeSubscriptionState, payment: ServicePayment)
+ case apiCreateBadgeInvoice(userId: Int64)
+ case apiGetBadgeState(userId: Int64)
+ case apiGetBadgeLedger(userId: Int64, badgePurchaseId: Int64)
+ case apiAckBadgeAlert(userId: Int64, badgePurchaseId: Int64, alertKind: BadgeAlertKind, snooze: Bool, episode: String)
// misc
case showVersion
case getAgentSubsTotal(userId: Int64)
@@ -413,6 +421,15 @@ enum ChatCommand: ChatCmdProtocol {
case let .apiUploadStandaloneFile(userId, file): return "/_upload \(userId) \(file.filePath)"
case let .apiDownloadStandaloneFile(userId, link, file): return "/_download \(userId) \(link) \(file.filePath)"
case let .apiStandaloneFileInfo(link): return "/_download info \(link)"
+ case let .apiRedeemBadgeCode(userId, code): return "/_redeem_badge_code \(userId) \(code)"
+ case let .apiPurchaseBadge(userId, echoedInvoiceId, origin, payment):
+ return "/_badge purchase \(userId)\(echoedInvoiceId.map { " invoice=\($0)" } ?? "")\(storeReceiptOriginParam(origin)) \(encodeJSON(payment))"
+ case let .apiSetBadgeSubscriptionStatus(status, payment): return "/_badge subscription \(status.text) \(encodeJSON(payment))"
+ case let .apiCreateBadgeInvoice(userId): return "/_badge invoice \(userId)"
+ case let .apiGetBadgeState(userId): return "/_badge state \(userId)"
+ case let .apiGetBadgeLedger(userId, badgePurchaseId): return "/_badge ledger \(userId) \(badgePurchaseId)"
+ case let .apiAckBadgeAlert(userId, badgePurchaseId, alertKind, snooze, episode):
+ return "/_badge ack \(userId) \(badgePurchaseId) \(badgeAlertKindParam(alertKind)) \(onOff(snooze)) \(episode)"
case .showVersion: return "/version"
case let .getAgentSubsTotal(userId): return "/get subs total \(userId)"
case let .getAgentServersSummary(userId): return "/get servers summary \(userId)"
@@ -600,6 +617,13 @@ enum ChatCommand: ChatCmdProtocol {
case .apiUploadStandaloneFile: return "apiUploadStandaloneFile"
case .apiDownloadStandaloneFile: return "apiDownloadStandaloneFile"
case .apiStandaloneFileInfo: return "apiStandaloneFileInfo"
+ case .apiRedeemBadgeCode: return "apiRedeemBadgeCode"
+ case .apiPurchaseBadge: return "apiPurchaseBadge"
+ case .apiSetBadgeSubscriptionStatus: return "apiSetBadgeSubscriptionStatus"
+ case .apiCreateBadgeInvoice: return "apiCreateBadgeInvoice"
+ case .apiGetBadgeState: return "apiGetBadgeState"
+ case .apiGetBadgeLedger: return "apiGetBadgeLedger"
+ case .apiAckBadgeAlert: return "apiAckBadgeAlert"
case .showVersion: return "showVersion"
case .getAgentSubsTotal: return "getAgentSubsTotal"
case .getAgentServersSummary: return "getAgentServersSummary"
@@ -653,6 +677,13 @@ enum ChatCommand: ChatCmdProtocol {
return .apiDeleteUser(userId: userId, delSMPQueues: delSMPQueues, viewPwd: obfuscate(viewPwd))
case let .testStorageEncryption(key):
return .testStorageEncryption(key: obfuscate(key))
+ // a code or a store receipt is a bearer secret until it is redeemed, and the terminal shows and copies cmdString
+ case let .apiRedeemBadgeCode(userId, code):
+ return .apiRedeemBadgeCode(userId: userId, code: obfuscate(code))
+ case let .apiPurchaseBadge(userId, echoedInvoiceId, origin, .apple(jws)):
+ return .apiPurchaseBadge(userId: userId, echoedInvoiceId: echoedInvoiceId, origin: origin, payment: .apple(jws: obfuscate(jws)))
+ case let .apiSetBadgeSubscriptionStatus(status, .apple(jws)):
+ return .apiSetBadgeSubscriptionStatus(status: status, payment: .apple(jws: obfuscate(jws)))
default: return self
}
}
@@ -679,6 +710,28 @@ enum ChatCommand: ChatCmdProtocol {
pwd == "" || pwd == nil ? "" : " " + encodeJSON(pwd)
}
+ // /_badge ack takes the kind in core's text encoding, not the JSON tag; an unknown kind has no banner to dismiss, so it is never acked
+ private func badgeAlertKindParam(_ kind: BadgeAlertKind) -> String {
+ switch kind {
+ case .renewalApproaching: "renewal_approaching"
+ case .paymentIssue: "payment_issue"
+ case .subscriptionCancelled: "subscription_cancelled"
+ case .subscriptionEnded: "subscription_ended"
+ case .prepaidEnding: "prepaid_ending"
+ case .supportEnded: "support_ended"
+ case .issueFailed: "issue_failed"
+ case let .unknown(s): s
+ }
+ }
+
+ private func storeReceiptOriginParam(_ origin: StoreReceiptOrigin) -> String {
+ switch origin {
+ case .purchased: ""
+ case .listed: " listed"
+ case .restored: " restored"
+ }
+ }
+
private func maybeContent(_ mc: MsgContent?) -> String {
if case let .text(s) = mc, s.isEmpty {
""
@@ -690,9 +743,40 @@ enum ChatCommand: ChatCmdProtocol {
}
}
+enum ServicePayment: Encodable {
+ case apple(jws: String)
+
+ func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ switch self {
+ case let .apple(jws):
+ try container.encode("apple", forKey: .type)
+ try container.encode(jws, forKey: .jws)
+ }
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case type, jws
+ }
+}
+
+enum StoreReceiptOrigin {
+ case purchased
+ // found in the store's list rather than bought or restored here, so core records it only into a record it has
+ case listed
+ // Restore: core claims it for this profile, moving it from another device or profile it was credited to
+ case restored
+}
+
+struct OpenStorePurchase: Decodable {
+ var invoiceId: String?
+ var transactionRef: String?
+ var creditError: BadgeIssueFailure?
+}
+
// ChatResponse is split to three enums to reduce stack size used when parsing it, parsing large enums is very inefficient.
// Spec: spec/api.md#ChatResponse0
-enum ChatResponse0: Decodable, ChatAPIResult {
+indirect enum ChatResponse0: Decodable, ChatAPIResult {
case activeUser(user: User)
case usersList(users: [UserInfo])
case chatStarted
@@ -820,7 +904,7 @@ enum ChatResponse0: Decodable, ChatAPIResult {
}
// Spec: spec/api.md#ChatResponse1
-enum ChatResponse1: Decodable, ChatAPIResult {
+indirect enum ChatResponse1: Decodable, ChatAPIResult {
case invitation(user: UserRef, connLinkInvitation: CreatedConnLink, connection: PendingContactConnection)
case connectionIncognitoUpdated(user: UserRef, toConnection: PendingContactConnection)
case connectionUserChanged(user: UserRef, fromConnection: PendingContactConnection, toConnection: PendingContactConnection, newUser: UserRef)
@@ -963,7 +1047,7 @@ enum ChatResponse1: Decodable, ChatAPIResult {
}
// Spec: spec/api.md#ChatResponse2
-enum ChatResponse2: Decodable, ChatAPIResult {
+indirect enum ChatResponse2: Decodable, ChatAPIResult {
// group responses
case groupCreated(user: UserRef, groupInfo: GroupInfo)
case publicGroupCreated(user: UserRef, groupInfo: GroupInfo, groupLink: GroupLink, groupRelays: [GroupRelay])
@@ -1019,6 +1103,13 @@ enum ChatResponse2: Decodable, ChatAPIResult {
case archiveExported(archiveErrors: [ArchiveError])
case archiveImported(archiveErrors: [ArchiveError])
case appSettings(appSettings: AppSettings)
+ // badges
+ // the full user, not UserRef: its profile carries the badge that setUserBadge just stored
+ case badgeRedeemed(user: User, redeemedBadge: LocalBadge, newBadge: Bool, badgeState: BadgeState?)
+ case badgeInvoice(user: UserRef, invoiceId: String)
+ case storeReceiptNotRecorded(user: UserRef)
+ case badgeState(user: UserRef, badgeState: BadgeState?, storePurchases: [OpenStorePurchase]?)
+ case badgeLedger(user: UserRef, badgeLedger: [StatementEntry])
var responseType: String {
switch self {
@@ -1070,6 +1161,11 @@ enum ChatResponse2: Decodable, ChatAPIResult {
case .archiveExported: "archiveExported"
case .archiveImported: "archiveImported"
case .appSettings: "appSettings"
+ case .badgeRedeemed: "badgeRedeemed"
+ case .badgeInvoice: "badgeInvoice"
+ case .storeReceiptNotRecorded: "storeReceiptNotRecorded"
+ case .badgeState: "badgeState"
+ case .badgeLedger: "badgeLedger"
}
}
@@ -1123,12 +1219,17 @@ enum ChatResponse2: Decodable, ChatAPIResult {
case let .archiveExported(archiveErrors): return String(describing: archiveErrors)
case let .archiveImported(archiveErrors): return String(describing: archiveErrors)
case let .appSettings(appSettings): return String(describing: appSettings)
+ case let .badgeRedeemed(u, redeemedBadge, newBadge, badgeState): return withUser(u, "redeemedBadge: \(String(describing: redeemedBadge))\nnewBadge: \(newBadge)\nbadgeState: \(String(describing: badgeState))")
+ case let .badgeInvoice(u, invoiceId): return withUser(u, invoiceId)
+ case let .storeReceiptNotRecorded(u): return withUser(u, "")
+ case let .badgeState(u, badgeState, storePurchases): return withUser(u, "\(String(describing: badgeState))\nstorePurchases: \(String(describing: storePurchases ?? []))")
+ case let .badgeLedger(u, badgeLedger): return withUser(u, String(describing: badgeLedger))
}
}
}
// Spec: spec/api.md#ChatEvent
-enum ChatEvent: Decodable, ChatAPIResult {
+indirect enum ChatEvent: Decodable, ChatAPIResult {
case chatSuspended
case contactSwitch(user: UserRef, contact: Contact, switchProgress: SwitchProgress)
case groupMemberSwitch(user: UserRef, groupInfo: GroupInfo, member: GroupMember, switchProgress: SwitchProgress)
@@ -1151,6 +1252,7 @@ enum ChatEvent: Decodable, ChatAPIResult {
// group events
case groupChatItemsDeleted(user: UserRef, groupInfo: GroupInfo, chatItemIDs: Set, byUser: Bool, member_: GroupMember?)
case receivedGroupInvitation(user: UserRef, groupInfo: GroupInfo, contact: Contact, memberRole: GroupMemberRole)
+ case receivedGroupInvitationViaGroup(user: UserRef, groupInfo: GroupInfo, viaGroupInfo: GroupInfo, viaMember: GroupMember, memberRole: GroupMemberRole)
case userAcceptedGroupSent(user: UserRef, groupInfo: GroupInfo, hostContact: Contact?)
case groupLinkConnecting(user: UserRef, groupInfo: GroupInfo, hostMember: GroupMember)
case businessLinkConnecting(user: UserRef, groupInfo: GroupInfo, hostMember: GroupMember, fromContact: Contact)
@@ -1205,6 +1307,11 @@ enum ChatEvent: Decodable, ChatAPIResult {
case remoteCtrlStopped(rcsState: RemoteCtrlSessionState, rcStopReason: RemoteCtrlStopReason)
// pq
case contactPQEnabled(user: UserRef, contact: Contact, pqEnabled: Bool)
+ // badges
+ case badgeChanged(user: User, badgeState: BadgeState?)
+ case badgeAlert(user: UserRef, badgeAlert: BadgeAlert)
+ case storePurchaseCredited(user: UserRef, invoiceId: String)
+ case storePurchaseRefused(user: UserRef, invoiceId: String, refusal: BadgeIssueFailure)
var responseType: String {
switch self {
@@ -1229,6 +1336,7 @@ enum ChatEvent: Decodable, ChatAPIResult {
case .chatItemsDeleted: "chatItemsDeleted"
case .groupChatItemsDeleted: "groupChatItemsDeleted"
case .receivedGroupInvitation: "receivedGroupInvitation"
+ case .receivedGroupInvitationViaGroup: "receivedGroupInvitationViaGroup"
case .userAcceptedGroupSent: "userAcceptedGroupSent"
case .groupLinkConnecting: "groupLinkConnecting"
case .businessLinkConnecting: "businessLinkConnecting"
@@ -1277,6 +1385,10 @@ enum ChatEvent: Decodable, ChatAPIResult {
case .remoteCtrlConnected: "remoteCtrlConnected"
case .remoteCtrlStopped: "remoteCtrlStopped"
case .contactPQEnabled: "contactPQEnabled"
+ case .badgeChanged: "badgeChanged"
+ case .badgeAlert: "badgeAlert"
+ case .storePurchaseCredited: "storePurchaseCredited"
+ case .storePurchaseRefused: "storePurchaseRefused"
}
}
@@ -1311,6 +1423,7 @@ enum ChatEvent: Decodable, ChatAPIResult {
case let .groupChatItemsDeleted(u, gInfo, chatItemIDs, byUser, member_):
return withUser(u, "chatItemIDs: \(String(describing: chatItemIDs))\ngroupInfo: \(String(describing: gInfo))\nbyUser: \(byUser)\nmember_: \(String(describing: member_))")
case let .receivedGroupInvitation(u, groupInfo, contact, memberRole): return withUser(u, "groupInfo: \(groupInfo)\ncontact: \(contact)\nmemberRole: \(memberRole)")
+ case let .receivedGroupInvitationViaGroup(u, groupInfo, viaGroupInfo, viaMember, memberRole): return withUser(u, "groupInfo: \(groupInfo)\nviaGroupInfo: \(viaGroupInfo)\nviaMember: \(viaMember)\nmemberRole: \(memberRole)")
case let .userAcceptedGroupSent(u, groupInfo, hostContact): return withUser(u, "groupInfo: \(groupInfo)\nhostContact: \(String(describing: hostContact))")
case let .groupLinkConnecting(u, groupInfo, hostMember): return withUser(u, "groupInfo: \(groupInfo)\nhostMember: \(String(describing: hostMember))")
case let .businessLinkConnecting(u, groupInfo, hostMember, fromContact): return withUser(u, "groupInfo: \(groupInfo)\nhostMember: \(String(describing: hostMember))\nfromContact: \(String(describing: fromContact))")
@@ -1359,6 +1472,10 @@ enum ChatEvent: Decodable, ChatAPIResult {
case let .remoteCtrlConnected(remoteCtrl): return String(describing: remoteCtrl)
case let .remoteCtrlStopped(rcsState, rcStopReason): return "rcsState: \(String(describing: rcsState))\nrcStopReason: \(String(describing: rcStopReason))"
case let .contactPQEnabled(u, contact, pqEnabled): return withUser(u, "contact: \(String(describing: contact))\npqEnabled: \(pqEnabled)")
+ case let .badgeChanged(u, badgeState): return withUser(u, String(describing: badgeState))
+ case let .badgeAlert(u, badgeAlert): return withUser(u, String(describing: badgeAlert))
+ case let .storePurchaseCredited(u, invoiceId): return withUser(u, "invoiceId: \(invoiceId)")
+ case let .storePurchaseRefused(u, invoiceId, refusal): return withUser(u, "invoiceId: \(invoiceId)\nrefusal: \(refusal.tag)")
}
}
}
@@ -1531,6 +1648,7 @@ struct AddressSettings: Codable, Hashable {
var businessAddress: Bool
var autoAccept: AutoAccept?
var autoReply: MsgContent?
+ var chatLayout: ChatLayout?
}
struct AutoAccept: Codable, Hashable {
@@ -1884,10 +2002,13 @@ enum UserServersError: Decodable {
case storageMissing(protocol: ServerProtocol, user: UserRef?)
case proxyMissing(protocol: ServerProtocol, user: UserRef?)
case duplicateServer(protocol: ServerProtocol, duplicateServer: String, duplicateHost: String)
+ case tooManyHosts(protocol: ServerProtocol, tooManyHostsServer: String)
case duplicateChatRelayAddress(duplicateChatRelay: String, duplicateAddress: String)
var globalError: String? {
switch self {
+ case .tooManyHosts:
+ return globalSMPError
case let .noServers(`protocol`, _):
switch `protocol` {
case .smp: return globalSMPError
@@ -1930,6 +2051,8 @@ enum UserServersError: Decodable {
} else {
return text
}
+ case let .tooManyHosts(.smp, server):
+ return String.localizedStringWithFormat(NSLocalizedString("Server %@ has more than two host names.", comment: "servers error"), serverHostname(server))
default:
return nil
}
@@ -2204,6 +2327,7 @@ struct AppSettings: Codable, Equatable {
var uiThemes: [ThemeOverrides]? = nil
var oneHandUI: Bool? = nil
var chatBottomBar: Bool? = nil
+ var uiChatLayout: ChatLayout? = nil
func prepareForExport() -> AppSettings {
var empty = AppSettings()
@@ -2240,6 +2364,7 @@ struct AppSettings: Codable, Equatable {
if uiThemes != def.uiThemes { empty.uiThemes = uiThemes }
if oneHandUI != def.oneHandUI { empty.oneHandUI = oneHandUI }
if chatBottomBar != def.chatBottomBar { empty.chatBottomBar = chatBottomBar }
+ if uiChatLayout != def.uiChatLayout { empty.uiChatLayout = uiChatLayout }
return empty
}
@@ -2276,7 +2401,8 @@ struct AppSettings: Codable, Equatable {
uiCurrentThemeIds: nil as [String: String]?,
uiThemes: nil as [ThemeOverrides]?,
oneHandUI: true,
- chatBottomBar: true
+ chatBottomBar: true,
+ uiChatLayout: .classic
)
}
}
diff --git a/apps/ios/Shared/Model/ChatModel.swift b/apps/ios/Shared/Model/ChatModel.swift
index e3a6ae30b9..1e9205473d 100644
--- a/apps/ios/Shared/Model/ChatModel.swift
+++ b/apps/ios/Shared/Model/ChatModel.swift
@@ -359,6 +359,36 @@ class ChannelRelaysModel: ObservableObject {
}
}
+// The badge of whichever profile it was last loaded for, kept current by the badgeChanged event so
+// that a screen already open shows what the renewal worker did with no command behind it.
+class BadgeModel: ObservableObject {
+ static let shared = BadgeModel()
+ @Published private(set) var userId: Int64?
+ @Published private(set) var badgeState: BadgeState?
+ @Published private(set) var alert: BadgeAlert?
+
+ // alert follows the state: getUserBadgeState derives it on every read, so a badgeChanged is
+ // never staler than the alert it carries - the invariant a new alert kind must keep
+ func set(userId: Int64, badgeState: BadgeState?) {
+ self.userId = userId
+ self.badgeState = badgeState
+ alert = badgeState?.alert
+ }
+
+ func setAlert(userId: Int64, alert: BadgeAlert) {
+ if self.userId == userId {
+ self.alert = alert
+ badgeState?.alert = alert
+ }
+ }
+}
+
+enum ChatListBanner {
+ case badgeAlert
+ case badgePitch
+ case getStake
+}
+
// Spec: spec/state.md#ChatModel
final class ChatModel: ObservableObject {
@Published var onboardingStage: OnboardingStage?
@@ -439,6 +469,31 @@ final class ChatModel: ObservableObject {
var filesToDelete: Set = []
+ // the banner kind the chat list showed this app session: it keeps the slot until restart, so dismissing it never puts
+ // another in its place; only the badge alert shows regardless. Set while rendering, so not published.
+ var chatListBanner: ChatListBanner?
+
+ var fileToOpen: (fileId: Int64, chatId: String?, open: (CIFile) -> Void)?
+
+ func bannerSlotFree(for banner: ChatListBanner) -> Bool {
+ chatListBanner == nil || chatListBanner == banner
+ }
+
+ func openWhenReceived(_ file: CIFile, open: @escaping (CIFile) -> Void) {
+ fileToOpen = (fileId: file.fileId, chatId: chatId, open: open)
+ }
+
+ func receivedFileToOpen(_ file: CIFile) -> Bool {
+ if let f = fileToOpen { f.fileId == file.fileId && f.chatId == chatId } else { false }
+ }
+
+ func openReceivedFile(_ file: CIFile) {
+ if let f = fileToOpen, receivedFileToOpen(file) {
+ fileToOpen = nil
+ f.open(file)
+ }
+ }
+
static let shared = ChatModel()
let im = ItemsModel.shared
@@ -896,6 +951,8 @@ final class ChatModel: ObservableObject {
func updateCurrentUser(_ newProfile: Profile, _ preferences: FullPreferences? = nil) {
if let current = currentUser {
currentUser?.profile = toLocalProfile(current.profile.profileId, newProfile, "")
+ currentUser?.profile.localBadge = current.profile.localBadge
+ currentUser?.profile.contactDomainVerified = current.profile.contactDomainVerified
if let preferences = preferences {
currentUser?.fullPreferences = preferences
}
@@ -1410,6 +1467,10 @@ final class Chat: ObservableObject, Identifiable, ChatLike {
public static var sampleData: Chat = Chat(chatInfo: ChatInfo.sampleData.direct, chatItems: [])
}
+func profileChatLayout(_ user: User?, _ appLayout: ChatLayout = chatLayoutDefault.get()) -> ChatLayout {
+ user?.uiThemes?.chatLayout?.known ?? appLayout.known ?? .classic
+}
+
final class GMember: ObservableObject, Identifiable {
@Published var wrapped: GroupMember
var created = Date.now
diff --git a/apps/ios/Shared/Model/SimpleXAPI.swift b/apps/ios/Shared/Model/SimpleXAPI.swift
index d7f29087d8..f5be035333 100644
--- a/apps/ios/Shared/Model/SimpleXAPI.swift
+++ b/apps/ios/Shared/Model/SimpleXAPI.swift
@@ -12,6 +12,7 @@ import UIKit
import Dispatch
import BackgroundTasks
import SwiftUI
+import StoreKit
@preconcurrency import SimpleXChat
private var chatController: chat_ctrl?
@@ -124,8 +125,8 @@ func chatSendCmd(_ cmd: ChatCommand, bgTask: Bool = true, bgDe
}
// Spec: spec/api.md#chatApiSendCmdWithRetry
-func chatApiSendCmdWithRetry(_ cmd: ChatCommand, bgTask: Bool = true, bgDelay: Double? = nil, inProgress: BoxedValue? = nil, retryNum: Int32 = 0) async -> APIResult? {
- let r: APIResult = await chatApiSendCmd(cmd, bgTask: bgTask, bgDelay: bgDelay, retryNum: retryNum)
+func chatApiSendCmdWithRetry(_ cmd: ChatCommand, bgTask: Bool = true, bgDelay: Double? = nil, inProgress: BoxedValue? = nil, retryNum: Int32 = 0, log: Bool = true) async -> APIResult? {
+ let r: APIResult = await chatApiSendCmd(cmd, bgTask: bgTask, bgDelay: bgDelay, retryNum: retryNum, log: log)
if inProgress == nil || inProgress?.boxedValue == true,
case let .error(e) = r, let alert = retryableNetworkErrorAlert(e) {
return await withCheckedContinuation { cont in
@@ -135,7 +136,7 @@ func chatApiSendCmdWithRetry(_ cmd: ChatCommand, bgTask: Bool
cont.resume(returning: nil)
},
onRetry: {
- let r1: APIResult? = await chatApiSendCmdWithRetry(cmd, bgTask: bgTask, bgDelay: bgDelay, inProgress: inProgress, retryNum: retryNum + 1)
+ let r1: APIResult? = await chatApiSendCmdWithRetry(cmd, bgTask: bgTask, bgDelay: bgDelay, inProgress: inProgress, retryNum: retryNum + 1, log: log)
cont.resume(returning: r1)
}
)
@@ -200,6 +201,10 @@ func retryableNetworkErrorAlert(_ e: ChatError) -> (title: String, message: Stri
title: NSLocalizedString("No private routing session", comment: "alert title"),
message: proxyDestinationErrorAlertMessage(proxyServer: proxyServer, destServer: destServer)
)
+ case .errorAgent(.AGENT(.A_SERVICE(.timeout))): (
+ title: NSLocalizedString("Connection timeout", comment: "alert title"),
+ message: NSLocalizedString("The service did not respond. Please try again.", comment: "alert message")
+ )
default: nil
}
}
@@ -1111,6 +1116,11 @@ private func apiConnectResponseAlert(_ r: APIResult) async {
NSLocalizedString("Connection link removed", comment: ""),
message: NSLocalizedString("Your contact removed this link, or it was a one-time link that was already used.\nTo connect, ask your contact to create a new link.", comment: "")
)
+ case .errorAgent(.CONN(.DUPLICATE, _)):
+ showAlert(
+ NSLocalizedString("Already connected?", comment: ""),
+ message: String.localizedStringWithFormat(NSLocalizedString("It seems like you are already connected via this link. If it is not the case, there was an error (%@).", comment: ""), "CONN DUPLICATE")
+ )
case let .errorAgent(.SMP(_, .BLOCKED(info))):
showAlert(
NSLocalizedString("Connection blocked", comment: ""),
@@ -1355,8 +1365,12 @@ func apiUpdateProfile(profile: Profile) async throws -> (Profile, [Contact])? {
switch r {
case .result(.userProfileNoChange): return (profile, [])
case let .result(.userProfileUpdated(_, _, toProfile, updateSummary)): return (toProfile, updateSummary.changedContacts)
- case .error(.errorStore(.duplicateName)): return nil;
- default: throw r.unexpected
+ case .error(.errorStore(.duplicateName)), .error(.error(.userExists)): return nil;
+ default:
+ await MainActor.run {
+ showErrorAlert(r.unexpected, NSLocalizedString("Error saving profile", comment: "alert title"))
+ }
+ throw r.unexpected
}
}
@@ -1842,8 +1856,8 @@ func apiSendCallAnswer(_ contact: Contact, _ rtcSession: String, _ rtcIceCandida
try await sendCommandOkResp(.apiSendCallAnswer(contact: contact, answer: answer))
}
-func apiSendCallExtraInfo(_ contact: Contact, _ rtcIceCandidates: String) async throws {
- let extraInfo = WebRTCExtraInfo(rtcIceCandidates: rtcIceCandidates)
+func apiSendCallExtraInfo(_ contact: Contact, _ rtcSession: String?, _ rtcIceCandidates: String) async throws {
+ let extraInfo = WebRTCExtraInfo(rtcSession: rtcSession, rtcIceCandidates: rtcIceCandidates)
try await sendCommandOkResp(.apiSendCallExtraInfo(contact: contact, extraInfo: extraInfo))
}
@@ -2182,6 +2196,127 @@ func resetAgentServersStats() async throws {
try await sendCommandOkResp(.resetAgentServersStats)
}
+// log: false because the code is a bearer secret until it is redeemed - it is in the command.
+// nil when the user cancels the retry alert.
+func apiRedeemBadgeCode(_ userId: Int64, _ code: String) async throws -> (user: User, newBadge: Bool, badgeState: BadgeState?)? {
+ let r: APIResult? = await chatApiSendCmdWithRetry(.apiRedeemBadgeCode(userId: userId, code: code), log: false)
+ guard let r else { return nil }
+ // redeemedBadge is dropped: the user's profile carries what is shown
+ if case let .result(.badgeRedeemed(user, _, newBadge, badgeState)) = r { return (user, newBadge, badgeState) }
+ throw r.unexpected
+}
+
+// a refusal is thrown, as BREServiceError with the code
+enum BadgePurchaseResult {
+ case held(user: UserRef, badgeState: BadgeState?, storePurchases: [OpenStorePurchase])
+ case credited(user: User, badgeState: BadgeState?)
+ // listed, and no record here has it: another device's purchase on the same Apple ID
+ case notRecorded
+}
+
+// log: false because a store receipt is a bearer secret, like a badge code - it is in the command.
+func apiPurchaseBadge(_ userId: Int64, _ echoedInvoiceId: String?, origin: StoreReceiptOrigin, _ payment: ServicePayment) async throws -> BadgePurchaseResult {
+ let r: ChatResponse2 = try await chatSendCmd(.apiPurchaseBadge(userId: userId, echoedInvoiceId: echoedInvoiceId, origin: origin, payment: payment), log: false)
+ switch r {
+ case let .badgeState(user, badgeState, storePurchases): return .held(user: user, badgeState: badgeState, storePurchases: storePurchases ?? [])
+ case let .badgeRedeemed(user, _, _, badgeState): return .credited(user: user, badgeState: badgeState)
+ case .storeReceiptNotRecorded: return .notRecorded
+ default: throw r.unexpected
+ }
+}
+
+// the device store's view of a subscription it charges, which changes what is shown and alerted, and retires its badge once ended
+func apiSetBadgeSubscriptionStatus(_ status: BadgeSubscriptionState, _ payment: ServicePayment) async throws {
+ let r: ChatResponse2 = try await chatSendCmd(.apiSetBadgeSubscriptionStatus(status: status, payment: payment), log: false)
+ if case .cmdOk = r { return }
+ throw r.unexpected
+}
+
+func apiCreateBadgeInvoice(_ userId: Int64) async throws -> String {
+ let r: ChatResponse2 = try await chatSendCmd(.apiCreateBadgeInvoice(userId: userId))
+ if case let .badgeInvoice(_, invoiceId) = r { return invoiceId }
+ throw r.unexpected
+}
+
+// localized where the user can act on it; otherwise the error itself, so a screenshot says what happened
+func redeemErrorText(_ error: Error, purchase: Bool) -> String {
+ if case let .error(.badgeRedeemError(e)) = error as? ChatError {
+ switch e {
+ case .invalidCode: return NSLocalizedString("This code is not valid.", comment: "alert message")
+ case .invalidReceipt: break
+ case .serviceNotConfigured:
+ return purchase
+ ? NSLocalizedString("This app version cannot buy badges.", comment: "alert message")
+ : NSLocalizedString("This app version cannot redeem badge codes.", comment: "alert message")
+ case .badgeActive:
+ return NSLocalizedString("This profile already has a badge.", comment: "alert message")
+ case .storePurchaseOpen:
+ return purchase
+ ? NSLocalizedString("A store purchase is being added to this profile.", comment: "alert message")
+ : NSLocalizedString("A purchase is being added to this profile. Try again later.", comment: "alert message")
+ case let .serviceError(code): if let text = badgeServiceErrorText(code) { return text }
+ case let .invalidResponse(message):
+ return String.localizedStringWithFormat(NSLocalizedString("The badge service sent an unexpected response: %@", comment: "alert message"), message)
+ case .unknownKeyIndex, .credentialNotVerified: return NSLocalizedString("This app version cannot verify this badge. Please update the app.", comment: "alert message")
+ }
+ }
+ if case .subscribedBefore? = error as? BadgeStoreError {
+ return NSLocalizedString("Subscribed on another profile.", comment: "alert message")
+ }
+ if let e = error as? Product.PurchaseError {
+ switch e {
+ case .productUnavailable: return NSLocalizedString("This badge is not on sale.", comment: "alert message")
+ case .purchaseNotAllowed: return NSLocalizedString("Purchases are off on this device.", comment: "alert message")
+ default: break
+ }
+ }
+ if let e = error as? StoreKitError {
+ switch e {
+ case .networkError: return NSLocalizedString("The store could not be reached.", comment: "alert message")
+ case .notAvailableInStorefront: return NSLocalizedString("This badge is not on sale.", comment: "alert message")
+ default: break
+ }
+ }
+ return String.localizedStringWithFormat(NSLocalizedString("Error: %@", comment: "alert message"), responseError(error))
+}
+
+func apiGetBadgeState(_ userId: Int64) async throws -> (badgeState: BadgeState?, storePurchases: [OpenStorePurchase]) {
+ let r: ChatResponse2 = try await chatSendCmd(.apiGetBadgeState(userId: userId))
+ if case let .badgeState(_, badgeState, storePurchases) = r { return (badgeState, storePurchases ?? []) }
+ throw r.unexpected
+}
+
+func apiGetBadgeStateSync(_ userId: Int64) throws -> (badgeState: BadgeState?, storePurchases: [OpenStorePurchase]) {
+ let r: ChatResponse2 = try chatSendCmdSync(.apiGetBadgeState(userId: userId))
+ if case let .badgeState(_, badgeState, storePurchases) = r { return (badgeState, storePurchases ?? []) }
+ throw r.unexpected
+}
+
+func apiGetBadgeLedger(_ userId: Int64, _ badgePurchaseId: Int64) async throws -> [StatementEntry] {
+ let r: ChatResponse2 = try await chatSendCmd(.apiGetBadgeLedger(userId: userId, badgePurchaseId: badgePurchaseId))
+ if case let .badgeLedger(_, badgeLedger) = r { return badgeLedger }
+ throw r.unexpected
+}
+
+func apiAckBadgeAlert(_ userId: Int64, _ badgePurchaseId: Int64, _ alertKind: BadgeAlertKind, snooze: Bool, episode: String) async throws -> BadgeState? {
+ let r: ChatResponse2 = try await chatSendCmd(.apiAckBadgeAlert(userId: userId, badgePurchaseId: badgePurchaseId, alertKind: alertKind, snooze: snooze, episode: episode))
+ if case let .badgeState(_, badgeState, _) = r { return badgeState }
+ throw r.unexpected
+}
+
+// An API call and not a stored flag: the ack is kept on the purchase in core, which then stops
+// raising this occurrence on every pass and across restarts, or until a snooze lapses.
+func ackBadgeAlert(snooze: Bool) async {
+ let badgeModel = BadgeModel.shared
+ guard let userId = badgeModel.userId, let purchaseId = badgeModel.badgeState?.badgePurchaseId, let alert = badgeModel.alert else { return }
+ do {
+ let badgeState = try await apiAckBadgeAlert(userId, purchaseId, alert.kind, snooze: snooze, episode: alert.episode)
+ await MainActor.run { badgeModel.set(userId: userId, badgeState: badgeState) }
+ } catch let error {
+ logger.error("ackBadgeAlert: \(responseError(error))")
+ }
+}
+
private func currentUserId(_ funcName: String) throws -> Int64 {
if let userId = ChatModel.shared.currentUser?.userId {
return userId
@@ -2294,6 +2429,11 @@ func startChat(refreshInvitations: Bool = true, onboarding: Bool = false) throws
ChatReceiver.shared.start()
m.chatRunning = true
chatLastStartGroupDefault.set(Date.now)
+ Task { await BadgeStore.shared.presentUnfinished() }
+ if shouldDeleteDatabaseBackupsDefault.get() {
+ deleteDatabaseBackups()
+ shouldDeleteDatabaseBackupsDefault.set(false)
+ }
}
func startChatWithTemporaryDatabase(ctrl: chat_ctrl) throws -> User? {
@@ -2318,6 +2458,7 @@ private func changeActiveUser_(_ userId: Int64, viewPwd: String?) throws {
m.currentUser = try apiSetActiveUser(userId, viewPwd: viewPwd)
m.users = try listUsers()
try getUserChatData()
+ Task { await BadgeStore.shared.presentUnfinished() }
}
func changeActiveUserAsync_(_ userId: Int64?, viewPwd: String?, keepingChatId: String? = nil) async throws {
@@ -2333,6 +2474,7 @@ func changeActiveUserAsync_(_ userId: Int64?, viewPwd: String?, keepingChatId: S
m.users = users
}
try await getUserChatDataAsync(keepingChatId: keepingChatId)
+ Task { await BadgeStore.shared.presentUnfinished() }
await MainActor.run {
if let currentUser = currentUser, var (_, invitation) = ChatModel.shared.callInvitations.first(where: { _, inv in inv.user.userId == userId }) {
invitation.user = currentUser
@@ -2352,12 +2494,44 @@ func getUserChatData() throws {
tm.activeFilter = nil
tm.userTags = tags
tm.updateChatTags(m.chats)
+ loadBadgeState()
+}
+
+// Not thrown: a failed badge read must not stop the app starting, and the model is left alone
+// rather than set to nil, which would read as "no badge".
+private func loadBadgeState() {
+ do {
+ let userId = try currentUserId("loadBadgeState")
+ let (badgeState, storePurchases) = try apiGetBadgeStateSync(userId)
+ BadgeModel.shared.set(userId: userId, badgeState: badgeState)
+ BadgeStore.shared.setStorePurchases(userId, storePurchases)
+ } catch let error {
+ logger.error("loadBadgeState: \(responseError(error))")
+ }
+}
+
+func loadBadgeStateAsync(_ userId: Int64) async {
+ do {
+ let (badgeState, storePurchases) = try await apiGetBadgeState(userId)
+ await MainActor.run {
+ BadgeModel.shared.set(userId: userId, badgeState: badgeState)
+ BadgeStore.shared.setStorePurchases(userId, storePurchases)
+ }
+ } catch let error {
+ logger.error("loadBadgeState: \(responseError(error))")
+ }
+}
+
+func loadCurrentBadgeState() async {
+ if let userId = await MainActor.run(body: { ChatModel.shared.currentUser?.userId }) {
+ await loadBadgeStateAsync(userId)
+ }
}
private func getUserChatDataAsync(keepingChatId: String?) async throws {
let m = ChatModel.shared
let tm = ChatTagsModel.shared
- if m.currentUser != nil {
+ if let userId = m.currentUser?.userId {
let userAddress = try await apiGetUserAddressAsync()
let chatItemTTL = try await getChatItemTTLAsync()
let chats = try await apiGetChatsAsync()
@@ -2370,6 +2544,7 @@ private func getUserChatDataAsync(keepingChatId: String?) async throws {
tm.userTags = tags
tm.updateChatTags(m.chats)
}
+ await loadBadgeStateAsync(userId)
} else {
await MainActor.run {
m.userAddress = nil
@@ -2607,7 +2782,8 @@ func processReceivedMsg(_ res: ChatEvent) async {
}
case let .groupChatItemsDeleted(user, groupInfo, chatItemIDs, _, member_):
await groupChatItemsDeleted(user, groupInfo, chatItemIDs, member_)
- case let .receivedGroupInvitation(user, groupInfo, _, _):
+ case let .receivedGroupInvitation(user, groupInfo, _, _),
+ let .receivedGroupInvitationViaGroup(user, groupInfo, _, _, _):
if active(user) {
await MainActor.run {
m.updateGroup(groupInfo) // update so that repeat group invitations are not duplicated
@@ -2774,6 +2950,9 @@ func processReceivedMsg(_ res: ChatEvent) async {
await chatItemSimpleUpdate(user, aChatItem)
case let .rcvFileComplete(user, aChatItem):
await chatItemSimpleUpdate(user, aChatItem)
+ if active(user), let file = aChatItem.chatItem.file, m.receivedFileToOpen(file) {
+ await MainActor.run { m.openReceivedFile(file) }
+ }
case let .rcvFileSndCancelled(user, aChatItem, _):
await chatItemSimpleUpdate(user, aChatItem)
Task { cleanupFile(aChatItem) }
@@ -2820,23 +2999,19 @@ func processReceivedMsg(_ res: ChatEvent) async {
m.callInvitations[invitation.contact.id] = invitation
}
activateCall(invitation)
- case let .callOffer(_, contact, callType, offer, sharedKey, _):
+ case let .callOffer(_, contact, callType, offer, sharedKey, askConfirmation):
await withCall(contact) { call in
await MainActor.run {
call.callState = .offerReceived
call.sharedKey = sharedKey
}
- let useRelay = UserDefaults.standard.bool(forKey: DEFAULT_WEBRTC_POLICY_RELAY)
- let iceServers = getIceServers()
- logger.debug(".callOffer useRelay \(useRelay)")
- logger.debug(".callOffer iceServers \(String(describing: iceServers))")
- await m.callCommand.processCommand(.offer(
- offer: offer.rtcSession,
- iceCandidates: offer.rtcIceCandidates,
- media: callType.media, aesKey: sharedKey,
- iceServers: iceServers,
- relay: useRelay
- ))
+ if askConfirmation {
+ showUnencryptedCallAlert(call) {
+ Task { await processCallOffer(callType, offer, sharedKey) }
+ }
+ } else {
+ await processCallOffer(callType, offer, sharedKey)
+ }
}
case let .callAnswer(_, contact, answer):
await withCall(contact) { call in
@@ -2847,7 +3022,7 @@ func processReceivedMsg(_ res: ChatEvent) async {
}
case let .callExtraInfo(_, contact, extraInfo):
await withCall(contact) { _ in
- await m.callCommand.processCommand(.ice(iceCandidates: extraInfo.rtcIceCandidates))
+ await m.callCommand.processCommand(.ice(iceCandidates: extraInfo.rtcIceCandidates, session: extraInfo.rtcSession))
}
case let .callEnded(_, contact):
if let invitation = await MainActor.run(body: { m.callInvitations.removeValue(forKey: contact.id) }) {
@@ -2948,6 +3123,24 @@ func processReceivedMsg(_ res: ChatEvent) async {
m.updateContact(contact)
}
}
+ case let .badgeChanged(user, badgeState):
+ await MainActor.run {
+ // read by core after retiring or presenting, so it carries the profile badge as changed
+ m.updateUser(user)
+ if active(user) {
+ BadgeModel.shared.set(userId: user.userId, badgeState: badgeState)
+ }
+ }
+ case let .badgeAlert(user, badgeAlert):
+ if active(user) {
+ await MainActor.run {
+ BadgeModel.shared.setAlert(userId: user.userId, alert: badgeAlert)
+ }
+ }
+ case let .storePurchaseCredited(user, invoiceId):
+ Task { await BadgeStore.shared.storePurchaseCredited(user, invoiceId) }
+ case let .storePurchaseRefused(user, invoiceId, refusal):
+ Task { await BadgeStore.shared.storePurchaseRefused(user, invoiceId, refusal) }
default:
logger.debug("unsupported event: \(res.responseType)")
}
@@ -2959,6 +3152,43 @@ func processReceivedMsg(_ res: ChatEvent) async {
logger.debug("processReceivedMsg: ignoring \(res.responseType), not in call with the contact \(contact.id)")
}
}
+
+ func processCallOffer(_ callType: CallType, _ offer: WebRTCSession, _ sharedKey: String?) async {
+ let useRelay = UserDefaults.standard.bool(forKey: DEFAULT_WEBRTC_POLICY_RELAY)
+ let iceServers = getIceServers()
+ logger.debug(".callOffer useRelay \(useRelay)")
+ logger.debug(".callOffer iceServers \(String(describing: iceServers))")
+ await m.callCommand.processCommand(.offer(
+ offer: offer.rtcSession,
+ iceCandidates: offer.rtcIceCandidates,
+ media: callType.media, aesKey: sharedKey,
+ iceServers: iceServers,
+ relay: useRelay
+ ))
+ }
+
+ func showUnencryptedCallAlert(_ call: Call, onContinue: @escaping () -> Void) {
+ DispatchQueue.main.async {
+ showAlert(
+ NSLocalizedString("Call is not encrypted", comment: "alert title"),
+ message: String.localizedStringWithFormat(NSLocalizedString("%@ accepted the call without end-to-end encryption.", comment: "alert message"), call.contact.displayName),
+ actions: {[
+ UIAlertAction(title: NSLocalizedString("End call", comment: "alert action"), style: .destructive) { _ in
+ // the call may have ended, or a new one started with the same contact, while the alert was shown
+ guard m.activeCall === call else { return }
+ if let uuid = call.callUUID {
+ CallController.shared.endCall(callUUID: uuid)
+ } else {
+ CallController.shared.endCall(call: call) {}
+ }
+ },
+ UIAlertAction(title: NSLocalizedString("Continue", comment: "alert action"), style: .default) { _ in
+ if m.activeCall === call { onContinue() }
+ }
+ ]}
+ )
+ }
+ }
}
func switchToLocalSession() {
diff --git a/apps/ios/Shared/SharedAssets.xcassets/Contents.json b/apps/ios/Shared/SharedAssets.xcassets/Contents.json
new file mode 100644
index 0000000000..4aa7c5350b
--- /dev/null
+++ b/apps/ios/Shared/SharedAssets.xcassets/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
\ No newline at end of file
diff --git a/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/Contents.json b/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/Contents.json
new file mode 100644
index 0000000000..300553af5f
--- /dev/null
+++ b/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "agent.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
\ No newline at end of file
diff --git a/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/agent.svg b/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/agent.svg
new file mode 100644
index 0000000000..fd0fdb485a
--- /dev/null
+++ b/apps/ios/Shared/SharedAssets.xcassets/agent.imageset/agent.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/apps/ios/Shared/SimpleXApp.swift b/apps/ios/Shared/SimpleXApp.swift
index 1e9a97c31b..654a31c001 100644
--- a/apps/ios/Shared/SimpleXApp.swift
+++ b/apps/ios/Shared/SimpleXApp.swift
@@ -43,7 +43,8 @@ struct SimpleXApp: App {
.environmentObject(chatModel)
.environmentObject(AppTheme.shared)
.onOpenURL { url in
- logger.debug("ContentView.onOpenURL: \(url)")
+ // an app link can carry a secret, such as a badge code that anyone who reads it can redeem
+ logger.debug("ContentView.onOpenURL: \(isAppLink(url) ? "app link" : url.absoluteString)")
if AppChatState.shared.value == .active {
chatModel.appOpenUrl = url
} else {
@@ -100,6 +101,7 @@ struct SimpleXApp: App {
if !chatModel.showCallView && !CallController.shared.hasActiveCalls() {
await updateCallInvitations()
}
+ Task { await BadgeStore.shared.presentUnfinished() }
if let url = chatModel.appOpenUrlLater {
await MainActor.run {
chatModel.appOpenUrlLater = nil
diff --git a/apps/ios/Shared/Views/Badges/BadgeStore.swift b/apps/ios/Shared/Views/Badges/BadgeStore.swift
new file mode 100644
index 0000000000..f1c5dbee0d
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgeStore.swift
@@ -0,0 +1,573 @@
+//
+// BadgeStore.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 14.08.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import Foundation
+import Combine
+import StoreKit
+import UIKit
+import SimpleXChat
+
+// TODO [badges] product ids will come from app config and prices from the badge service catalog;
+// hardcoded here so the App Store integration can be tested before the purchase API lands.
+func badgeProductId(_ level: BadgeLevel, _ period: BadgePeriod) -> String {
+ switch (level, period) {
+ case (.supporter, .oneMonth): "BADGE_SUPPORTER_01"
+ case (.supporter, .monthly): "SUBSCR_BADGE_SUPPORTER_MONTH_01"
+ case (.supporter, .annual): "SUBSCR_BADGE_SUPPORTER_YEAR_01"
+ case (.legend, .oneMonth): "BADGE_LEGEND_01"
+ case (.legend, .monthly): "SUBSCR_BADGE_LEGEND_MONTH_01"
+ case (.legend, .annual): "SUBSCR_BADGE_LEGEND_YEAR_01"
+ }
+}
+
+let badgeProductIds: [String] = BadgeLevel.allCases.flatMap { level in
+ BadgePeriod.allCases.map { badgeProductId(level, $0) }
+}
+
+// the page's app flag rides in the fragment, which never reaches the service
+let badgePageUrl = "https://badges.simplex.chat/#/tier?app=true"
+// the dev deployment, for testing store purchases: swap with the line above
+// let badgePageUrl = "https://smp7.simplex.im/#/tier?app=true"
+
+// where the store allows a link out to the badge page: the US for now, a set expected to widen.
+// An unknown storefront does not count, as this decides whether the store sees a link out of the app.
+var badgeBrowserAllowed: Bool {
+ SKPaymentQueue.default().storefront?.countryCode == "USA"
+}
+
+// Checks that build is from App Store, supported in iOS 15
+private var appStoreReceiptIsProduction: Bool {
+ Bundle.main.appStoreReceiptURL?.lastPathComponent == "receipt"
+}
+
+enum BadgePrice {
+ case loading
+ case price(String)
+ case unavailable
+
+ var canPurchase: Bool {
+ switch self {
+ case .price: true
+ case .loading, .unavailable: false
+ }
+ }
+}
+
+struct BadgePriceList {
+ let oneMonth: BadgePrice
+ let monthly: BadgePrice
+ let annual: BadgePrice
+ let monthlyAmount: Decimal?
+ let annualAmount: Decimal?
+ let subscriptionsForSale: Bool
+ let subscribedBefore: Bool
+
+ func price(_ period: BadgePeriod) -> BadgePrice {
+ switch period {
+ case .oneMonth: oneMonth
+ case .monthly: monthly
+ case .annual: annual
+ }
+ }
+
+ func forSale(_ period: BadgePeriod) -> Bool {
+ period == .oneMonth || subscriptionsForSale
+ }
+
+ // percentage the annual subscription saves against 12 monthly payments
+ var annualSavings: Int? {
+ guard let monthlyAmount, let annualAmount else { return nil }
+ let year = monthlyAmount * 12
+ guard year > 0, annualAmount < year else { return nil }
+ let saved = (year - annualAmount) / year * 100
+ let percent = Int(NSDecimalNumber(decimal: saved).doubleValue.rounded())
+ return percent > 0 ? percent : nil
+ }
+}
+
+struct BadgeStoreReceipt {
+ // the signed token the badge service verifies - never transaction.jsonRepresentation
+ let jws: String
+ let productId: String
+ let invoiceId: UUID?
+ let signatureVerified: Bool
+ let transaction: Transaction
+
+ var echoedInvoiceId: String? { invoiceId.map(coreInvoiceId) }
+}
+
+// core mints the id in lower case, and UUID formats it in upper case
+func coreInvoiceId(_ invoiceId: UUID) -> String { invoiceId.uuidString.lowercased() }
+
+enum BadgePurchaseOutcome {
+ case purchased(BadgeStoreReceipt)
+ case pending(invoiceId: String?)
+ case cancelled
+}
+
+enum BadgePurchaseState {
+ case issuing
+ case waitingForApproval
+}
+
+enum BadgeStoreError: Error {
+ case productUnavailable(productId: String)
+ case unknownPurchaseResult
+ case noActiveProfile
+ case invalidInvoiceId(String)
+ case noWindowScene
+ case subscribedBefore
+}
+
+final class BadgeStore: ObservableObject {
+ static let shared = BadgeStore()
+
+ private enum LoadState { case notLoaded, loading, loaded, failed }
+
+ @Published private var state: LoadState = .notLoaded
+ private var products: [String: Product] = [:]
+ // core's open store purchases for the profile they were read for: core knows whose a purchase is
+ @Published private var storePurchases: (userId: Int64, purchases: [OpenStorePurchase])? = nil
+ // whether a store sheet this run opened has not returned
+ @Published private var buying = false
+ // kept for this run only: StoreKit lists no deferred purchase, and a declined one delivers nothing
+ // by invoice id, so a pending purchase shows only under the profile whose record it names
+ @Published private var waitingForApproval: Set = []
+ // set once presentUnfinished has read the store: until then, an Ask to Buy approved while the app was
+ // closed, or a purchase it died before handing over, are both unknown, so canBuy refuses to buy again
+ @Published private var reconciledOnce = false
+ // the original ids of the Apple ID's subscriptions; nil until load() has read them. Apple folds a new subscription
+ // of an Apple ID that subscribed before into the earlier one, which core resumes only for the profile it retired
+ @Published private(set) var priorSubscriptions: Set? = nil
+ // right from the first frame, and confirmed by readEnvironment on iOS 16
+ @Published private(set) var servedByAppStore = appStoreReceiptIsProduction
+ // the sweep has no buyer waiting and runs at four triggers, so a failure that cannot clear is told once a run
+ private var sweepFailureShown = false
+ private var transactionUpdates: Task? = nil
+
+ private init() {}
+
+ func purchaseState(_ userId: Int64?) -> BadgePurchaseState? {
+ let purchases = openStorePurchases(userId)
+ if purchases.contains(where: { $0.transactionRef != nil }) { return .issuing }
+ if purchases.contains(where: { $0.invoiceId.map(waitingForApproval.contains) == true }) { return .waitingForApproval }
+ return nil
+ }
+
+ func creditError(_ userId: Int64?) -> BadgeIssueFailure? {
+ openStorePurchases(userId).compactMap(\.creditError).first
+ }
+
+ var checkingPurchases: Bool { !reconciledOnce }
+
+ func canBuy(_ userId: Int64?) -> Bool {
+ reconciledOnce && !buying && purchaseState(userId) == nil
+ }
+
+ func setStorePurchases(_ userId: Int64, _ purchases: [OpenStorePurchase]) {
+ storePurchases = (userId, purchases)
+ }
+
+ private func openStorePurchases(_ userId: Int64?) -> [OpenStorePurchase] {
+ guard let storePurchases, storePurchases.userId == userId else { return [] }
+ return storePurchases.purchases
+ }
+
+ func forSale(_ level: BadgeLevel, _ period: BadgePeriod) -> Bool {
+ switch period {
+ case .oneMonth: true
+ case .monthly, .annual: priorSubscriptions?.allSatisfy { $0 == resumableSubscription(level) } ?? false
+ }
+ }
+
+ // a subscription of an Apple ID that subscribed before resumes only the active profile's newest purchase,
+ // once its badge is retired and only at its own level, as the service grants a new charge only of the same tier
+ private func resumableSubscription(_ level: BadgeLevel) -> String? {
+ let badgeModel = BadgeModel.shared
+ guard badgeModel.userId == ChatModel.shared.currentUser?.userId,
+ let badgeState = badgeModel.badgeState,
+ !badgeState.shown,
+ badgeState.badgeType == level.badgeType
+ else { return nil }
+ return badgeState.subscription?.transactionRef
+ }
+
+ var subscribedBefore: Bool { priorSubscriptions?.isEmpty == false }
+
+ func price(_ level: BadgeLevel, _ period: BadgePeriod, compact: Bool = true) -> BadgePrice {
+ switch state {
+ case .notLoaded, .loading: return .loading
+ case .loaded, .failed:
+ if let p = products[badgeProductId(level, period)] { return .price(compact ? compactPrice(p) : p.displayPrice) }
+ return .unavailable
+ }
+ }
+
+ func priceList(_ level: BadgeLevel, compact: Bool = true) -> BadgePriceList {
+ BadgePriceList(
+ oneMonth: price(level, .oneMonth, compact: compact),
+ monthly: price(level, .monthly, compact: compact),
+ annual: price(level, .annual, compact: compact),
+ monthlyAmount: products[badgeProductId(level, .monthly)]?.price,
+ annualAmount: products[badgeProductId(level, .annual)]?.price,
+ subscriptionsForSale: forSale(level, .monthly),
+ subscribedBefore: subscribedBefore
+ )
+ }
+
+ // iOS 16 includes the environment in the app transaction
+ func readEnvironment() async {
+ if #available(iOS 16.0, *) {
+ if let verification = try? await AppTransaction.shared,
+ case .verified(let appTransaction) = verification {
+ let served = appTransaction.environment == .production
+ await MainActor.run { servedByAppStore = served }
+ }
+ }
+ }
+
+ func load() async {
+ guard await startLoading() else { return }
+ do {
+ let loaded = try await Product.products(for: badgeProductIds)
+ let byId = Dictionary(loaded.map { ($0.id, $0) }, uniquingKeysWith: { p, _ in p })
+ let missing = badgeProductIds.filter { byId[$0] == nil }
+ if !missing.isEmpty {
+ // the store drops ids it cannot resolve without saying why, so the storefront and
+ // the bundle the request was made for are logged with them
+ let storefront = await Storefront.current
+ logger.warning("BadgeStore.load: no product returned for \(missing.joined(separator: ", ")) - bundle \(Bundle.main.bundleIdentifier ?? "?"), storefront \(storefront?.countryCode ?? "none"), canMakePayments \(AppStore.canMakePayments)")
+ }
+ let prior = await subscriptionOriginalIds()
+ await MainActor.run {
+ products = byId
+ priorSubscriptions = prior
+ state = .loaded
+ }
+ } catch let error {
+ logger.error("BadgeStore.load: \(String(describing: error))")
+ await MainActor.run { state = .failed }
+ }
+ }
+
+ // A purchase has its core record before the store charges, and every store outcome reaches it.
+ func purchase(_ level: BadgeLevel, _ period: BadgePeriod) async throws -> BadgePurchaseOutcome {
+ let productId = badgeProductId(level, period)
+ guard let product = await MainActor.run(body: { products[productId] }) else {
+ throw BadgeStoreError.productUnavailable(productId: productId)
+ }
+ // another device on this Apple ID may have subscribed since load(), and Apple would fold this purchase into that one
+ if product.type == .autoRenewable {
+ let prior = await subscriptionOriginalIds()
+ await MainActor.run { priorSubscriptions = priorSubscriptions?.union(prior) }
+ }
+ guard await MainActor.run(body: { forSale(level, period) }) else {
+ throw BadgeStoreError.subscribedBefore
+ }
+ guard let userId = await MainActor.run(body: { ChatModel.shared.currentUser?.userId }) else {
+ throw BadgeStoreError.noActiveProfile
+ }
+ let invoice = try await apiCreateBadgeInvoice(userId)
+ guard let invoiceId = UUID(uuidString: invoice) else { throw BadgeStoreError.invalidInvoiceId(invoice) }
+ await MainActor.run { buying = true }
+ await loadBadgeStateAsync(userId)
+ do {
+ let outcome = try await storePurchase(product, invoiceId)
+ if product.type == .autoRenewable {
+ switch outcome {
+ case let .purchased(receipt): await MainActor.run { _ = priorSubscriptions?.insert(String(receipt.transaction.originalID)) }
+ // StoreKit lists no deferred purchase, so subscriptions stay shut for this run
+ case .pending: await MainActor.run { priorSubscriptions = nil }
+ case .cancelled: break
+ }
+ }
+ if case let .purchased(receipt) = outcome, receipt.signatureVerified {
+ try await handOver(receipt, origin: .purchased)
+ }
+ await MainActor.run { buying = false }
+ return outcome
+ } catch let error {
+ await MainActor.run { buying = false }
+ throw error
+ }
+ }
+
+ private func storePurchase(_ product: Product, _ invoiceId: UUID) async throws -> BadgePurchaseOutcome {
+ switch try await product.purchase(options: [.appAccountToken(invoiceId)]) {
+ case let .success(verification): return .purchased(storeReceipt(verification))
+ case .pending:
+ let pending = coreInvoiceId(invoiceId)
+ await MainActor.run { _ = waitingForApproval.insert(pending) }
+ return .pending(invoiceId: pending)
+ case .userCancelled: return .cancelled
+ @unknown default: throw BadgeStoreError.unknownPurchaseResult
+ }
+ }
+
+ // Core holds the receipt and credits it; the transaction stays unfinished until core answers it credited
+ // or refused, as an unfinished transaction is what the store re-delivers if anything is lost on the way.
+ private func handOver(_ receipt: BadgeStoreReceipt, origin: StoreReceiptOrigin) async throws {
+ guard let userId = await MainActor.run(body: { ChatModel.shared.currentUser?.userId }) else { return }
+ // a refusal is announced from core's event for it, so only an unexpected answer reaches the buyer
+ do {
+ switch try await apiPurchaseBadge(userId, receipt.echoedInvoiceId, origin: origin, .apple(jws: receipt.jws)) {
+ case let .held(user, badgeState, storePurchases):
+ await MainActor.run {
+ // the answer is the owner's, which may be another profile and a hidden one
+ if active(user) {
+ BadgeModel.shared.set(userId: user.userId, badgeState: badgeState)
+ setStorePurchases(user.userId, storePurchases)
+ }
+ }
+ case let .credited(user, badgeState):
+ await MainActor.run {
+ if active(user) {
+ BadgeModel.shared.set(userId: user.userId, badgeState: badgeState)
+ ChatModel.shared.updateUser(user)
+ if badgeState?.shown == true { UserDefaults.standard.set(true, forKey: DEFAULT_SUPPORTER_BANNER_SHOWN) }
+ }
+ }
+ await receipt.transaction.finish()
+ case .notRecorded:
+ // left unfinished, for the device that bought it, or for Restore to claim it here
+ break
+ }
+ } catch let error where badgeReceiptRefused(error) {
+ logger.error("BadgeStore.handOver: \(responseError(error))")
+ await receipt.transaction.finish()
+ // Restore found this purchase, so it says why it was refused rather than that there was nothing to restore
+ if origin == .restored { throw error }
+ }
+ }
+
+ func storePurchaseCredited(_ user: UserRef, _ invoiceId: String) async {
+ await MainActor.run {
+ // an open badges screen is the notice only for the active profile, whose badge it shows
+ if !active(user) || !badgesViewShown { showBadgeAddedAlert(user) }
+ }
+ await storePurchaseResolved(user, invoiceId)
+ }
+
+ func storePurchaseRefused(_ user: UserRef, _ invoiceId: String, _ refusal: BadgeIssueFailure) async {
+ await MainActor.run {
+ if active(user) && openStorePurchases(user.userId).contains(where: { $0.invoiceId == invoiceId }) {
+ showAlert(refusal.purchaseAlertTitle, message: refusal.purchaseText)
+ }
+ }
+ await storePurchaseResolved(user, invoiceId)
+ }
+
+ private func storePurchaseResolved(_ user: UserRef, _ invoiceId: String) async {
+ // the row goes before the store is read, or the screen shows it open while the store answers;
+ // the transaction is finished whoever owns it, as only the app can, while the cached row is the active profile's
+ await MainActor.run {
+ if active(user), let open = storePurchases, open.userId == user.userId {
+ storePurchases = (open.userId, open.purchases.filter { $0.invoiceId != invoiceId })
+ }
+ }
+ for await verification in Transaction.unfinished {
+ let receipt = storeReceipt(verification)
+ if receipt.echoedInvoiceId == invoiceId {
+ await receipt.transaction.finish()
+ return
+ }
+ }
+ }
+
+ // at launch, on return to the foreground and on a profile switch, never on a timer
+ func presentUnfinished() async {
+ await listenForTransactions()
+ for await verification in Transaction.unfinished {
+ await reconcileListed(verification)
+ }
+ await loadCurrentBadgeState()
+ await MainActor.run { reconciledOnce = true }
+ await reportSubscriptionStates()
+ }
+
+ // transactions the store settles outside a purchase call, such as an approved Ask to Buy
+ @MainActor
+ private func listenForTransactions() {
+ if transactionUpdates == nil {
+ transactionUpdates = Task.detached {
+ for await verification in Transaction.updates {
+ await BadgeStore.shared.reconcileListed(verification)
+ }
+ }
+ }
+ }
+
+ // the store lists an Apple ID's transactions on every device signed into it, so these are handed over as listed
+ private func reconcileListed(_ verification: VerificationResult) async {
+ // the receipt stays unfinished, so the next sweep hands it over again
+ do { try await reconcile(verification, origin: .listed) } catch let error {
+ logger.error("BadgeStore.reconcile: \(responseError(error))")
+ await MainActor.run {
+ // showAlert presents on the top view controller, which the launch sweep can precede;
+ // an alert with nowhere to go must not spend the one this run gets
+ if !sweepFailureShown, getTopViewController() != nil {
+ sweepFailureShown = true
+ showAlert(NSLocalizedString("Purchase error", comment: "alert title"), message: redeemErrorText(error, purchase: true))
+ }
+ }
+ }
+ }
+
+ // an unverified transaction is never sent, and left unfinished rather than lost
+ private func reconcile(_ verification: VerificationResult, origin: StoreReceiptOrigin) async throws {
+ let receipt = storeReceipt(verification)
+ let t = receipt.transaction
+ if t.productType == .autoRenewable { await MainActor.run { _ = priorSubscriptions?.insert(String(t.originalID)) } }
+ if t.productType == .autoRenewable && t.revocationDate != nil {
+ // the service refuses a revoked charge as invalid, and that would refuse the whole subscription's record
+ await t.finish()
+ } else if !badgeProductIds.contains(receipt.productId) {
+ await t.finish()
+ } else if receipt.signatureVerified {
+ try await handOver(receipt, origin: origin)
+ }
+ }
+
+ // The service asks the store only once the paid period ends, so a cancellation or a failed charge before
+ // then is seen only here. Sent with the latest transaction, which names the subscription as its first one did.
+ func reportSubscriptionStates() async {
+ guard !(await subscriptionOriginalIds()).isEmpty else { return }
+ await load()
+ guard let subscription = await MainActor.run(body: { products.values.first { $0.type == .autoRenewable }?.subscription }) else { return }
+ do {
+ for status in try await subscription.status {
+ guard case let .verified(renewalInfo) = status.renewalInfo, case .verified = status.transaction else { continue }
+ let state: BadgeSubscriptionState? = switch status.state {
+ case .subscribed: renewalInfo.willAutoRenew ? .renewing : .cancelled
+ case .inBillingRetryPeriod, .inGracePeriod: .billingRetry
+ case .expired, .revoked: .ended
+ default: nil
+ }
+ if let state {
+ try await apiSetBadgeSubscriptionStatus(state, .apple(jws: status.transaction.jwsRepresentation))
+ }
+ }
+ } catch let error {
+ logger.error("BadgeStore.reportSubscriptionStates: \(responseError(error))")
+ }
+ }
+
+ func manageSubscriptions() async {
+ let scene = await MainActor.run {
+ UIApplication.shared.connectedScenes
+ .compactMap { $0 as? UIWindowScene }
+ .first { $0.windows.contains(where: \.isKeyWindow) }
+ }
+ do {
+ guard let scene else { throw BadgeStoreError.noWindowScene }
+ try await AppStore.showManageSubscriptions(in: scene)
+ } catch let error {
+ logger.error("BadgeStore.manageSubscriptions: \(String(describing: error))")
+ if let url = URL(string: "https://apps.apple.com/account/subscriptions") {
+ await MainActor.run { UIApplication.shared.open(url) }
+ }
+ }
+ await reportSubscriptionStates()
+ await loadCurrentBadgeState()
+ }
+
+ // Hands over as restored whatever the store lists, so this profile claims it, also from another install or profile.
+ // Answers whether a badge is shown, or a purchase is being added or awaits approval, afterwards.
+ func restorePurchases() async throws -> Bool {
+ try await AppStore.sync()
+ var handOverError: Error? = nil
+ var handedOver: Set = []
+ for transactions in [Transaction.currentEntitlements, Transaction.unfinished] {
+ for await verification in transactions {
+ // a repeat would be refused once the first hand-over's badge is shown
+ guard handedOver.insert(verification.unsafePayloadValue.id).inserted else { continue }
+ do { try await reconcile(verification, origin: .restored) } catch let error {
+ logger.error("BadgeStore.restorePurchases: \(responseError(error))")
+ if handOverError == nil { handOverError = error }
+ }
+ }
+ }
+ await reportSubscriptionStates()
+ await loadCurrentBadgeState()
+ let restored: Bool = await MainActor.run {
+ let userId = ChatModel.shared.currentUser?.userId
+ let badgeShown = BadgeModel.shared.userId == userId && BadgeModel.shared.badgeState?.shown == true
+ return badgeShown || purchaseState(userId) != nil
+ }
+ if !restored, let handOverError { throw handOverError }
+ return restored
+ }
+
+ func subscriptionPrice(_ badgeType: BadgeType, planMonths: Int) -> String? {
+ let period: BadgePeriod? = switch planMonths {
+ case 1: .monthly
+ case 12: .annual
+ default: nil
+ }
+ guard let period, let level = BadgeLevel.allCases.first(where: { $0.badgeType == badgeType }) else { return nil }
+ return products[badgeProductId(level, period)]?.displayPrice
+ }
+
+ // an unverified transaction counts too: Apple, not this check, decides what a new subscription folds into
+ private func subscriptionOriginalIds() async -> Set {
+ var ids: Set = []
+ for await verification in Transaction.all {
+ let t = verification.unsafePayloadValue
+ if t.productType == .autoRenewable { ids.insert(String(t.originalID)) }
+ }
+ return ids
+ }
+
+ @MainActor
+ private func startLoading() -> Bool {
+ switch state {
+ case .notLoaded, .failed:
+ state = .loading
+ return true
+ case .loading, .loaded:
+ return false
+ }
+ }
+}
+
+// drops the fraction from whole amounts ("$7", not "$7.00") in the product's own currency style;
+// Product.displayPrice remains the exact form for views that need the cents
+private func compactPrice(_ product: Product) -> String {
+ var whole = Decimal()
+ var price = product.price
+ NSDecimalRound(&whole, &price, 0, .plain)
+ return whole == product.price
+ ? product.price.formatted(product.priceFormatStyle.precision(.fractionLength(0)))
+ : product.displayPrice
+}
+
+private func storeReceipt(_ verification: VerificationResult) -> BadgeStoreReceipt {
+ let (t, signatureVerified) = switch verification {
+ case let .verified(t): (t, true)
+ case let .unverified(t, _): (t, false)
+ }
+ return BadgeStoreReceipt(
+ jws: verification.jwsRepresentation,
+ productId: t.productID,
+ invoiceId: t.appAccountToken,
+ signatureVerified: signatureVerified,
+ transaction: t
+ )
+}
+
+// the codes core refuses a receipt with for good, after which the store may stop re-delivering it;
+// a sweep that hands over a receipt refused while the app was not running learns it only from this answer
+private func badgeReceiptRefused(_ error: Error) -> Bool {
+ let code = badgeServiceErrorCode(error)
+ return code == .receiptInvalid || code == .receiptUsed || code == .testPurchase || code == .transferLimited
+}
+
+private func badgeServiceErrorCode(_ error: Error) -> BadgeServiceErrorCode? {
+ if case let .error(.badgeRedeemError(.serviceError(code))) = error as? ChatError { return code }
+ return nil
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgeUserPreview.swift b/apps/ios/Shared/Views/Badges/BadgeUserPreview.swift
new file mode 100644
index 0000000000..10b68be473
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgeUserPreview.swift
@@ -0,0 +1,31 @@
+//
+// BadgeUserPreview.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 30.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgeUserPreview: View {
+ @EnvironmentObject var chatModel: ChatModel
+ let level: BadgeLevel
+
+ var body: some View {
+ let user = chatModel.currentUser
+ let displayName = user?.displayName ?? NSLocalizedString("My nickname", comment: "badges preview placeholder")
+ let previewBadge = LocalBadge(
+ // fabricated for the preview: the status is given here, and NameBadge renders from it alone
+ badge: BadgeInfo(badgeType: level.badgeType, badgeExpiry: .distantFuture),
+ status: .active
+ )
+ return VStack(spacing: 12) {
+ ProfileImage(imageStr: user?.image, size: 128)
+ NameWithBadge(Text(displayName).font(.largeTitle), previewBadge, .largeTitle)
+ .lineLimit(1)
+ .minimumScaleFactor(0.75)
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesCheckOrderView.swift b/apps/ios/Shared/Views/Badges/BadgesCheckOrderView.swift
new file mode 100644
index 0000000000..20cc4bec9f
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesCheckOrderView.swift
@@ -0,0 +1,219 @@
+//
+// BadgesCheckOrderView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 29.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import StoreKit
+import SimpleXChat
+
+struct BadgesCheckOrderView: View {
+ let level: BadgeLevel
+ let period: BadgePeriod
+ var startDate = Date()
+ var priceList: BadgePriceList? = nil
+
+ var body: some View {
+ BadgesCheckOrderLayout(level: level, period: period, startDate: startDate, priceList: priceList)
+ .task { await BadgeStore.shared.load() }
+ }
+}
+
+struct BadgesCheckOrderLayout: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ @ObservedObject private var store = BadgeStore.shared
+ // store.forSale reads the active profile's badge
+ @ObservedObject private var badgeModel = BadgeModel.shared
+ let level: BadgeLevel
+ let period: BadgePeriod
+ var startDate = Date()
+ var priceList: BadgePriceList? = nil
+ @State private var purchasing = false
+ // presented from this view, not AlertManager: its host is behind the sheet these views open in
+ @State private var alert: SomeAlert?
+
+ private var prices: BadgePriceList {
+ priceList ?? store.priceList(level, compact: false)
+ }
+
+ var body: some View {
+ GeometryReader { g in
+ ScrollView {
+ VStack(alignment: .center, spacing: 16) {
+ Text("Check your order")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ VStack(spacing: 0) {
+ orderRow("Your badge", Text(level.title))
+ orderRow("Duration", Text(period.label))
+ Divider()
+ .padding(.top, 8)
+ .padding(.bottom, 6)
+ orderRow("Total", period.priceText(prices.price(period)))
+ }
+ .padding(.horizontal, 24)
+ .padding(.vertical, 12)
+ .background(Color(uiColor: .secondarySystemGroupedBackground))
+ .clipShape(RoundedRectangle(cornerRadius: 16))
+ .padding(.top, 20)
+
+ if case let .price(p) = prices.price(period) {
+ switch period {
+ case .monthly: footnote("Renews at \(p) a month until you cancel it in the App Store.")
+ case .annual: footnote("Renews at \(p) a year until you cancel it in the App Store.")
+ case .oneMonth: EmptyView()
+ }
+ }
+
+ if !prices.forSale(period) && prices.subscribedBefore {
+ footnote("Subscribed on another profile.")
+ }
+
+ if !AppStore.canMakePayments {
+ footnote("Purchases are off on this device.")
+ }
+
+ Spacer(minLength: 20)
+
+ VStack(spacing: 10) {
+ payButton()
+ .padding(.vertical, 10)
+ BadgeBillingFooter(period: period, startDate: startDate)
+ BadgeInvestorOffer(level: level)
+ }
+ .padding(.bottom, g.safeAreaInsets.bottom == 0 ? 20 : 0)
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, 0)
+ .padding(.bottom, 20)
+ .frame(minHeight: g.size.height)
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ .alert(item: $alert) { $0.alert }
+ }
+
+ private func footnote(_ text: LocalizedStringKey) -> some View {
+ Text(text)
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ private func orderRow(_ title: LocalizedStringKey, _ value: Text) -> some View {
+ HStack {
+ Text(title)
+ .foregroundColor(theme.colors.secondary)
+ Spacer()
+ value
+ .fontWeight(.medium)
+ }
+ .font(.body)
+ .padding(.vertical, 8)
+ }
+
+ private func payButton() -> some View {
+ let price = prices.price(period)
+ let disabled = !price.canPurchase || purchasing || !store.canBuy(chatModel.currentUser?.userId) || !prices.forSale(period) || !AppStore.canMakePayments
+ return Button {
+ purchase()
+ } label: {
+ period.payText(price)
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: disabled))
+ .disabled(disabled)
+ }
+
+ private func purchase() {
+ purchasing = true
+ Task {
+ do {
+ if case let .purchased(receipt) = try await store.purchase(level, period), !receipt.signatureVerified {
+ await MainActor.run {
+ alert = SomeAlert(
+ alert: mkAlert(
+ title: "Cannot verify this purchase",
+ message: "Apple did not sign this purchase, so it cannot be verified."
+ ),
+ id: "badgePurchaseUnverified"
+ )
+ }
+ }
+ await MainActor.run { purchasing = false }
+ } catch let error {
+ logger.error("BadgesCheckOrderView.purchase: \(String(describing: error))")
+ await MainActor.run {
+ purchasing = false
+ // thrown when the purchase sheet or its sign-in prompt is dismissed, which needs no alert
+ if case .userCancelled? = error as? StoreKitError { return }
+ alert = SomeAlert(
+ alert: Alert(
+ title: Text("Purchase error"),
+ message: Text(verbatim: redeemErrorText(error, purchase: true))
+ ),
+ id: "badgePurchaseError"
+ )
+ }
+ }
+ }
+ }
+}
+
+struct RestorePurchasesButton: View {
+ @State private var restoring = false
+
+ var body: some View {
+ Button("Restore purchases") {
+ restoring = true
+ Task {
+ await restore()
+ await MainActor.run { restoring = false }
+ }
+ }
+ .font(.footnote)
+ .disabled(restoring)
+ }
+
+ private func restore() async {
+ do {
+ let found = try await BadgeStore.shared.restorePurchases()
+ if !found {
+ await MainActor.run {
+ showAlert(
+ NSLocalizedString("Nothing to restore", comment: "alert title"),
+ message: NSLocalizedString("No App Store purchase waiting to be added was found.", comment: "alert message")
+ )
+ }
+ }
+ } catch let error {
+ logger.error("RestorePurchasesButton: \(String(describing: error))")
+ if case .userCancelled? = error as? StoreKitError { return }
+ await MainActor.run {
+ showAlert(NSLocalizedString("Restore failed", comment: "alert title"), message: redeemErrorText(error, purchase: true))
+ }
+ }
+ }
+}
+
+struct BadgesCheckOrderView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesCheckOrderLayout(
+ level: .supporter,
+ period: .oneMonth,
+ startDate: previewDate,
+ priceList: BadgePriceList(oneMonth: .price("$7.00"), monthly: .price("$7.00"), annual: .price("$42.00"), monthlyAmount: 7, annualAmount: 42, subscriptionsForSale: true, subscribedBefore: false)
+ )
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesChooseBadgeView.swift b/apps/ios/Shared/Views/Badges/BadgesChooseBadgeView.swift
new file mode 100644
index 0000000000..76553c644a
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesChooseBadgeView.swift
@@ -0,0 +1,210 @@
+//
+// BadgesChooseBadgeView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+// TODO [badges]: replace with types produced by the badge purchase API when it lands.
+enum BadgeLevel: String, CaseIterable, Identifiable {
+ case supporter
+ case legend
+
+ var id: String { rawValue }
+
+ var title: LocalizedStringKey {
+ switch self {
+ case .supporter: "Supporter"
+ case .legend: "Legend"
+ }
+ }
+
+ var fileSize: LocalizedStringKey {
+ switch self {
+ case .supporter: "Files up to 2 GB"
+ case .legend: "Files up to 5 GB"
+ }
+ }
+
+ var fileStorage: LocalizedStringKey {
+ switch self {
+ case .supporter: "Stored for 7 days"
+ case .legend: "Stored for 21 days"
+ }
+ }
+
+ var summary: LocalizedStringKey {
+ switch self {
+ case .supporter: "Supporter: 2 GB files available for 7 days."
+ case .legend: "Legend: 5 GB files available for 21 days."
+ }
+ }
+
+ var investorOffer: LocalizedStringKey {
+ switch self {
+ case .supporter: "Invest $100+ and get a free badge."
+ case .legend: "Invest $1000+ and get a free legend badge."
+ }
+ }
+
+ var badgeType: BadgeType {
+ switch self {
+ case .supporter: .supporter
+ case .legend: .legend
+ }
+ }
+}
+
+struct BadgesChooseBadgeView: View {
+ @EnvironmentObject var theme: AppTheme
+ @ObservedObject private var store = BadgeStore.shared
+ @State private var selectedLevel: BadgeLevel = .supporter
+ @State private var continueActive = false
+
+ var body: some View {
+ GeometryReader { g in
+ ScrollView {
+ VStack(alignment: .center, spacing: 16) {
+ Text("Choose your badge")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Text("Larger files that stay available longer.")
+ .font(.body)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ BadgeUserPreview(level: selectedLevel)
+ .padding(.top, 4)
+
+ Spacer(minLength: 12)
+
+ // fixedSize + maxHeight on the cards so both match the taller one when a
+ // store price wraps in one of them
+ HStack(alignment: .top, spacing: 12) {
+ levelCard(.supporter)
+ levelCard(.legend)
+ }
+ .fixedSize(horizontal: false, vertical: true)
+
+ Spacer(minLength: 12)
+
+ VStack(spacing: 10) {
+ continueButton()
+ .padding(.vertical, 10)
+ // redeeming a code is here only when Support SimpleX offers the browser instead
+ Group {
+ if badgeBrowserAllowed {
+ RedeemCodeButton()
+ } else {
+ Color.clear
+ }
+ }
+ .frame(height: 22)
+ BadgeInvestorOffer(level: selectedLevel)
+ }
+ .padding(.bottom, g.safeAreaInsets.bottom == 0 ? 20 : 0)
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, 0)
+ .padding(.bottom, 20)
+ .frame(minHeight: g.size.height)
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ .task { await store.load() }
+ }
+
+ private func levelCard(_ level: BadgeLevel) -> some View {
+ let isSelected = level == selectedLevel
+ return Button {
+ selectedLevel = level
+ } label: {
+ VStack(spacing: 10) {
+ Image(badgeImageName(level.badgeType))
+ .resizable()
+ .scaledToFit()
+ .frame(width: 44, height: 44)
+ .padding(.top, 16)
+ Text(level.title)
+ .font(.title3)
+ .fontWeight(.bold)
+ BadgePeriod.monthly.priceText(store.price(level, .monthly))
+ .font(.body)
+ VStack(spacing: 2) {
+ Text(level.fileSize)
+ Text(level.fileStorage)
+ }
+ .font(.subheadline)
+ .foregroundColor(theme.colors.secondary)
+ .padding(.bottom, 16)
+ }
+ .multilineTextAlignment(.center)
+ .padding(.horizontal, 12)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
+ .background(Color(uiColor: .secondarySystemGroupedBackground))
+ .clipShape(RoundedRectangle(cornerRadius: 16))
+ .overlay(
+ RoundedRectangle(cornerRadius: 16)
+ .stroke(isSelected ? theme.colors.primary : Color(uiColor: .secondarySystemFill), lineWidth: 2)
+ )
+ }
+ .buttonStyle(.plain)
+ }
+
+ private func continueButton() -> some View {
+ ZStack {
+ Button {
+ continueActive = true
+ } label: {
+ Text("Continue")
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: false))
+
+ NavigationLink(isActive: $continueActive) {
+ BadgesHowLongView(level: selectedLevel)
+ .modifier(ThemedBackground())
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+}
+
+struct BadgeInvestorOffer: View {
+ @EnvironmentObject var theme: AppTheme
+ let level: BadgeLevel
+
+ var body: some View {
+ VStack(spacing: 4) {
+ Text(level.investorOffer)
+ .font(.footnote)
+ Link(destination: wefunderURL) {
+ Text("Learn more on Wefunder")
+ .font(.subheadline)
+ .foregroundColor(theme.colors.primary)
+ }
+ }
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
+
+struct BadgesChooseBadgeView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesChooseBadgeView()
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesHowItWorksView.swift b/apps/ios/Shared/Views/Badges/BadgesHowItWorksView.swift
new file mode 100644
index 0000000000..5758ceb12c
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesHowItWorksView.swift
@@ -0,0 +1,47 @@
+//
+// BadgesHowItWorksView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesHowItWorksView: View {
+ @EnvironmentObject var theme: AppTheme
+
+ var body: some View {
+ VStack(alignment: .leading) {
+ Text("How badges protect your privacy")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .padding(.top, 8)
+ .padding(.bottom, 16)
+ ScrollView {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("A badge is an anonymous credential stored in your profile on your device. This credential is never sent to anyone.")
+ Text("To prove to a contact or a server that you have a badge, the app generates a new proof that reveals only the badge type and the expiry date, rounded to a week.")
+ Text("Nobody can link two different proofs to each other or to the purchase.")
+ ExternalLink("Read more in our blog.", destination: URL(string: "https://simplex.chat/blog/20260919-simplex-supporter-badges.html")!)
+ }
+ .lineLimit(nil)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ Spacer()
+ }
+ .padding(.horizontal, 25)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+}
+
+struct BadgesHowItWorksView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesHowItWorksView()
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesHowLongView.swift b/apps/ios/Shared/Views/Badges/BadgesHowLongView.swift
new file mode 100644
index 0000000000..f837cee6b1
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesHowLongView.swift
@@ -0,0 +1,260 @@
+//
+// BadgesHowLongView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+// TODO [badges]: replace with types produced by the badge purchase API when it lands.
+enum BadgePeriod: String, CaseIterable, Identifiable {
+ case oneMonth
+ case monthly
+ case annual
+
+ var id: String { rawValue }
+
+ var icon: String {
+ switch self {
+ case .oneMonth: "calendar"
+ case .monthly: "arrow.clockwise"
+ case .annual: "arrow.clockwise"
+ }
+ }
+
+ var label: LocalizedStringKey {
+ switch self {
+ case .oneMonth: "1 month"
+ case .monthly: "Monthly"
+ case .annual: "Annual"
+ }
+ }
+
+ var months: Int {
+ switch self {
+ case .oneMonth: 1
+ case .monthly: 1
+ case .annual: 12
+ }
+ }
+
+ func priceText(_ price: BadgePrice) -> Text {
+ switch price {
+ case .loading: return Text(verbatim: "…")
+ case .unavailable: return Text(verbatim: "—")
+ case let .price(p):
+ switch self {
+ case .oneMonth: return Text(verbatim: p)
+ case .monthly: return Text("\(p)/month")
+ case .annual: return Text("\(p)/year")
+ }
+ }
+ }
+
+ func payText(_ price: BadgePrice) -> Text {
+ switch price {
+ case .loading: return Text("Loading…")
+ case .unavailable: return Text("Not available")
+ case let .price(p):
+ switch self {
+ case .oneMonth: return Text("Pay \(p)")
+ case .monthly: return Text("Pay \(p)/month")
+ case .annual: return Text("Pay \(p)/year")
+ }
+ }
+ }
+}
+
+struct BadgesHowLongView: View {
+ let level: BadgeLevel
+ var startDate = Date()
+ var priceList: BadgePriceList? = nil
+
+ var body: some View {
+ BadgesHowLongLayout(level: level, startDate: startDate, priceList: priceList)
+ .task { await BadgeStore.shared.load() }
+ }
+}
+
+struct BadgesHowLongLayout: View {
+ @EnvironmentObject var theme: AppTheme
+ @ObservedObject private var store = BadgeStore.shared
+ // store.forSale reads the active profile's badge
+ @ObservedObject private var badgeModel = BadgeModel.shared
+ let level: BadgeLevel
+ var startDate = Date()
+ var priceList: BadgePriceList? = nil
+ @State private var chosenPeriod: BadgePeriod? = nil
+ @State private var continueActive = false
+
+ private var prices: BadgePriceList {
+ priceList ?? store.priceList(level)
+ }
+
+ // monthly once subscriptions turn out to be for sale, unless a period was chosen before that
+ private var selectedPeriod: BadgePeriod {
+ chosenPeriod ?? (prices.forSale(.monthly) ? .monthly : .oneMonth)
+ }
+
+ var body: some View {
+ GeometryReader { g in
+ ScrollView {
+ VStack(alignment: .center, spacing: 16) {
+ Text("How long?")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Text(level.summary)
+ .font(.body)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ BadgeUserPreview(level: level)
+ .padding(.top, 4)
+
+ Spacer(minLength: 20)
+
+ // fixedSize + maxHeight on the cards so they all match the tallest one -
+ // only Annual carries a savings line, and prices wrap at large fonts
+ HStack(alignment: .top, spacing: 12) {
+ ForEach(BadgePeriod.allCases) { periodCard($0) }
+ }
+ .fixedSize(horizontal: false, vertical: true)
+
+ if !prices.forSale(.monthly) && prices.subscribedBefore {
+ Text("Subscribed on another profile.")
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ Spacer(minLength: 20)
+
+ VStack(spacing: 10) {
+ continueButton()
+ .padding(.vertical, 10)
+ BadgeBillingFooter(period: selectedPeriod, startDate: startDate)
+ BadgeInvestorOffer(level: level)
+ }
+ .padding(.bottom, g.safeAreaInsets.bottom == 0 ? 20 : 0)
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, 0)
+ .padding(.bottom, 20)
+ .frame(minHeight: g.size.height)
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func periodCard(_ period: BadgePeriod) -> some View {
+ let isSelected = period == selectedPeriod
+ let forSale = prices.forSale(period)
+ return Button {
+ chosenPeriod = period
+ } label: {
+ VStack(spacing: 12) {
+ Image(systemName: period.icon)
+ .resizable()
+ .scaledToFit()
+ .frame(width: 32, height: 32)
+ .foregroundColor(isSelected ? theme.colors.primary : theme.colors.secondary)
+ .opacity(forSale ? 1 : 0.4)
+ Text(period.label)
+ .font(.subheadline)
+ period.priceText(prices.price(period))
+ .font(.headline)
+ if let percent = savingsPercent(period) {
+ Text("\(percent)% off")
+ .font(.footnote)
+ .foregroundColor(isSelected ? theme.colors.primary : theme.colors.secondary)
+ }
+ }
+ .foregroundColor(forSale ? nil : theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .padding(.vertical, 25)
+ .padding(.horizontal, 12)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
+ .background(Color(uiColor: .secondarySystemGroupedBackground))
+ .clipShape(RoundedRectangle(cornerRadius: 16))
+ .overlay(
+ RoundedRectangle(cornerRadius: 16)
+ .stroke(isSelected ? theme.colors.primary : Color(uiColor: .secondarySystemFill), lineWidth: 2)
+ )
+ }
+ .buttonStyle(.plain)
+ .disabled(!forSale)
+ }
+
+ private func savingsPercent(_ period: BadgePeriod) -> Int? {
+ period == .annual ? prices.annualSavings : nil
+ }
+
+ private func continueButton() -> some View {
+ ZStack {
+ Button {
+ chosenPeriod = selectedPeriod
+ continueActive = true
+ } label: {
+ Text("Continue")
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: false))
+
+ NavigationLink(isActive: $continueActive) {
+ BadgesCheckOrderView(level: level, period: selectedPeriod)
+ .modifier(ThemedBackground(grouped: true))
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+}
+
+struct BadgeBillingFooter: View {
+ @EnvironmentObject var theme: AppTheme
+ let period: BadgePeriod
+ let startDate: Date
+
+ var body: some View {
+ Text(billingFooter)
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(height: 22)
+ }
+
+ private var billingFooter: LocalizedStringKey {
+ // TODO [badges] from now only because a purchase is refused while a badge is held (refuseWhileBadgeHeld);
+ // a top-up must count from the end of the existing balance
+ let endDate = Calendar.current.date(byAdding: .month, value: period.months, to: startDate) ?? startDate
+ let date = DateFormatter.localizedString(from: endDate, dateStyle: .long, timeStyle: .none)
+ switch period {
+ case .monthly, .annual: return "Renews on \(date). Cancel anytime."
+ case .oneMonth: return "Ends on \(date)."
+ }
+ }
+}
+
+struct BadgesHowLongView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesHowLongLayout(
+ level: .supporter,
+ startDate: previewDate,
+ priceList: BadgePriceList(oneMonth: .price("$7"), monthly: .price("$7"), annual: .price("$42"), monthlyAmount: 7, annualAmount: 42, subscriptionsForSale: true, subscribedBefore: false)
+ )
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesLedgerView.swift b/apps/ios/Shared/Views/Badges/BadgesLedgerView.swift
new file mode 100644
index 0000000000..a89bcb1299
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesLedgerView.swift
@@ -0,0 +1,156 @@
+//
+// BadgesLedgerView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 17.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesLedgerView: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ let badgeState: BadgeState
+ @State private var entries: [StatementEntry]? = nil
+ @State private var expanded: Set = []
+
+ var body: some View {
+ List {
+ if let entries {
+ Section {
+ if entries.isEmpty {
+ Text("No entries")
+ .foregroundColor(theme.colors.secondary)
+ } else {
+ ForEach(entries, id: \.entryId) { entry in
+ ledgerRow(entry)
+ }
+ }
+ }
+ }
+ }
+ .navigationTitle("Badge ledger")
+ .navigationBarTitleDisplayMode(.inline)
+ .modifier(ThemedBackground(grouped: true))
+ .toolbar {
+ ToolbarItem(placement: .navigationBarTrailing) {
+ Button { showShareSheet(items: [ledgerShareText()]) } label: {
+ Image(systemName: "square.and.arrow.up")
+ }
+ .disabled(entries?.isEmpty ?? true)
+ }
+ }
+ .onAppear(perform: loadLedger)
+ }
+
+ @ViewBuilder private func ledgerRow(_ entry: StatementEntry) -> some View {
+ let isExpanded = expanded.contains(entry.entryId)
+ Button {
+ withAnimation {
+ if isExpanded { expanded.remove(entry.entryId) } else { expanded.insert(entry.entryId) }
+ }
+ } label: {
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(entry.entryType.text)
+ Text(dateText(entry.createdAt))
+ .font(.caption)
+ .foregroundColor(theme.colors.secondary)
+ }
+ Spacer()
+ Text(changeText(entry))
+ .foregroundStyle(.secondary)
+ Image(systemName: isExpanded ? "chevron.up" : "chevron.down")
+ .foregroundColor(theme.colors.secondary)
+ }
+ }
+ .foregroundColor(theme.colors.onBackground)
+ if isExpanded {
+ ForEach(entryFields(entry), id: \.0) { field in
+ infoRow(Text(field.0), field.1).padding(.leading, 24)
+ }
+ }
+ }
+
+ private func changeText(_ entry: StatementEntry) -> String {
+ let n = entry.changeMonths
+ let months = abs(n) == 1
+ ? String.localizedStringWithFormat(NSLocalizedString("%d month", comment: "time interval"), n)
+ : String.localizedStringWithFormat(NSLocalizedString("%d months", comment: "time interval"), n)
+ return n > 0 ? "+" + months : months
+ }
+
+ private func entryFields(_ entry: StatementEntry) -> [(String, String)] {
+ var fields = [
+ (NSLocalizedString("Date", comment: "ledger entry field"), dateTimeText(entry.createdAt)),
+ (NSLocalizedString("Balance", comment: "ledger entry field"), "\(entry.balanceMonths)"),
+ (NSLocalizedString("Balance start", comment: "ledger entry field"), dateTimeText(entry.balanceStartTs)),
+ (NSLocalizedString("Anchor", comment: "ledger entry field"), dateTimeText(entry.balanceAnchorTs)),
+ (NSLocalizedString("Badge type", comment: "ledger entry field"), entry.balanceBadgeType.text)
+ ]
+ if let pausedSince = entry.wasPausedSince {
+ fields.append((NSLocalizedString("Paused since", comment: "ledger entry field"), dateTimeText(pausedSince)))
+ }
+ fields.append((NSLocalizedString("Entry ID", comment: "ledger entry field"), entry.entryId))
+ if let payload = payloadField(entry.entryType) {
+ fields.append(payload)
+ }
+ return fields
+ }
+
+ private func payloadField(_ entryType: StatementEntryType) -> (String, String)? {
+ switch entryType {
+ case let .credit(credit):
+ switch credit {
+ case let .payment(invoiceId):
+ return invoiceId.map { (NSLocalizedString("Invoice ID", comment: "ledger entry field"), $0) }
+ case let .charge(chargeId):
+ return (NSLocalizedString("Charge ID", comment: "ledger entry field"), chargeId)
+ case let .transferIn(fromPurchaseKey):
+ return (NSLocalizedString("From purchase key", comment: "ledger entry field"), fromPurchaseKey)
+ case .code, .support, .opening, .unknown:
+ return nil
+ }
+ case let .debit(debit):
+ switch debit {
+ case let .upgrade(toPurchaseKey), let .transferOut(toPurchaseKey):
+ return (NSLocalizedString("To purchase key", comment: "ledger entry field"), toPurchaseKey)
+ case .refund, .support, .badge, .lapse, .unknown:
+ return nil
+ }
+ }
+ }
+
+ // the JSON as core sent it: English field names and ISO dates, for support
+ private func ledgerShareText() -> String {
+ let encoder = getJSONEncoder()
+ encoder.outputFormatting = .prettyPrinted
+ let data = (try? encoder.encode(entries ?? [])) ?? Data()
+ return String(decoding: data, as: UTF8.self)
+ }
+
+ private func dateText(_ date: Date) -> String {
+ DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none)
+ }
+
+ private func dateTimeText(_ date: Date) -> String {
+ DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .short)
+ }
+
+ private func loadLedger() {
+ guard let user = chatModel.currentUser else { return }
+ Task {
+ do {
+ let ledger = try await apiGetBadgeLedger(user.userId, badgeState.badgePurchaseId)
+ await MainActor.run { entries = ledger }
+ } catch let e {
+ logger.error("apiGetBadgeLedger error: \(responseError(e))")
+ await MainActor.run {
+ showErrorAlert(e, NSLocalizedString("Error", comment: ""))
+ }
+ }
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesPurchaseStateView.swift b/apps/ios/Shared/Views/Badges/BadgesPurchaseStateView.swift
new file mode 100644
index 0000000000..702304acd4
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesPurchaseStateView.swift
@@ -0,0 +1,100 @@
+//
+// BadgesPurchaseStateView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 29.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesPurchaseStateView: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.dismiss) private var dismiss
+ let title: LocalizedStringKey
+ var message: LocalizedStringKey? = nil
+ var failure: BadgeIssueFailure? = nil
+ var showsAsSheet: Bool = false
+
+ var body: some View {
+ GeometryReader { g in
+ ScrollView {
+ content
+ .padding(.horizontal, 25)
+ .padding(.top, showsAsSheet ? 48 : 0)
+ .padding(.bottom, 20)
+ .frame(minHeight: g.size.height)
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private var content: some View {
+ VStack(alignment: .center, spacing: 16) {
+ Text(title)
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ if let message {
+ Text(message)
+ .font(.body)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ if let failure {
+ VStack(spacing: 6) {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundColor(.red)
+ Text(failure.purchaseText)
+ .font(.body)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ Spacer()
+
+ ProgressView().scaleEffect(2)
+
+ Spacer()
+
+ VStack(spacing: 10) {
+ Button {
+ dismiss()
+ } label: {
+ Text("Dismiss")
+ .font(.body)
+ .fontWeight(.medium)
+ .foregroundColor(theme.colors.primary)
+ .padding()
+ }
+ .padding(.vertical, 10)
+ Color.clear
+ .frame(height: 22)
+ }
+ }
+ }
+}
+
+extension BadgePurchaseState {
+ var title: LocalizedStringKey {
+ switch self {
+ case .issuing: "Issuing your badge"
+ case .waitingForApproval: "Waiting for approval"
+ }
+ }
+
+ var message: LocalizedStringKey {
+ switch self {
+ case .issuing: "Your payment is complete. The badge will be added to this profile."
+ case .waitingForApproval: "Nothing has been charged."
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesRedeemCodeView.swift b/apps/ios/Shared/Views/Badges/BadgesRedeemCodeView.swift
new file mode 100644
index 0000000000..0cf0ec0673
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesRedeemCodeView.swift
@@ -0,0 +1,446 @@
+//
+// BadgesRedeemCodeView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+import CodeScanner
+
+private let badgeCodePrefix = "SB"
+private let badgeCodeBodyLength = 20
+private let badgeCodeGroupLength = 5
+
+// Regroups what was typed; validity and the folding of ambiguous characters are core's alone.
+private func formatBadgeCodeInput(_ s: String) -> String {
+ var normalized = ""
+ for c in s.prefix(256).uppercased() {
+ guard c.isLetter || c.isNumber else { continue }
+ normalized.append(c)
+ if normalized.count == badgeCodePrefix.count + badgeCodeBodyLength { break }
+ }
+ guard normalized.hasPrefix(badgeCodePrefix) else { return normalized }
+ var groups = [badgeCodePrefix]
+ var i = normalized.index(normalized.startIndex, offsetBy: badgeCodePrefix.count)
+ while i < normalized.endIndex {
+ let j = normalized.index(i, offsetBy: badgeCodeGroupLength, limitedBy: normalized.endIndex) ?? normalized.endIndex
+ groups.append(String(normalized[i.. BadgeRedeemOutcome {
+ do {
+ guard let redeemed = try await apiRedeemBadgeCode(user.userId, code) else { return .cancelled }
+ return await MainActor.run { () -> BadgeRedeemOutcome in
+ BadgeModel.shared.set(userId: user.userId, badgeState: redeemed.badgeState)
+ ChatModel.shared.updateUser(redeemed.user)
+ if let badgeState = redeemed.badgeState, !badgeState.shown {
+ // a replay adds no purchase; a fresh code's badge can be retired on arrival
+ return .refused(message: redeemed.newBadge
+ ? NSLocalizedString("The code was accepted, but the badge it grants has already ended.", comment: "alert message")
+ : NSLocalizedString("This code has already been used.", comment: "alert message")
+ )
+ }
+ UserDefaults.standard.set(true, forKey: DEFAULT_SUPPORTER_BANNER_SHOWN)
+ return .redeemed
+ }
+ } catch let error {
+ logger.error("apiRedeemBadgeCode: \(responseError(error))")
+ return .refused(message: redeemErrorText(error, purchase: false))
+ }
+}
+
+func showCannotRedeemAlert(_ message: String) {
+ showAlert(NSLocalizedString("Cannot redeem code", comment: "alert title"), message: message)
+}
+
+// a hidden profile is named only while it is the active one, which is unlocked and on screen
+func showBadgeAddedAlert(_ user: any UserLike) {
+ guard let owner = ChatModel.shared.getUser(user.userId), active(owner) || !owner.hidden else { return }
+ showAlert(
+ NSLocalizedString("Badge added", comment: "alert title"),
+ message: String.localizedStringWithFormat(NSLocalizedString("The badge was added to the profile %@.", comment: "alert message"), owner.displayName)
+ )
+}
+
+struct BadgesRedeemCodeView: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ @Environment(\.dismiss) var dismiss: DismissAction
+ @State private var code = ""
+ @State private var canonicalCode: String? = nil
+ @State private var submitting = false
+ @State private var showQRCodeScanner = true
+
+ var body: some View {
+ ZStack {
+ GeometryReader { g in
+ ScrollView {
+ VStack(alignment: .center, spacing: 16) {
+ entryContent(g)
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, 8)
+ .padding(.bottom, 20)
+ .frame(minHeight: g.size.height)
+ }
+ }
+
+ if submitting {
+ ZStack {
+ Circle()
+ .fill(.white)
+ .opacity(0.7)
+ .frame(width: 56, height: 56)
+ ProgressView().scaleEffect(2)
+ }
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ @ViewBuilder
+ private func entryContent(_ g: GeometryProxy) -> some View {
+ Text("Redeem code")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Text("Paste the code you received.")
+ .font(.body)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ codeField()
+
+ pasteButton()
+
+ ScannerInView(
+ showQRCodeScanner: $showQRCodeScanner,
+ scannerPaused: $submitting,
+ processQRCode: processQRCode,
+ scanMode: .oncePerCode,
+ placeholderBackground: Color(.tertiarySystemFill)
+ )
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.top, 12)
+
+ Spacer(minLength: 0)
+
+ VStack(spacing: 10) {
+ submitButton()
+ .padding(.vertical, 10)
+ Color.clear
+ .frame(height: 22)
+ }
+ .padding(.bottom, g.safeAreaInsets.bottom == 0 ? 20 : 0)
+ }
+
+ private func codeField() -> some View {
+ TextField(text: $code) { Text(verbatim: "SB-XXXXX-XXXXX-XXXXX-XXXXX") }
+ .font(.body.monospaced())
+ .multilineTextAlignment(.center)
+ .autocorrectionDisabled(true)
+ .textInputAutocapitalization(.characters)
+ .disabled(submitting)
+ .padding(EdgeInsets(top: 14, leading: 12, bottom: 14, trailing: 12))
+ .background(Color(.tertiarySystemFill))
+ .cornerRadius(10.0)
+ .onChange(of: code) { applyCodeInput($0) }
+ }
+
+ private func pasteButton() -> some View {
+ Button {
+ if let pasted = UIPasteboard.general.string { applyCodeInput(pasted) }
+ } label: {
+ Text("Paste")
+ .font(.body)
+ .fontWeight(.medium)
+ .foregroundColor(theme.colors.primary)
+ }
+ .disabled(submitting)
+ }
+
+ // a changed field re-enters through onChange with the formatted text, which is when it is parsed
+ private func applyCodeInput(_ s: String) {
+ let formatted = formatBadgeCodeInput(s)
+ if formatted != code {
+ code = formatted
+ } else {
+ canonicalCode = parseBadgeCode(formatted)
+ }
+ }
+
+ private func processQRCode(_ resp: Result) {
+ switch resp {
+ case let .success(r):
+ let formatted = formatBadgeCodeInput(r.string)
+ if let canonical = parseBadgeCode(formatted) {
+ // set here rather than through onChange, which runs after redeem() reads it
+ code = formatted
+ canonicalCode = canonical
+ redeem()
+ } else {
+ showAlert(
+ NSLocalizedString("Invalid QR code", comment: "alert title"),
+ message: NSLocalizedString("The code you scanned is not a badge code.", comment: "alert message")
+ )
+ }
+ case let .failure(e):
+ logger.error("processQRCode QR code error: \(e.localizedDescription)")
+ showAlert(
+ NSLocalizedString("Invalid QR code", comment: "alert title"),
+ message: String.localizedStringWithFormat(NSLocalizedString("Error scanning code: %@", comment: "alert message"), e.localizedDescription)
+ )
+ }
+ }
+
+ private func submitButton() -> some View {
+ let disabled = canonicalCode == nil || submitting
+ return Button {
+ redeem()
+ } label: {
+ Text("Redeem")
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: disabled))
+ .disabled(disabled)
+ }
+
+ private func redeem() {
+ guard let sending = canonicalCode, let user = chatModel.currentUser else { return }
+ submitting = true
+ Task {
+ let outcome = await redeemBadgeCode(user, sending)
+ await MainActor.run {
+ submitting = false
+ switch outcome {
+ case .redeemed: dismiss()
+ case let .refused(message): showCannotRedeemAlert(message)
+ case .cancelled: break
+ }
+ }
+ }
+ }
+}
+
+private weak var badgeLinkSheet: UIViewController?
+// the open screen's own state, not a copy of its step, so the two cannot disagree
+private weak var badgeLinkState: BadgeLinkState?
+
+func isBadgeLinkIssuing() -> Bool {
+ badgeLinkSheet?.presentingViewController != nil && badgeLinkState?.step == .issuing
+}
+
+func openBadgeLink(_ codeText: String) {
+ guard let code = parseBadgeCode(codeText) else {
+ return showCannotRedeemAlert(NSLocalizedString("This code is not valid.", comment: "alert message"))
+ }
+ let state = BadgeLinkState()
+ badgeLinkSheet = showAppSheet {
+ NavigationView {
+ BadgesRedeemLinkView(code: code, state: state)
+ .modifier(ThemedBackground())
+ }
+ }
+ badgeLinkState = state
+}
+
+enum BadgeLinkStep {
+ case confirming
+ case issuing
+ case redeemed
+ case viewingBadge
+}
+
+final class BadgeLinkState: ObservableObject {
+ @Published var step = BadgeLinkStep.confirming
+}
+
+// Any web page can send a badge link, and a profile holds one badge at a time,
+// so this screen asks before redeeming, names the profile, and offers nothing but the redemption.
+// It is a code redemption with the code hidden, so it inherits the redeem screen's behaviour: an
+// interrupted request is not resumed, and the code stays on the page that issued the link.
+struct BadgesRedeemLinkView: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ @ObservedObject private var badgeModel = BadgeModel.shared
+ let code: String
+ @ObservedObject var state: BadgeLinkState
+
+ var body: some View {
+ switch state.step {
+ case .confirming: if profileHasBadge { badgeHeld() } else { confirming() }
+ case .issuing: beingIssued()
+ case .redeemed, .viewingBadge: BadgesView(showsAsSheet: true)
+ }
+ }
+
+ // read for the profile the screen names, when it renders, so the two cannot disagree;
+ // core refuses a code while the profile shows a badge
+ private var profileHasBadge: Bool {
+ badgeModel.userId == chatModel.currentUser?.userId && badgeModel.badgeState?.shown == true
+ }
+
+ // the screen cannot tell a repeated link for the badge it shows from a code for another badge,
+ // so it asserts neither
+ private func badgeHeld() -> some View {
+ linkStep(
+ "Profile already has a badge",
+ primary: ("View your badge", { state.step = .viewingBadge }),
+ textButton: ("Cancel", { closeIfShowing() })
+ ) {
+ linkText(NSLocalizedString("A badge can be added to another profile, or here once this badge ends.", comment: "badge link, profile has a badge"))
+ linkText(NSLocalizedString("Its code is on the page you bought it on, under Show code.", comment: "badge link, profile has a badge"))
+ }
+ }
+
+ private func confirming() -> some View {
+ linkStep(
+ "Add badge to your profile?",
+ primary: ("Add badge", { redeemFromLink() }),
+ textButton: ("Cancel", { closeIfShowing() })
+ ) {
+ linkText(String.localizedStringWithFormat(NSLocalizedString("The badge will be added to the profile %@.", comment: "badge link confirmation"), chatModel.currentUser?.displayName ?? ""))
+ }
+ }
+
+ // leaving does not cancel: the badge is still added after the screen closes
+ private func beingIssued() -> some View {
+ linkStep("Issuing your badge", textButton: ("Dismiss", { closeIfShowing() })) {
+ linkText(NSLocalizedString("The badge will be added to this profile.", comment: "badge link, being issued"))
+ Spacer()
+ ProgressView().scaleEffect(2)
+ }
+ }
+
+ // with no primary, the text button takes its place, so a button does not move between steps
+ private func linkStep(
+ _ title: LocalizedStringKey,
+ primary: (label: LocalizedStringKey, action: () -> Void)? = nil,
+ textButton: (label: LocalizedStringKey, action: () -> Void),
+ @ViewBuilder content: () -> Content
+ ) -> some View {
+ let textButtonLabel = Text(textButton.label)
+ .font(.body)
+ .fontWeight(.medium)
+ .foregroundColor(theme.colors.primary)
+ return VStack(alignment: .center, spacing: 16) {
+ Text(title)
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ content()
+
+ Spacer()
+
+ VStack(spacing: 10) {
+ if let primary {
+ Button {
+ primary.action()
+ } label: {
+ Text(primary.label)
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: false))
+ .padding(.vertical, 10)
+
+ Button {
+ textButton.action()
+ } label: {
+ textButtonLabel
+ }
+ .frame(height: 22)
+ } else {
+ Button {
+ textButton.action()
+ } label: {
+ // the inset OnboardingButtonStyle gives a primary
+ textButtonLabel.padding()
+ }
+ .padding(.vertical, 10)
+ Color.clear
+ .frame(height: 22)
+ }
+ }
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, 48)
+ .padding(.bottom, 20)
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ }
+
+ private func linkText(_ text: String) -> some View {
+ Text(text)
+ .font(.body)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ private func redeemFromLink() {
+ // a second tap before the screen changes must not send the code again
+ guard state.step == .confirming else { return }
+ guard let user = chatModel.currentUser else { return closeIfShowing() }
+ state.step = .issuing
+ Task {
+ let outcome = await redeemBadgeCode(user, code)
+ await MainActor.run {
+ switch outcome {
+ case .redeemed:
+ if !isShowing { showBadgeAddedAlert(user) }
+ // a covered screen is not left on the spinner; a closed one is not written to
+ if isOpen { state.step = .redeemed }
+ case let .refused(message): closeIfShowing { showCannotRedeemAlert(message) }
+ case .cancelled: closeIfShowing()
+ }
+ }
+ }
+ }
+
+ private var isOpen: Bool {
+ badgeLinkState === state && badgeLinkSheet?.presentingViewController != nil
+ }
+
+ // an alert over this screen still counts: dismissing from the presenter dismisses it too
+ private var isShowing: Bool {
+ guard isOpen, let sheet = badgeLinkSheet else { return false }
+ return sheet.presentedViewController == nil || sheet.presentedViewController is UIAlertController
+ }
+
+ // An outcome can arrive after this screen was closed or covered: it must not close another screen,
+ // and a covered one goes back to asking, so it is never left locked on the spinner.
+ private func closeIfShowing(then: @escaping () -> Void = {}) {
+ if isShowing, let presenter = badgeLinkSheet?.presentingViewController {
+ presenter.dismiss(animated: true, completion: then)
+ } else {
+ if isOpen { state.step = .confirming }
+ then()
+ }
+ }
+}
+
+struct BadgesRedeemCodeView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesRedeemCodeView()
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesSupportSimplexView.swift b/apps/ios/Shared/Views/Badges/BadgesSupportSimplexView.swift
new file mode 100644
index 0000000000..a8b10ed877
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesSupportSimplexView.swift
@@ -0,0 +1,238 @@
+//
+// BadgesSupportSimplexView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesSupportSimplexView: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ @ObservedObject private var store = BadgeStore.shared
+ // set true when presented as a sheet root (from the chat-list banner) — that path doesn't
+ // reserve nav-bar space like a NavigationLink push does, so the title lands too close to the top
+ var showsAsSheet: Bool = false
+ var servedByAppStore: Bool? = nil
+ @State private var whyBuiltActive = false
+ @State private var howItWorksActive = false
+ @State private var chooseLevelActive = false
+
+ var body: some View {
+ GeometryReader { g in
+ VStack(alignment: .center, spacing: 16) {
+ Text("Support SimpleX")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ Text("Get a badge to send larger files (2-5GB) that stay available longer (7-21 days), and to show it on your profile.")
+ .font(.body)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+
+ howItWorksButton()
+
+ Spacer(minLength: 0)
+
+ PhoneSupporterHero()
+ .frame(maxWidth: g.size.width * 0.55)
+ .layoutPriority(-1)
+
+ Spacer(minLength: 0)
+
+ VStack(spacing: 10) {
+ if servedByAppStore ?? store.servedByAppStore {
+ chooseLevelButton()
+ .padding(.vertical, 10)
+ Group {
+ if badgeBrowserAllowed {
+ buyInBrowserButton()
+ } else {
+ RedeemCodeButton()
+ }
+ }
+ .frame(height: 22)
+ RestorePurchasesButton()
+ .frame(height: 22)
+ .padding(.top, 10)
+ Text("If you were charged but have no badge, this adds it. A subscription bought with this App Store account moves to this profile, and the device or profile that had it loses its badge at its next renewal.")
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ chooseBadgeOnSiteButton()
+ .padding(.vertical, 10)
+ Group {
+ RedeemCodeButton()
+ }
+ .frame(height: 22)
+ BadgeInvestorOffer(level: .supporter).hidden()
+ }
+ }
+ .padding(.bottom, g.safeAreaInsets.bottom == 0 ? 20 : 0)
+ }
+ .padding(.horizontal, 25)
+ .padding(.top, showsAsSheet ? 48 : 0)
+ .padding(.bottom, 20)
+ // .frame(height:) not minHeight — inside the banner sheet's NavigationView minHeight
+ // would let the VStack expand past the visible area and inflate the hero.
+ .frame(height: g.size.height)
+ }
+ .frame(maxHeight: .infinity)
+ .navigationBarTitleDisplayMode(.inline)
+ .task { await store.readEnvironment() }
+ }
+
+ private func chooseLevelButton() -> some View {
+ let disabled = !store.canBuy(chatModel.currentUser?.userId)
+ return ZStack {
+ Button {
+ chooseLevelActive = true
+ } label: {
+ Text("Choose your badge")
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: disabled))
+ .disabled(disabled)
+
+ NavigationLink(isActive: $chooseLevelActive) {
+ BadgesChooseBadgeView()
+ .modifier(ThemedBackground())
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+
+ private func whyBuiltButton() -> some View {
+ ZStack {
+ Button { whyBuiltActive = true } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "info.circle")
+ Text("Why SimpleX is built.").fontWeight(.medium)
+ }
+ .font(.body)
+ }
+ NavigationLink(isActive: $whyBuiltActive) {
+ WhySimpleX(onboarding: false, titleColor: theme.colors.primary, createProfileNavLinkActive: .constant(false))
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+
+ private func howItWorksButton() -> some View {
+ ZStack {
+ Button { howItWorksActive = true } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "info.circle")
+ Text("How badges protect your privacy").fontWeight(.medium)
+ }
+ .font(.body)
+ }
+ NavigationLink(isActive: $howItWorksActive) {
+ BadgesHowItWorksView()
+ .modifier(ThemedBackground())
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+
+ private func chooseBadgeOnSiteButton() -> some View {
+ Button {
+ UIApplication.shared.open(URL(string: badgePageUrl)!)
+ } label: {
+ Text("Choose your badge")
+ }
+ .buttonStyle(OnboardingButtonStyle(isDisabled: false))
+ }
+
+ private func buyInBrowserButton() -> some View {
+ Button {
+ UIApplication.shared.open(URL(string: badgePageUrl)!)
+ } label: {
+ Text("Buy in browser")
+ .font(.body)
+ .fontWeight(.medium)
+ .foregroundColor(theme.colors.primary)
+ }
+ }
+}
+
+struct RedeemCodeButton: View {
+ @EnvironmentObject var theme: AppTheme
+ @State private var redeemCodeActive = false
+
+ var body: some View {
+ ZStack {
+ Button {
+ redeemCodeActive = true
+ } label: {
+ Text("Redeem badge code")
+ .font(.body)
+ .fontWeight(.medium)
+ .foregroundColor(theme.colors.primary)
+ }
+
+ NavigationLink(isActive: $redeemCodeActive) {
+ BadgesRedeemCodeView()
+ .modifier(ThemedBackground())
+ } label: {
+ EmptyView()
+ }
+ .frame(width: 1, height: 1)
+ .hidden()
+ }
+ }
+}
+
+struct PhoneSupporterHero: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+
+ var body: some View {
+ #if SIMPLEX_ASSETS
+ Image(colorScheme == .light ? "phone-supporter" : "phone-supporter-light")
+ .resizable()
+ .scaledToFit()
+ .frame(maxWidth: .infinity)
+ #else
+ ZStack {
+ let gp = OnboardingCardView.gradientPoints(aspectRatio: 1.0, scale: colorScheme == .light ? 1.2 : 1.5)
+ LinearGradient(
+ stops: colorScheme == .light ? OnboardingCardView.lightStops : OnboardingCardView.darkStops,
+ startPoint: gp.start,
+ endPoint: gp.end
+ )
+ Image("badge-supporter")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 96)
+ }
+ .aspectRatio(1.0, contentMode: .fit)
+ .clipShape(RoundedRectangle(cornerRadius: 24))
+ .frame(maxWidth: .infinity)
+ #endif
+ }
+}
+
+struct BadgesSupportSimplexView_Previews: PreviewProvider {
+ static var previews: some View {
+ NavigationView {
+ BadgesSupportSimplexView(servedByAppStore: true)
+ }
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesView.swift b/apps/ios/Shared/Views/Badges/BadgesView.swift
new file mode 100644
index 0000000000..be22b4436f
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesView.swift
@@ -0,0 +1,73 @@
+//
+// BadgesView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 11.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesView: View {
+ @EnvironmentObject var chatModel: ChatModel
+ @ObservedObject private var badgeModel = BadgeModel.shared
+ @ObservedObject private var store = BadgeStore.shared
+ var showsAsSheet: Bool = false
+
+ private var shownBadge: BadgeState? {
+ currentShownBadge()
+ }
+
+ var body: some View {
+ Group {
+ if let badgeState = shownBadge {
+ BadgesYourBadgeView(badgeState: badgeState, showsAsSheet: showsAsSheet)
+ .transition(.opacity)
+ } else if let purchaseState = store.purchaseState(chatModel.currentUser?.userId) {
+ // holds the purchase screens' slot, so a consumable cannot be bought twice
+ BadgesPurchaseStateView(title: purchaseState.title, message: purchaseState.message, failure: store.creditError(chatModel.currentUser?.userId), showsAsSheet: showsAsSheet)
+ .transition(.opacity)
+ } else if store.checkingPurchases {
+ BadgesPurchaseStateView(title: "Checking your purchases", showsAsSheet: showsAsSheet)
+ .transition(.opacity)
+ } else {
+ BadgesSupportSimplexView(showsAsSheet: showsAsSheet)
+ .transition(.opacity)
+ }
+ }
+ .animation(.default, value: shownBadge != nil)
+ .animation(.default, value: store.purchaseState(chatModel.currentUser?.userId))
+ .animation(.default, value: store.checkingPurchases)
+ .onAppear { badgesViewShown = true }
+ .onDisappear { badgesViewShown = false }
+ }
+}
+
+private(set) var badgesViewShown = false
+
+var supportSimpleXAlertAction: UIAlertAction {
+ UIAlertAction(title: NSLocalizedString("Support SimpleX", comment: "alert button"), style: .default) { _ in
+ openBadgesView()
+ }
+}
+
+func openBadgesView() {
+ showAppSheet {
+ NavigationView {
+ BadgesView(showsAsSheet: true)
+ .modifier(ThemedBackground())
+ }
+ }
+}
+
+func currentShownBadge() -> BadgeState? {
+ guard BadgeModel.shared.userId == ChatModel.shared.currentUser?.userId else { return nil }
+ if let badgeState = BadgeModel.shared.badgeState, badgeState.shown { return badgeState }
+ return nil
+}
+
+// false until the badge state is loaded for the current profile, so a supporter is never pitched to
+func noShownBadge() -> Bool {
+ BadgeModel.shared.badgeState?.shown != true && BadgeModel.shared.userId == ChatModel.shared.currentUser?.userId
+}
diff --git a/apps/ios/Shared/Views/Badges/BadgesYourBadgeView.swift b/apps/ios/Shared/Views/Badges/BadgesYourBadgeView.swift
new file mode 100644
index 0000000000..8a68efddb2
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/BadgesYourBadgeView.swift
@@ -0,0 +1,195 @@
+//
+// BadgesYourBadgeView.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 11.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct BadgesYourBadgeView: View {
+ @EnvironmentObject var theme: AppTheme
+ @EnvironmentObject var chatModel: ChatModel
+ @Environment(\.dismiss) private var dismiss
+ @AppStorage(DEFAULT_DEVELOPER_TOOLS) private var developerTools = false
+ @ObservedObject private var store = BadgeStore.shared
+ let badgeState: BadgeState
+ var showsAsSheet: Bool = false
+
+ var body: some View {
+ VStack(spacing: 0) {
+ if showsAsSheet {
+ Text("Your badge")
+ .font(.largeTitle)
+ .bold()
+ .foregroundColor(theme.colors.primary)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.horizontal, 25)
+ .padding(.top, 48)
+ }
+
+ List {
+ Section {
+ BadgeSummary(badgeState: badgeState)
+ }
+ let level: BadgeLevel = badgeState.badgeType == .legend ? .legend : .supporter
+ Section {
+ settingsRow("doc", color: theme.colors.secondary) { Text(level.fileSize) }
+ settingsRow("clock", color: theme.colors.secondary) { Text(level.fileStorage) }
+ } header: {
+ Text("Benefits")
+ .foregroundColor(theme.colors.secondary)
+ }
+ if let subscription = badgeState.subscription {
+ let ended = badgeState.paidThrough <= Date.now
+ let date = badgeState.paidThroughText
+ switch subscription.status {
+ case .billingRetry:
+ subscriptionSection(
+ HStack(spacing: 6) {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundColor(.red)
+ Text("Payment problem")
+ },
+ footer: "Payment failed. Update your payment method in the App Store."
+ )
+ case .cancelled where !ended:
+ subscriptionSection(Text("Ends \(date)"), footer: "Your subscription is cancelled. The badge stays until \(date).")
+ case .ended, .cancelled:
+ subscriptionSection(Text("Ended"), footer: "Subscription ended. The badge will be removed.")
+ case .renewing, .unknown, nil:
+ if ended {
+ subscriptionSection(Text("Renewing"), footer: "Renews once the App Store charges your subscription.")
+ } else if let price = store.subscriptionPrice(badgeState.badgeType, planMonths: subscription.planMonths) {
+ subscriptionSection(Text("Renews \(date) · \(price)"), footer: "Renews automatically until you cancel it in the App Store.")
+ } else {
+ subscriptionSection(Text("Renews \(date)"), footer: "Renews automatically until you cancel it in the App Store.")
+ }
+ }
+ } else {
+ Section {
+ Text(badgeState.paidThroughText)
+ } header: {
+ Text("Ends")
+ .foregroundColor(theme.colors.secondary)
+ } footer: {
+ Text("No renewal: the badge ends when the prepaid months run out.")
+ .foregroundColor(theme.colors.secondary)
+ }
+ }
+ Section {
+ NavigationLink {
+ BadgesHowItWorksView()
+ .modifier(ThemedBackground())
+ } label: {
+ settingsRow("info.circle", color: theme.colors.secondary) {
+ Text("How badges protect your privacy")
+ }
+ }
+ }
+ if let issueError = badgeState.issueError {
+ Section {
+ Text(issueError.reason.text)
+ .foregroundColor(theme.colors.secondary)
+ infoRow("Since", badgeTimestamp(issueError.failedSince))
+ if issueError.lastAttemptAt != issueError.failedSince {
+ infoRow("Last attempt", badgeTimestamp(issueError.lastAttemptAt))
+ }
+ settingsRow("number", color: theme.colors.secondary) {
+ Button("Contact SimpleX team") {
+ dismiss()
+ DispatchQueue.main.async {
+ // simplexTeamURL targets this same app; route to the in-app connect flow
+ ChatModel.shared.appOpenUrl = simplexTeamURL
+ }
+ }
+ }
+ } header: {
+ HStack(spacing: 6) {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundColor(.red)
+ Text("Error")
+ }
+ }
+ }
+ if developerTools {
+ Section(header: Text("Credential").foregroundColor(theme.colors.secondary)) {
+ if let badge = chatModel.currentUser?.profile.localBadge {
+ infoRow("Status", badge.status.rawValue)
+ infoRow("Expires", badgeTimestamp(badge.badge.badgeExpiry))
+ }
+ infoRow("Months left", "\(badgeState.monthsLeft)")
+ infoRow("Purchase ID", "\(badgeState.badgePurchaseId)")
+ if let nextWakeAt = badgeState.nextWakeAt {
+ infoRow("Next check", badgeTimestamp(nextWakeAt))
+ }
+ if let issueError = badgeState.issueError {
+ infoRow("Error", issueError.reason.tag)
+ }
+ Button("Copy purchase key") {
+ UIPasteboard.general.string = badgeState.purchaseKey
+ }
+ NavigationLink {
+ BadgesLedgerView(badgeState: badgeState)
+ } label: {
+ Text("Badge ledger")
+ }
+ }
+ }
+ }
+ }
+ .frame(maxHeight: .infinity)
+ .navigationTitle(showsAsSheet ? "" : "Your badge")
+ .navigationBarTitleDisplayMode(showsAsSheet ? .inline : .large)
+ .modifier(ThemedBackground(grouped: true))
+ }
+
+ private func subscriptionSection(_ status: some View, footer: LocalizedStringKey) -> some View {
+ Section {
+ status
+ settingsRow("creditcard", color: theme.colors.secondary) {
+ Button("Manage subscription") {
+ Task { await BadgeStore.shared.manageSubscriptions() }
+ }
+ }
+ } header: {
+ Text("Subscription")
+ .foregroundColor(theme.colors.secondary)
+ } footer: {
+ Text(footer)
+ .foregroundColor(theme.colors.secondary)
+ }
+ }
+
+ private func badgeTimestamp(_ date: Date) -> String {
+ DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .short)
+ }
+}
+
+struct BadgeSummary: View {
+ @EnvironmentObject var theme: AppTheme
+ let badgeState: BadgeState
+
+ var body: some View {
+ VStack(spacing: 4) {
+ Image(badgeImageName(badgeState.badgeType))
+ .resizable()
+ .scaledToFit()
+ .frame(width: 68, height: 68)
+ .padding(.bottom, 8)
+
+ Text(badgeTypeName(badgeState.badgeType))
+ .font(.title3)
+ .fontWeight(.semibold)
+
+ Text("shown on your profile")
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 8)
+ }
+}
diff --git a/apps/ios/Shared/Views/Badges/SupportSimpleXBanner.swift b/apps/ios/Shared/Views/Badges/SupportSimpleXBanner.swift
new file mode 100644
index 0000000000..507be8ce5e
--- /dev/null
+++ b/apps/ios/Shared/Views/Badges/SupportSimpleXBanner.swift
@@ -0,0 +1,91 @@
+//
+// SupportSimpleXBanner.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 28.07.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+struct SupportSimpleXBanner: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+ var title: LocalizedStringKey = "Support SimpleX"
+ var subtitle: LocalizedStringKey = "Get badge + better files"
+ var warning: Bool = false
+ var showDismiss: Bool = true
+ let onTap: () -> Void
+ let onDismiss: () -> Void
+
+ // the card's own height, for centring the fallback hero; hero stays fixed so its above-card
+ // overhang shrinks at very large fonts
+ @ScaledMetric(relativeTo: .body) private var scaledCardHeight: CGFloat = 72
+ private var cardHeight: CGFloat { max(72, scaledCardHeight) }
+ private let heroWidth: CGFloat = 110
+ // shorter than the natural drawn height so .clipped() slices the phone body at card bottom
+ private let heroVisibleHeight: CGFloat = 108
+ // hero right edge sits exactly at the dismiss X's left edge (X trailing 16 + width 12)
+ private let heroTrailingPadding: CGFloat = 28
+ private let textToHeroGap: CGFloat = 6
+
+ var body: some View {
+ // Card is the Button; hero is an overlay so it can extend above the card top without
+ // affecting layout size. Dismiss X is a ZStack sibling anchored to the card's top-right.
+ ZStack(alignment: .topTrailing) {
+ Button(action: onTap) {
+ HStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text(title)
+ .font(.headline)
+ .foregroundColor(warning ? .red : theme.colors.primary)
+ .lineLimit(2)
+ Text(subtitle)
+ .font(.subheadline)
+ .foregroundColor(theme.colors.onBackground)
+ .lineLimit(2)
+ }
+ Spacer(minLength: heroWidth + heroTrailingPadding + textToHeroGap)
+ }
+ .modifier(BannerCard())
+ }
+ .buttonStyle(.plain)
+ .overlay(alignment: .bottomTrailing) {
+ heroThumbnail()
+ .padding(.trailing, heroTrailingPadding)
+ .allowsHitTesting(false)
+ }
+
+ if showDismiss {
+ BannerDismissButton(onDismiss: onDismiss)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func heroThumbnail() -> some View {
+ #if SIMPLEX_ASSETS
+ // draws at natural aspect, top-aligned in a shorter slot; .clipped() cuts the overflow at card bottom
+ Image(colorScheme == .light ? "phone-supporter" : "phone-supporter-light")
+ .resizable()
+ .aspectRatio(contentMode: .fill)
+ .frame(width: heroWidth, height: heroVisibleHeight, alignment: .top)
+ .clipped()
+ #else
+ Image("badge-supporter")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 48, height: 48)
+ .padding(.vertical, (cardHeight - 48) / 2)
+ .padding(.trailing, 12)
+ #endif
+ }
+}
+
+struct SupportSimpleXBanner_Previews: PreviewProvider {
+ static var previews: some View {
+ SupportSimpleXBanner(onTap: {}, onDismiss: {})
+ .padding()
+ }
+}
diff --git a/apps/ios/Shared/Views/Call/ActiveCallView.swift b/apps/ios/Shared/Views/Call/ActiveCallView.swift
index 754bcb2715..c74ee673d2 100644
--- a/apps/ios/Shared/Views/Call/ActiveCallView.swift
+++ b/apps/ios/Shared/Views/Call/ActiveCallView.swift
@@ -161,10 +161,10 @@ struct ActiveCallView: View {
CallSoundsPlayer.shared.stop()
}
}
- case let .ice(iceCandidates):
+ case let .ice(iceCandidates, session):
Task {
do {
- try await apiSendCallExtraInfo(call.contact, iceCandidates)
+ try await apiSendCallExtraInfo(call.contact, session, iceCandidates)
} catch {
logger.error("apiSendCallExtraInfo \(responseError(error))")
}
@@ -172,15 +172,24 @@ struct ActiveCallView: View {
case let .connection(state):
if let callStatus = WebRTCCallStatus.init(rawValue: state.connectionState),
case .connected = callStatus {
- call.direction == .outgoing
- ? CallController.shared.reportOutgoingCall(call: call, connectedAt: nil)
- : CallController.shared.reportIncomingCall(call: call, connectedAt: nil)
+ // connectedAt is kept on reconnection, so that call duration is not reset
+ if call.connectedAt == nil {
+ call.direction == .outgoing
+ ? CallController.shared.reportOutgoingCall(call: call, connectedAt: nil)
+ : CallController.shared.reportIncomingCall(call: call, connectedAt: nil)
+ call.connectedAt = .now
+ }
call.callState = .connected
- call.connectedAt = .now
+ CallSoundsPlayer.shared.stop()
if !wasConnected {
CallSoundsPlayer.shared.vibrate(long: false)
wasConnected = true
}
+ } else if state.connectionState == "reconnecting" {
+ if call.callState != .reconnecting {
+ CallSoundsPlayer.shared.startConnectingCallSound()
+ }
+ call.callState = .reconnecting
}
if state.connectionState == "closed" {
closeCallView(client)
@@ -190,17 +199,22 @@ struct ActiveCallView: View {
m.activeCall = nil
m.activeCallViewIsCollapsed = false
}
- Task {
- do {
- try await apiCallStatus(call.contact, state.connectionState)
- } catch {
- logger.error("apiCallStatus \(responseError(error))")
+ // "reconnecting" is not a core call status
+ if state.connectionState != "reconnecting" {
+ Task {
+ do {
+ try await apiCallStatus(call.contact, state.connectionState)
+ } catch {
+ logger.error("apiCallStatus \(responseError(error))")
+ }
}
}
case let .connected(connectionInfo):
call.callState = .connected
call.connectionInfo = connectionInfo
- call.connectedAt = .now
+ if call.connectedAt == nil {
+ call.connectedAt = .now
+ }
if !wasConnected {
CallSoundsPlayer.shared.vibrate(long: false)
wasConnected = true
@@ -519,9 +533,9 @@ struct ActiveCallOverlay: View {
struct ActiveCallOverlay_Previews: PreviewProvider {
static var previews: some View {
Group{
- ActiveCallOverlay(call: Call(direction: .incoming, contact: Contact.sampleData, callUUID: UUID().uuidString.lowercased(), callState: .offerSent, initialCallType: .video), client: WebRTCClient({ _ in }, Binding.constant(nil)))
+ ActiveCallOverlay(call: Call(direction: .incoming, contact: Contact.sampleData, callUUID: "00000000-0000-0000-0000-000000000001", callState: .offerSent, initialCallType: .video), client: WebRTCClient({ _ in }, Binding.constant(nil)))
.background(.black)
- ActiveCallOverlay(call: Call(direction: .incoming, contact: Contact.sampleData, callUUID: UUID().uuidString.lowercased(), callState: .offerSent, initialCallType: .audio), client: WebRTCClient({ _ in }, Binding.constant(nil)))
+ ActiveCallOverlay(call: Call(direction: .incoming, contact: Contact.sampleData, callUUID: "00000000-0000-0000-0000-000000000002", callState: .offerSent, initialCallType: .audio), client: WebRTCClient({ _ in }, Binding.constant(nil)))
.background(.black)
}
}
diff --git a/apps/ios/Shared/Views/Call/CallViewRenderers.swift b/apps/ios/Shared/Views/Call/CallViewRenderers.swift
index e779093a24..f007555817 100644
--- a/apps/ios/Shared/Views/Call/CallViewRenderers.swift
+++ b/apps/ios/Shared/Views/Call/CallViewRenderers.swift
@@ -222,7 +222,7 @@ struct CallViewLocal: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
let view = UIView()
- let localRenderer = RTCEAGLVideoView(frame: .zero)
+ let localRenderer = RTCMTLVideoView(frame: .zero)
context.coordinator.renderer = localRenderer
client.addLocalRenderer(localRenderer)
addSubviewAndResize(localRenderer, nil, into: view)
@@ -245,7 +245,7 @@ struct CallViewLocal: UIViewRepresentable {
// MARK: - Coordinator
class Coordinator: NSObject, AVPictureInPictureControllerDelegate {
- var renderer: RTCEAGLVideoView?
+ var renderer: RTCMTLVideoView?
var client: WebRTCClient
required init(_ client: WebRTCClient) {
diff --git a/apps/ios/Shared/Views/Call/WebRTC.swift b/apps/ios/Shared/Views/Call/WebRTC.swift
index ef9135761c..6f7a0efa38 100644
--- a/apps/ios/Shared/Views/Call/WebRTC.swift
+++ b/apps/ios/Shared/Views/Call/WebRTC.swift
@@ -77,6 +77,7 @@ enum CallState {
case answerReceived // incoming - webrtc answer received via API
case negotiated // outgoing - webrtc offer processed and answer sent, incoming - webrtc answer processed
case connected
+ case reconnecting
case ended
var text: LocalizedStringKey {
@@ -89,6 +90,7 @@ enum CallState {
case .answerReceived: return "received confirmation…"
case .negotiated: return "connecting…"
case .connected: return "connected"
+ case .reconnecting: return "reconnecting…"
case .ended: return "ended"
}
}
@@ -119,7 +121,7 @@ enum WCallCommand: Equatable, Encodable, Decodable {
case start(media: CallMediaType, aesKey: String? = nil, iceServers: [RTCIceServer]? = nil, relay: Bool? = nil)
case offer(offer: String, iceCandidates: String, media: CallMediaType, aesKey: String? = nil, iceServers: [RTCIceServer]? = nil, relay: Bool? = nil)
case answer(answer: String, iceCandidates: String)
- case ice(iceCandidates: String)
+ case ice(iceCandidates: String, session: String? = nil)
case media(source: CallMediaSource, enable: Bool)
case end
@@ -131,6 +133,7 @@ enum WCallCommand: Equatable, Encodable, Decodable {
case offer
case answer
case iceCandidates
+ case session
case enable
case iceServers
case relay
@@ -174,9 +177,10 @@ enum WCallCommand: Equatable, Encodable, Decodable {
try container.encode("answer", forKey: .type)
try container.encode(answer, forKey: .answer)
try container.encode(iceCandidates, forKey: .iceCandidates)
- case let .ice(iceCandidates):
+ case let .ice(iceCandidates, session):
try container.encode("ice", forKey: .type)
try container.encode(iceCandidates, forKey: .iceCandidates)
+ try container.encodeIfPresent(session, forKey: .session)
case let .media(source, enable):
try container.encode("media", forKey: .type)
try container.encode(source, forKey: .media)
@@ -213,7 +217,8 @@ enum WCallCommand: Equatable, Encodable, Decodable {
self = .answer(answer: answer, iceCandidates: iceCandidates)
case "ice":
let iceCandidates = try container.decode(String.self, forKey: CodingKeys.iceCandidates)
- self = .ice(iceCandidates: iceCandidates)
+ let session = try container.decodeIfPresent(String.self, forKey: CodingKeys.session)
+ self = .ice(iceCandidates: iceCandidates, session: session)
case "media":
let source = try container.decode(CallMediaSource.self, forKey: CodingKeys.source)
let enable = try container.decode(Bool.self, forKey: CodingKeys.enable)
@@ -231,7 +236,7 @@ enum WCallResponse: Equatable, Decodable {
case capabilities(capabilities: CallCapabilities)
case offer(offer: String, iceCandidates: String, capabilities: CallCapabilities)
case answer(answer: String, iceCandidates: String)
- case ice(iceCandidates: String)
+ case ice(iceCandidates: String, session: String? = nil)
case connection(state: ConnectionState)
case connected(connectionInfo: ConnectionInfo)
case peerMedia(source: CallMediaSource, enabled: Bool)
@@ -246,6 +251,7 @@ enum WCallResponse: Equatable, Decodable {
case offer
case answer
case iceCandidates
+ case session
case state
case connectionInfo
case message
@@ -290,7 +296,8 @@ enum WCallResponse: Equatable, Decodable {
self = .answer(answer: answer, iceCandidates: iceCandidates)
case "ice":
let iceCandidates = try container.decode(String.self, forKey: CodingKeys.iceCandidates)
- self = .ice(iceCandidates: iceCandidates)
+ let session = try container.decodeIfPresent(String.self, forKey: CodingKeys.session)
+ self = .ice(iceCandidates: iceCandidates, session: session)
case "connection":
let state = try container.decode(ConnectionState.self, forKey: CodingKeys.state)
self = .connection(state: state)
@@ -333,9 +340,10 @@ extension WCallResponse: Encodable {
try container.encode("answer", forKey: .type)
try container.encode(answer, forKey: .answer)
try container.encode(iceCandidates, forKey: .iceCandidates)
- case let .ice(iceCandidates):
+ case let .ice(iceCandidates, session):
try container.encode("ice", forKey: .type)
try container.encode(iceCandidates, forKey: .iceCandidates)
+ try container.encodeIfPresent(session, forKey: .session)
case let .connection(state):
try container.encode("connection", forKey: .type)
try container.encode(state, forKey: .state)
diff --git a/apps/ios/Shared/Views/Call/WebRTCClient.swift b/apps/ios/Shared/Views/Call/WebRTCClient.swift
index 2ce04e4b80..7fb2feb15e 100644
--- a/apps/ios/Shared/Views/Call/WebRTCClient.swift
+++ b/apps/ios/Shared/Views/Call/WebRTCClient.swift
@@ -13,13 +13,12 @@ import SimpleXChat
final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDelegate, RTCFrameDecryptorDelegate {
private static let factory: RTCPeerConnectionFactory = {
RTCInitializeSSL()
- let videoEncoderFactory = RTCDefaultVideoEncoderFactory()
- let videoDecoderFactory = RTCDefaultVideoDecoderFactory()
- videoEncoderFactory.preferredCodec = RTCVideoCodecInfo(name: kRTCVp8CodecName)
- return RTCPeerConnectionFactory(encoderFactory: videoEncoderFactory, decoderFactory: videoDecoderFactory)
+ return RTCPeerConnectionFactory(encoderFactory: VP8EncoderFactory(), decoderFactory: VP8DecoderFactory())
}()
private static let ivTagBytes: Int = 28
private static let enableEncryption: Bool = true
+ private static let reconnectTimeout: UInt64 = 30_000_000_000
+ private static let iceRestartInterval: UInt64 = 10_000_000_000
private var chat_ctrl = getChatCtrl()
struct Call {
@@ -37,6 +36,9 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
var frameEncryptor: RTCFrameEncryptor?
var frameDecryptor: RTCFrameDecryptor?
var peerHasOldVersion: Bool
+ var wasConnected = false
+ var reconnection: Task? = nil
+ var iceRestarts: Task? = nil
}
struct NotConnectedCall {
@@ -61,6 +63,7 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
private let rtcAudioSession = RTCAudioSession.sharedInstance()
private let audioQueue = DispatchQueue(label: "chat.simplex.app.audio")
+ private let endCallLock = NSLock()
private var sendCallResponse: (WVAPIMessage) async -> Void
var activeCall: Call?
var notConnectedCall: NotConnectedCall?
@@ -117,7 +120,7 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
encryptor.delegate = self
frameEncryptor = encryptor
- let decryptor = RTCFrameDecryptor.init(sizeChange: -Int32(WebRTCClient.ivTagBytes))
+ let decryptor = RTCFrameDecryptor.init(sizeChange: 0)
decryptor.delegate = self
frameDecryptor = decryptor
}
@@ -257,11 +260,15 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
resp = .error(message: "answer: remote description is not set")
}
}
- case let .ice(iceCandidates):
+ case let .ice(iceCandidates, session):
if let pc = pc,
let remoteIceCandidates: [RTCIceCandidate] = decodeJSON(decompressFromBase64(input: iceCandidates)) {
- addIceCandidates(pc, remoteIceCandidates)
- resp = .ok
+ if let session {
+ resp = await receiveRestartSession(pc, session, remoteIceCandidates)
+ } else {
+ addIceCandidates(pc, remoteIceCandidates)
+ resp = .ok
+ }
} else {
resp = .error(message: "ice: call not started")
}
@@ -301,6 +308,101 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
}
}
+ private func startReconnecting(_ connection: RTCPeerConnection) async {
+ activeCall?.reconnection = Task {
+ _ = try? await Task.sleep(nanoseconds: WebRTCClient.reconnectTimeout)
+ if Task.isCancelled { return }
+ await sendConnectionState(connection, "disconnected")
+ endCall()
+ }
+ // Only the party that sent the initial offer restarts ICE, so that restart offers never collide
+ if connection.localDescription?.type == .offer {
+ activeCall?.iceRestarts = Task {
+ while !Task.isCancelled {
+ await restartIce(connection)
+ _ = try? await Task.sleep(nanoseconds: WebRTCClient.iceRestartInterval)
+ }
+ }
+ }
+ await sendConnectionState(connection, "reconnecting")
+ }
+
+ private func stopReconnecting() {
+ activeCall?.reconnection?.cancel()
+ activeCall?.reconnection = nil
+ activeCall?.iceRestarts?.cancel()
+ activeCall?.iceRestarts = nil
+ }
+
+ private func restartIce(_ connection: RTCPeerConnection) async {
+ // the previous restart offer is not answered yet
+ if connection.signalingState != .stable { return }
+ let (offer, error) = await connection.offer(iceRestart: true)
+ if let offer {
+ await sendRestartSession(offer)
+ } else {
+ logger.error("WebRTCClient: ICE restart error: \(error?.localizedDescription ?? "unknown error")")
+ }
+ }
+
+ private func receiveRestartSession(_ pc: RTCPeerConnection, _ session: String, _ remoteIceCandidates: [RTCIceCandidate]) async -> WCallResponse {
+ guard let desc: CustomRTCSessionDescription = decodeJSON(decompressFromBase64(input: session)),
+ let type = desc.type, let sdp = desc.sdp else {
+ return .error(message: "ice: invalid session")
+ }
+ let remoteDesc = RTCSessionDescription(type: type.toWebRTCSdpType(), sdp: sdp)
+ if type == .offer && pc.localDescription?.type != .offer {
+ if (try? await pc.setRemoteDescription(remoteDesc)) == nil {
+ return .error(message: "ice: remote offer is not set")
+ }
+ let (answer, error) = await pc.answer()
+ guard let answer else {
+ return .error(message: "ice: answer error: \(error?.localizedDescription ?? "unknown error")")
+ }
+ addIceCandidates(pc, remoteIceCandidates)
+ await sendRestartSession(answer)
+ } else if type == .answer && pc.signalingState == .haveLocalOffer {
+ if (try? await pc.setRemoteDescription(remoteDesc)) == nil {
+ return .error(message: "ice: remote answer is not set")
+ }
+ addIceCandidates(pc, remoteIceCandidates)
+ } else {
+ return .error(message: "ice: unexpected ICE restart \(type.rawValue)")
+ }
+ return .ok
+ }
+
+ private func sendRestartSession(_ desc: RTCSessionDescription) async {
+ await sendCallResponse(.init(
+ corrId: nil,
+ resp: .ice(
+ iceCandidates: compressToBase64(input: encodeJSON(await getInitialIceCandidates())),
+ session: compressToBase64(input: encodeJSON(CustomRTCSessionDescription(type: desc.type.toSdpType(), sdp: desc.sdp)))
+ ),
+ command: nil)
+ )
+ waitForMoreIceCandidates()
+ }
+
+ private func sendConnectionState(_ connection: RTCPeerConnection, _ connectionState: String) async {
+ guard let iceConnectionState = connection.iceConnectionState.toString(),
+ let iceGatheringState = connection.iceGatheringState.toString(),
+ let signalingState = connection.signalingState.toString()
+ else {
+ return
+ }
+ await sendCallResponse(.init(
+ corrId: nil,
+ resp: .connection(state: ConnectionState(
+ connectionState: connectionState,
+ iceConnectionState: iceConnectionState,
+ iceGatheringState: iceGatheringState,
+ signalingState: signalingState)
+ ),
+ command: nil)
+ )
+ }
+
// Spec: spec/services/calls.md#sendIceCandidates
func sendIceCandidates(_ candidates: [RTCIceCandidate]) async {
await self.sendCallResponse(.init(
@@ -387,7 +489,7 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
}
}
- func addLocalRenderer(_ renderer: RTCEAGLVideoView) {
+ func addLocalRenderer(_ renderer: RTCMTLVideoView) {
if let activeCall {
if let track = activeCall.localVideoTrack {
track.add(renderer)
@@ -401,7 +503,7 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
renderer.delegate = self
}
- func removeLocalRenderer(_ renderer: RTCEAGLVideoView) {
+ func removeLocalRenderer(_ renderer: RTCMTLVideoView) {
if let activeCall {
if let track = activeCall.localVideoTrack {
track.remove(renderer)
@@ -481,6 +583,21 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
}
}
}
+ setAudioSendersActive(pc)
+ }
+
+ // WebRTC starts an audio sender's stream without a track too, and sends the microphone on it unmuted (M156): the screen
+ // audio sender, which has no track, sent the microphone, also when it was muted. So only senders with a track are active.
+ func setAudioSendersActive(_ connection: RTCPeerConnection) {
+ for transceiver in connection.transceivers where transceiver.mediaType == .audio {
+ let sender = transceiver.sender
+ let active = sender.track != nil
+ let parameters = sender.parameters
+ if parameters.encodings.contains(where: { $0.isActive != active }) {
+ parameters.encodings.forEach { $0.isActive = active }
+ sender.parameters = parameters
+ }
+ }
}
func mediaSourceFromTransceiverMid(_ mid: String?) -> CallMediaSource {
@@ -508,13 +625,17 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
func frameDecryptor(_ decryptor: RTCFrameDecryptor, mediaType: RTCRtpMediaType, withFrame encrypted: Data) -> Data? {
guard encrypted.count > 0 else { return nil }
+ let isKeyFrame = encrypted[0] & 1 == 0
+ let clearTextBytesSize = mediaType.rawValue == 0 ? 1 : isKeyFrame ? 10 : 3
+ guard encrypted.count >= clearTextBytesSize + WebRTCClient.ivTagBytes else { return nil }
if var key: [CChar] = activeCall?.aesKey?.cString(using: .utf8),
let pointer: UnsafeMutableRawPointer = malloc(encrypted.count) {
memcpy(pointer, (encrypted as NSData).bytes, encrypted.count)
- let isKeyFrame = encrypted[0] & 1 == 0
- let clearTextBytesSize = mediaType.rawValue == 0 ? 1 : isKeyFrame ? 10 : 3
- logCrypto("decrypt", chat_decrypt_media(&key, pointer.advanced(by: clearTextBytesSize), Int32(encrypted.count - clearTextBytesSize)))
- return Data(bytes: pointer, count: encrypted.count - WebRTCClient.ivTagBytes)
+ guard checkCrypto("decrypt", chat_decrypt_media(&key, pointer.advanced(by: clearTextBytesSize), Int32(encrypted.count - clearTextBytesSize))) else {
+ free(pointer)
+ return nil
+ }
+ return Data(bytesNoCopy: pointer, count: encrypted.count - WebRTCClient.ivTagBytes, deallocator: .free)
} else {
return nil
}
@@ -522,27 +643,30 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
func frameEncryptor(_ encryptor: RTCFrameEncryptor, mediaType: RTCRtpMediaType, withFrame unencrypted: Data) -> Data? {
guard unencrypted.count > 0 else { return nil }
+ let isKeyFrame = unencrypted[0] & 1 == 0
+ let clearTextBytesSize = mediaType.rawValue == 0 ? 1 : isKeyFrame ? 10 : 3
+ guard unencrypted.count >= clearTextBytesSize else { return nil }
if var key: [CChar] = activeCall?.aesKey?.cString(using: .utf8),
let pointer: UnsafeMutableRawPointer = malloc(unencrypted.count + WebRTCClient.ivTagBytes) {
memcpy(pointer, (unencrypted as NSData).bytes, unencrypted.count)
- let isKeyFrame = unencrypted[0] & 1 == 0
- let clearTextBytesSize = mediaType.rawValue == 0 ? 1 : isKeyFrame ? 10 : 3
- logCrypto("encrypt", chat_encrypt_media(chat_ctrl, &key, pointer.advanced(by: clearTextBytesSize), Int32(unencrypted.count + WebRTCClient.ivTagBytes - clearTextBytesSize)))
- return Data(bytes: pointer, count: unencrypted.count + WebRTCClient.ivTagBytes)
+ guard checkCrypto("encrypt", chat_encrypt_media(chat_ctrl, &key, pointer.advanced(by: clearTextBytesSize), Int32(unencrypted.count + WebRTCClient.ivTagBytes - clearTextBytesSize))) else {
+ free(pointer)
+ return nil
+ }
+ return Data(bytesNoCopy: pointer, count: unencrypted.count + WebRTCClient.ivTagBytes, deallocator: .free)
} else {
return nil
}
}
- private func logCrypto(_ op: String, _ r: UnsafeMutablePointer?) {
- if let r = r {
- let err = fromCString(r)
- if err != "" {
- logger.error("\(op) error: \(err)")
-// } else {
-// logger.debug("\(op) ok")
- }
+ private func checkCrypto(_ op: String, _ r: UnsafeMutablePointer?) -> Bool {
+ guard let r = r else { return true }
+ let err = fromCString(r)
+ if err != "" {
+ logger.error("\(op) error: \(err)")
+ return false
}
+ return true
}
func addRemoteCameraRenderer(_ renderer: RTCVideoRenderer) {
@@ -581,7 +705,7 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
func startCaptureLocalVideo(_ device: AVCaptureDevice.Position?, _ capturer: RTCVideoCapturer?) {
#if targetEnvironment(simulator)
guard
- let capturer = (activeCall?.localCamera ?? notConnectedCall?.localCameraAndTrack?.0) as? RTCFileVideoCapturer
+ let capturer = (capturer ?? activeCall?.localCamera ?? notConnectedCall?.localCameraAndTrack?.0) as? RTCFileVideoCapturer
else {
logger.error("Unable to work with a file capturer")
return
@@ -653,15 +777,22 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
private func _endCall() {
(notConnectedCall?.localCameraAndTrack?.0 as? RTCCameraVideoCapturer)?.stopCapture()
- guard let call = activeCall else { return }
+ // The end command and the call view ending it on disappearing both end the call: closing the connection from
+ // both at once froze the app (CI run 41311546712), so only the first takes the call.
+ endCallLock.lock()
+ let call = activeCall
+ activeCall = nil
+ endCallLock.unlock()
+ guard let call else { return }
logger.debug("WebRTCClient: ending the call")
+ call.reconnection?.cancel()
+ call.iceRestarts?.cancel()
call.connection.close()
call.connection.delegate = nil
call.frameEncryptor?.delegate = nil
call.frameDecryptor?.delegate = nil
(call.localCamera as? RTCCameraVideoCapturer)?.stopCapture()
audioSessionToDefaults()
- activeCall = nil
}
func untilIceComplete(timeoutMs: UInt64, stepMs: UInt64, action: @escaping () async -> Void) async {
@@ -676,16 +807,18 @@ final class WebRTCClient: NSObject, RTCVideoViewDelegate, RTCFrameEncryptorDeleg
extension WebRTC.RTCPeerConnection {
- func mediaConstraints() -> RTCMediaConstraints {
- RTCMediaConstraints(
- mandatoryConstraints: [kRTCMediaConstraintsOfferToReceiveAudio: kRTCMediaConstraintsValueTrue,
- kRTCMediaConstraintsOfferToReceiveVideo: kRTCMediaConstraintsValueTrue],
- optionalConstraints: nil)
+ func mediaConstraints(iceRestart: Bool = false) -> RTCMediaConstraints {
+ var constraints = [kRTCMediaConstraintsOfferToReceiveAudio: kRTCMediaConstraintsValueTrue,
+ kRTCMediaConstraintsOfferToReceiveVideo: kRTCMediaConstraintsValueTrue]
+ if iceRestart {
+ constraints[kRTCMediaConstraintsIceRestart] = kRTCMediaConstraintsValueTrue
+ }
+ return RTCMediaConstraints(mandatoryConstraints: constraints, optionalConstraints: nil)
}
- func offer() async -> (RTCSessionDescription?, Error?) {
+ func offer(iceRestart: Bool = false) async -> (RTCSessionDescription?, Error?) {
await withCheckedContinuation { cont in
- offer(for: mediaConstraints()) { (sdp, error) in
+ offer(for: mediaConstraints(iceRestart: iceRestart)) { (sdp, error) in
self.processSDP(cont, sdp, error)
}
}
@@ -764,24 +897,20 @@ extension WebRTCClient: RTCPeerConnectionDelegate {
func peerConnection(_ connection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {
debugPrint("Connection new connection state: \(newState.toString() ?? "" + newState.rawValue.description) \(connection.receivers)")
- guard let connectionStateString = newState.toString(),
- let iceConnectionStateString = connection.iceConnectionState.toString(),
- let iceGatheringStateString = connection.iceGatheringState.toString(),
- let signalingStateString = connection.signalingState.toString()
- else {
- return
- }
+ guard let connectionStateString = newState.toString() else { return }
Task {
- await sendCallResponse(.init(
- corrId: nil,
- resp: .connection(state: ConnectionState(
- connectionState: connectionStateString,
- iceConnectionState: iceConnectionStateString,
- iceGatheringState: iceGatheringStateString,
- signalingState: signalingStateString)
- ),
- command: nil)
- )
+ if activeCall?.wasConnected == true && ChatModel.shared.activeCall?.contact.callReconnectSupported == true {
+ switch newState {
+ case .disconnected, .failed:
+ if activeCall?.reconnection == nil {
+ await startReconnecting(connection)
+ }
+ return
+ case .new, .checking: return
+ default: ()
+ }
+ }
+ await sendConnectionState(connection, connectionStateString)
switch newState {
case .checking:
@@ -790,7 +919,10 @@ extension WebRTCClient: RTCPeerConnectionDelegate {
}
let enableSpeaker: Bool = ChatModel.shared.activeCall?.localMediaSources.hasVideo == true
setSpeakerEnabledAndConfigureSession(enableSpeaker)
- case .connected: sendConnectedEvent(connection)
+ case .connected:
+ stopReconnecting()
+ activeCall?.wasConnected = true
+ sendConnectedEvent(connection)
case .disconnected, .failed: endCall()
default: ()
}
@@ -905,16 +1037,16 @@ extension WebRTCClient {
do {
let hasExternalAudioDevice = self.rtcAudioSession.session.hasExternalAudioDevice()
if enabled {
- try self.rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord.rawValue, with: [.defaultToSpeaker, .allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
- try self.rtcAudioSession.setMode(AVAudioSession.Mode.videoChat.rawValue)
+ try self.rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord, with: [.defaultToSpeaker, .allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
+ try self.rtcAudioSession.setMode(AVAudioSession.Mode.videoChat)
if hasExternalAudioDevice && !skipExternalDevice, let preferred = self.rtcAudioSession.session.preferredInputDevice() {
try self.rtcAudioSession.setPreferredInput(preferred)
} else {
try self.rtcAudioSession.overrideOutputAudioPort(.speaker)
}
} else {
- try self.rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord.rawValue, with: [.allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
- try self.rtcAudioSession.setMode(AVAudioSession.Mode.voiceChat.rawValue)
+ try self.rtcAudioSession.setCategory(AVAudioSession.Category.playAndRecord, with: [.allowBluetooth, .allowAirPlay, .allowBluetoothA2DP])
+ try self.rtcAudioSession.setMode(AVAudioSession.Mode.voiceChat)
try self.rtcAudioSession.overrideOutputAudioPort(.none)
}
if hasExternalAudioDevice && !skipExternalDevice {
@@ -937,8 +1069,8 @@ extension WebRTCClient {
self.rtcAudioSession.unlockForConfiguration()
}
do {
- try self.rtcAudioSession.setCategory(AVAudioSession.Category.ambient.rawValue)
- try self.rtcAudioSession.setMode(AVAudioSession.Mode.default.rawValue)
+ try self.rtcAudioSession.setCategory(AVAudioSession.Category.ambient)
+ try self.rtcAudioSession.setMode(AVAudioSession.Mode.default)
try self.rtcAudioSession.overrideOutputAudioPort(.none)
try self.rtcAudioSession.setActive(false)
logger.debug("WebRTCClient: audioSession to defaults success")
@@ -953,6 +1085,9 @@ extension WebRTCClient {
if activeCall != nil {
activeCall?.localAudioTrack = enabled ? createAudioTrack() : nil
activeCall?.connection.transceivers.first(where: { t in mediaSourceFromTransceiverMid(t.mid) == .mic })?.sender.track = activeCall?.localAudioTrack
+ if let connection = activeCall?.connection {
+ setAudioSendersActive(connection)
+ }
} else if notConnectedCall != nil {
notConnectedCall?.audioTrack = enabled ? createAudioTrack() : nil
}
@@ -1137,3 +1272,17 @@ extension RTCSignalingState {
}
}
}
+
+// The frame encryption leaves only VP8's header in the clear for WebRTC's packetizer, so calls send and receive VP8 alone:
+// with the default factories two apps on WebRTC M156 chose H.264, and no video arrived.
+private final class VP8EncoderFactory: NSObject, RTCVideoEncoderFactory {
+ func createEncoder(_ info: RTCVideoCodecInfo) -> RTCVideoEncoder? { RTCVideoEncoderVP8.vp8Encoder() }
+
+ func supportedCodecs() -> [RTCVideoCodecInfo] { RTCVideoEncoderVP8.supportedCodecs() }
+}
+
+private final class VP8DecoderFactory: NSObject, RTCVideoDecoderFactory {
+ func createDecoder(_ info: RTCVideoCodecInfo) -> RTCVideoDecoder? { RTCVideoDecoderVP8.vp8Decoder() }
+
+ func supportedCodecs() -> [RTCVideoCodecInfo] { RTCVideoDecoderVP8.supportedCodecs() }
+}
diff --git a/apps/ios/Shared/Views/Chat/ChatInfoView.swift b/apps/ios/Shared/Views/Chat/ChatInfoView.swift
index 3d1e7ef477..24e708152d 100644
--- a/apps/ios/Shared/Views/Chat/ChatInfoView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatInfoView.swift
@@ -370,7 +370,8 @@ struct ChatInfoView: View {
VStack(spacing: 8) {
let cInfo = chat.chatInfo
ChatInfoImage(chat: chat, size: 192, color: Color(uiColor: .tertiarySystemFill))
- .padding(.vertical, 12)
+ .padding(.top, 20)
+ .padding(.bottom, 12)
// show actual display name, alias can be edited in this view
let displayName = contact.profile.displayName.trimmingCharacters(in: .whitespacesAndNewlines)
let fullName = cInfo.fullName.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -950,10 +951,12 @@ struct ChatWallpaperEditorSheet: View {
themeModeOverride: initialTheme,
applyToMode: themes.light == themes.dark ? nil : initialTheme.mode,
globalThemeUsed: $globalThemeUsed,
+ layoutSection: AnyView(ChatLayoutSection(chatInfo: chat.chatInfo, setChatLayout: setChatLayout)),
save: { applyToMode, newTheme in
await save(applyToMode, newTheme, $chat)
}
)
+ .environment(\.terminalLayout, chat.chatInfo.activeChatLayout(profileChatLayout(ChatModel.shared.currentUser)) == .terminal)
.navigationTitle("Chat theme")
.modifier(ThemedBackground(grouped: true))
.navigationBarTitleDisplayMode(.inline)
@@ -978,6 +981,29 @@ struct ChatWallpaperEditorSheet: View {
}
}
+ private func setChatLayout(_ layout: ChatLayout?) {
+ let changedThemes = themesFromChat(chat).withChatLayout(layout)
+ Task {
+ if await apiSetChatUIThemes(chatId: chat.id, themes: changedThemes) {
+ await MainActor.run {
+ if case var ChatInfo.direct(contact) = chat.chatInfo {
+ contact.uiThemes = changedThemes
+ updateChatInfo(ChatInfo.direct(contact: contact))
+ } else if case var ChatInfo.group(groupInfo, _) = chat.chatInfo {
+ groupInfo.uiThemes = changedThemes
+ updateChatInfo(ChatInfo.group(groupInfo: groupInfo, groupChatScope: nil))
+ }
+ }
+ }
+ }
+ }
+
+ private func updateChatInfo(_ chatInfo: ChatInfo) {
+ ChatModel.shared.updateChatInfo(chatInfo)
+ chat = Chat(chatInfo: chatInfo)
+ themes = themesFromChat(chat)
+ }
+
private static var updateBackendTask: Task = Task {}
private func save(
_ applyToMode: DefaultThemeMode?,
@@ -1023,14 +1049,14 @@ struct ChatWallpaperEditorSheet: View {
let filePath = saveWallpaperFile(url: getWallpaperFilePath(imageFile))
if currentMode == DefaultThemeMode.light {
dark.wallpaper?.imageFile = filePath
- changedThemes = ThemeModeOverrides(light: changedThemes?.light, dark: dark)
+ changedThemes?.dark = dark
} else {
light.wallpaper?.imageFile = filePath
- changedThemes = ThemeModeOverrides(light: light, dark: changedThemes?.dark)
+ changedThemes?.light = light
}
}
} else {
- changedThemes = nil
+ changedThemes = changedThemes?.layoutOnly()
}
wallpaperFiles.remove(changedThemes?.light?.wallpaper?.imageFile)
wallpaperFiles.remove(changedThemes?.dark?.wallpaper?.imageFile)
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CICallItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CICallItemView.swift
index e5f3c05eed..1496ab5046 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CICallItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CICallItemView.swift
@@ -20,26 +20,34 @@ struct CICallItemView: View {
var body: some View {
let sent = chatItem.chatDir.sent
- VStack(spacing: 4) {
- switch status {
- case .pending:
- if sent {
- Image(systemName: "phone.arrow.up.right").foregroundColor(theme.colors.secondary)
- } else {
- acceptCallButton()
- }
- case .missed: missedCallIcon(sent).foregroundColor(.red)
- case .rejected: Image(systemName: "phone.down").foregroundColor(.red)
- case .accepted: connectingCallIcon()
- case .negotiated: connectingCallIcon()
- case .progress: Image(systemName: "phone.and.waveform.fill").foregroundColor(.green)
- case .ended: endedCallIcon(sent)
- case .error: missedCallIcon(sent).foregroundColor(.orange)
- }
-
+ ItemWithMeta {
CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary, showStatus: false, showEdited: false)
- .padding(.bottom, 8)
- .padding(.horizontal, 12)
+ } content: { inlineMeta in
+ VStack(spacing: 4) {
+ switch status {
+ case .pending:
+ if sent {
+ Image(systemName: "phone.arrow.up.right").foregroundColor(theme.colors.secondary)
+ } else {
+ acceptCallButton()
+ }
+ case .missed: missedCallIcon(sent).foregroundColor(.red)
+ case .rejected: Image(systemName: "phone.down").foregroundColor(.red)
+ case .accepted: connectingCallIcon()
+ case .negotiated: connectingCallIcon()
+ case .progress: Image(systemName: "phone.and.waveform.fill").foregroundColor(.green)
+ case .ended: endedCallIcon(sent)
+ case .error: missedCallIcon(sent).foregroundColor(.orange)
+ }
+
+ if let inlineMeta {
+ inlineMeta
+ .padding(.bottom, 8)
+ .padding(.horizontal, 12)
+ }
+ }
+ .padding(.leading, inlineMeta == nil ? chatItemTextPadding : 0)
+ .padding(.bottom, inlineMeta == nil ? 8 : 0)
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIChatFeatureView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIChatFeatureView.swift
index 5521470d07..75a7222eb4 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIChatFeatureView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIChatFeatureView.swift
@@ -14,6 +14,7 @@ import SimpleXChat
struct CIChatFeatureView: View {
@EnvironmentObject var m: ChatModel
@Environment(\.revealed) var revealed: Bool
+ @Environment(\.terminalLayout) private var terminal
@ObservedObject var chat: Chat
@ObservedObject var im: ItemsModel
@EnvironmentObject var theme: AppTheme
@@ -27,8 +28,8 @@ struct CIChatFeatureView: View {
HStack {
ForEach(fs, content: featureIconView)
}
- .padding(.horizontal, 6)
- .padding(.vertical, 6)
+ .if(terminal) { $0.frame(height: terminalLineHeight(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
+ .padding(terminal ? terminalEventPadding : EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6))
} else {
fullFeatureView
}
@@ -93,15 +94,18 @@ struct CIChatFeatureView: View {
}
private var fullFeatureView: some View {
- HStack(alignment: .bottom, spacing: 4) {
- Image(systemName: icon ?? feature.iconFilled)
- .foregroundColor(iconColor)
- .scaleEffect(feature.iconScale)
- chatEventText(chatItem, theme.colors.secondary)
+ ChatEventWithMeta(chatItem: chatItem) { ts in
+ HStack(alignment: terminal ? .center : .bottom, spacing: 4) {
+ Image(systemName: icon ?? feature.iconFilled)
+ .foregroundColor(iconColor)
+ .scaleEffect(feature.iconScale)
+ .if(terminal) { $0.frame(height: 0) }
+ chatEventText(chatItem, theme.colors.secondary, ts: terminal ? ts : textSpace + ts)
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
+ }
+ .padding(terminal ? terminalEventPadding : EdgeInsets(top: 4, leading: 6, bottom: 4, trailing: 6))
+ .textSelection(.disabled)
}
- .padding(.horizontal, 6)
- .padding(.vertical, 4)
- .textSelection(.disabled)
}
}
@@ -111,7 +115,7 @@ struct CIChatFeatureView_Previews: PreviewProvider {
CIChatFeatureView(
chat: Chat.sampleData,
im: ItemsModel.shared,
- chatItem: ChatItem.getChatFeatureSample(.fullDelete, enabled), feature: ChatFeature.fullDelete, iconColor: enabled.iconColor(.secondary)
+ chatItem: previewDated(ChatItem.getChatFeatureSample(.fullDelete, enabled)), feature: ChatFeature.fullDelete, iconColor: enabled.iconColor(.secondary)
).environment(\.revealed, true)
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIChatLinkHeader.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIChatLinkHeader.swift
index aaaa29929d..a5e87c3eb2 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIChatLinkHeader.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIChatLinkHeader.swift
@@ -4,6 +4,7 @@ import SimpleXChat
struct CIChatLinkHeader: View {
@EnvironmentObject var theme: AppTheme
@Environment(\.showTimestamp) var showTimestamp: Bool
+ @Environment(\.terminalLayout) private var terminal
var chatItem: ChatItem
var chatLink: MsgChatLink
var ownerSig: LinkOwnerSig?
@@ -32,7 +33,7 @@ struct CIChatLinkHeader: View {
.foregroundColor(theme.colors.secondary)
.padding(.bottom, 2)
let t = Text("Tap to open").foregroundColor(theme.colors.primary).font(.callout)
- if hasText {
+ if hasText || terminal {
t
} else {
t
@@ -50,7 +51,7 @@ struct CIChatLinkHeader: View {
HStack(alignment: .top) {
ProfileImage(
imageStr: chatLink.image,
- iconName: chatLink.iconName,
+ icon: Image(systemName: chatLink.iconName),
size: 44,
color: Color(uiColor: .tertiaryLabel)
)
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIEventView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIEventView.swift
index 49a086d45a..bbf361c5de 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIEventView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIEventView.swift
@@ -12,14 +12,16 @@ import SimpleXChat
// Spec: spec/client/chat-view.md#CIEventView
struct CIEventView: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var eventText: Text
var body: some View {
eventText
- .padding(.horizontal, 6)
- .padding(.vertical, 4)
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
+ .padding(terminal ? terminalEventPadding : EdgeInsets(top: 4, leading: 6, bottom: 4, trailing: 6))
.textSelection(.disabled)
- .lineLimit(4)
+ .lineLimit(terminal ? nil : 4)
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIFeaturePreferenceView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIFeaturePreferenceView.swift
index dcd6ea579c..a334dc45df 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIFeaturePreferenceView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIFeaturePreferenceView.swift
@@ -14,33 +14,37 @@ import SimpleXChat
struct CIFeaturePreferenceView: View {
@ObservedObject var chat: Chat
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var chatItem: ChatItem
var feature: ChatFeature
var allowed: FeatureAllowed
var param: Int?
var body: some View {
- HStack(alignment: .center, spacing: 4) {
- Image(systemName: feature.icon)
- .foregroundColor(theme.colors.secondary)
- .scaleEffect(feature.iconScale)
- if let ct = chat.chatInfo.contact,
- allowed != .no && ct.allowsFeature(feature) && !ct.userAllowsFeature(feature) {
- let setParam = feature == .timedMessages && ct.mergedPreferences.timedMessages.userPreference.preference.ttl == nil
- featurePreferenceView(acceptText: setParam ? "Set 1 day" : "Accept")
- .simultaneousGesture(TapGesture().onEnded {
- allowFeatureToContact(ct, feature, param: setParam ? 86400 : nil)
- })
- } else {
- featurePreferenceView()
+ ChatEventWithMeta(chatItem: chatItem) { ts in
+ HStack(alignment: .center, spacing: 4) {
+ Image(systemName: feature.icon)
+ .foregroundColor(theme.colors.secondary)
+ .scaleEffect(feature.iconScale)
+ .if(terminal) { $0.frame(height: 0) }
+ if let ct = chat.chatInfo.contact,
+ allowed != .no && ct.allowsFeature(feature) && !ct.userAllowsFeature(feature) {
+ let setParam = feature == .timedMessages && ct.mergedPreferences.timedMessages.userPreference.preference.ttl == nil
+ featurePreferenceView(acceptText: setParam ? "Set 1 day" : "Accept", ts: ts)
+ .simultaneousGesture(TapGesture().onEnded {
+ allowFeatureToContact(ct, feature, param: setParam ? 86400 : nil)
+ })
+ } else {
+ featurePreferenceView(ts: ts)
+ }
}
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
+ .padding(terminal ? terminalEventPadding : EdgeInsets(top: 0, leading: 6, bottom: 6, trailing: 0))
+ .textSelection(.disabled)
}
- .padding(.leading, 6)
- .padding(.bottom, 6)
- .textSelection(.disabled)
}
- private func featurePreferenceView(acceptText: LocalizedStringKey? = nil) -> some View {
+ private func featurePreferenceView(acceptText: LocalizedStringKey? = nil, ts: Text) -> some View {
var r = Text(CIContent.preferenceText(feature, allowed, param) + " ")
.fontWeight(.light)
.foregroundColor(theme.colors.secondary)
@@ -51,7 +55,7 @@ struct CIFeaturePreferenceView: View {
.foregroundColor(theme.colors.primary)
+ Text(verbatim: " ")
}
- r = r + chatItem.timestampText
+ r = r + ts
.fontWeight(.light)
.foregroundColor(theme.colors.secondary)
return r.font(.caption)
@@ -78,7 +82,7 @@ struct CIFeaturePreferenceView_Previews: PreviewProvider {
let content = CIContent.rcvChatPreference(feature: .timedMessages, allowed: .yes, param: 30)
let chatItem = ChatItem(
chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, content.text, .rcvRead),
+ meta: CIMeta.getSample(1, previewDate, content.text, .rcvRead),
content: content,
quotedItem: nil,
file: nil
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift
index 8bb76ca155..a71cdeb4dc 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIFileView.swift
@@ -15,6 +15,7 @@ struct CIFileView: View {
@EnvironmentObject var m: ChatModel
@EnvironmentObject var theme: AppTheme
@Environment(\.showTimestamp) var showTimestamp: Bool
+ @Environment(\.terminalLayout) private var terminal
@AppStorage(DEFAULT_SHOW_SENT_VIA_RPOXY) private var showSentViaProxy = false
@AppStorage(DEFAULT_PRIVACY_SHOW_SIGNATURE) private var showSignature = true
@AppStorage(DEFAULT_PRIVACY_SHOW_FILE_ENCRYPTION) private var showFileEncryption = true
@@ -26,14 +27,14 @@ struct CIFileView: View {
var body: some View {
if smallViewSize != nil {
fileIndicator()
- .simultaneousGesture(TapGesture().onEnded(fileAction))
+ .simultaneousGesture(TapGesture().onEnded { fileAction(file) })
} else {
// reserve exact space for the overlaid meta (timestamp + all icons), rendered transparently - matches MsgContentView
let encrypted: Bool? = if let fileSource = file?.fileSource { fileSource.cryptoArgs != nil } else { nil }
let metaReserve = Text(verbatim: " ") + ciMetaText(meta, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: encrypted, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, signedFileVerified: file?.loaded, showSignature: showSignature, showFileEncryption: showFileEncryption)
HStack(alignment: .bottom, spacing: 6) {
fileIndicator()
- .padding(.top, 5)
+ .padding(.top, terminal ? 0 : 5)
.padding(.bottom, 3)
if let file = file {
let prettyFileSize = ByteCountFormatter.string(fromByteCount: file.fileSize, countStyle: .binary)
@@ -52,11 +53,11 @@ struct CIFileView: View {
metaReserve.font(.caption)
}
}
- .padding(.top, 4)
- .padding(.bottom, 6)
+ .padding(.top, terminal ? 0 : 4)
+ .padding(.bottom, terminal ? 0 : 6)
.padding(.leading, 10)
.padding(.trailing, 12)
- .simultaneousGesture(TapGesture().onEnded(fileAction))
+ .simultaneousGesture(TapGesture().onEnded { fileAction(file) })
.disabled(!itemInteractive)
}
}
@@ -85,7 +86,7 @@ struct CIFileView: View {
return false
}
- private func fileAction() {
+ private func fileAction(_ file: CIFile?) {
logger.debug("CIFileView fileAction")
if let file = file {
switch (file.fileStatus) {
@@ -93,6 +94,7 @@ struct CIFileView: View {
if let prohibited = file.fileProhibited {
showProhibitedFileAlert(file, prohibited)
} else {
+ m.openWhenReceived(file) { fileAction($0) }
Task {
logger.debug("CIFileView fileAction - in .rcvInvitation, .rcvAborted, in Task")
if let user = m.currentUser {
@@ -117,7 +119,7 @@ struct CIFileView: View {
case .rcvComplete:
logger.debug("CIFileView fileAction - in .rcvComplete")
if let fileSource = getLoadedFileSource(file) {
- saveCryptoFile(fileSource)
+ openFile(file, fileSource)
}
case let .rcvError(rcvFileError):
logger.debug("CIFileView fileAction - in .rcvError")
@@ -128,12 +130,12 @@ struct CIFileView: View {
case .sndStored:
logger.debug("CIFileView fileAction - in .sndStored")
if file.fileProtocol == .local, let fileSource = getLoadedFileSource(file) {
- saveCryptoFile(fileSource)
+ openFile(file, fileSource)
}
case .sndComplete:
logger.debug("CIFileView fileAction - in .sndComplete")
if let fileSource = getLoadedFileSource(file) {
- saveCryptoFile(fileSource)
+ openFile(file, fileSource)
}
case let .sndError(sndFileError):
logger.debug("CIFileView fileAction - in .sndError")
@@ -146,6 +148,14 @@ struct CIFileView: View {
}
}
+ private func openFile(_ file: CIFile, _ fileSource: CryptoFile) {
+ if isMarkdownFile(file) {
+ showMarkdownFile(file)
+ } else {
+ saveCryptoFile(fileSource)
+ }
+ }
+
@ViewBuilder private func fileIndicator() -> some View {
if let file = file {
switch file.fileStatus {
@@ -307,29 +317,37 @@ struct CIFileView_Previews: PreviewProvider {
let im = ItemsModel.shared
let sentFile: ChatItem = ChatItem(
chatDir: .directSnd,
- meta: CIMeta.getSample(1, .now, "", .sndSent(sndProgress: .complete), itemEdited: true),
+ meta: CIMeta.getSample(1, previewDate, "", .sndSent(sndProgress: .complete), itemEdited: true),
content: .sndMsgContent(msgContent: .file("")),
quotedItem: nil,
file: CIFile.getSample(fileStatus: .sndComplete)
)
let fileChatItemWtFile = ChatItem(
chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "", .rcvRead),
+ meta: CIMeta.getSample(1, previewDate, "", .rcvRead),
content: .rcvMsgContent(msgContent: .file("")),
quotedItem: nil,
file: nil
)
Group {
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(fileName: "some_long_file_name_here", fileStatus: .rcvInvitation), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(fileStatus: .rcvAccepted), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(fileStatus: .rcvCancelled), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(fileSize: 1_000_000_000, fileStatus: .rcvInvitation), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(text: "Hello there", fileStatus: .rcvInvitation), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getFileMsgContentSample(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", fileStatus: .rcvInvitation), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: fileChatItemWtFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(sentFile, tailVisible: true))
+ let ci1 = previewDated(ChatItem.getFileMsgContentSample())
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = previewDated(ChatItem.getFileMsgContentSample(fileName: "some_long_file_name_here", fileStatus: .rcvInvitation))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = previewDated(ChatItem.getFileMsgContentSample(fileStatus: .rcvAccepted))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = previewDated(ChatItem.getFileMsgContentSample(fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci4, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = previewDated(ChatItem.getFileMsgContentSample(fileStatus: .rcvCancelled))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci5, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci5, tailVisible: true))
+ let ci6 = previewDated(ChatItem.getFileMsgContentSample(fileSize: 1_000_000_000, fileStatus: .rcvInvitation))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci6, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci6, tailVisible: true))
+ let ci7 = previewDated(ChatItem.getFileMsgContentSample(text: "Hello there", fileStatus: .rcvInvitation))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci7, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci7, tailVisible: true))
+ let ci8 = previewDated(ChatItem.getFileMsgContentSample(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", fileStatus: .rcvInvitation))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci8, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci8, tailVisible: true))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: fileChatItemWtFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(fileChatItemWtFile, tailVisible: true))
}
.environment(\.revealed, false)
.previewLayout(.fixed(width: 360, height: 360))
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIGroupInvitationView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIGroupInvitationView.swift
index ddb58fdfd1..e2bdb5786a 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIGroupInvitationView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIGroupInvitationView.swift
@@ -28,51 +28,63 @@ struct CIGroupInvitationView: View {
var body: some View {
let action = !chatItem.chatDir.sent && groupInvitation.status == .pending
- let v = ZStack(alignment: .bottomTrailing) {
- ZStack {
- VStack(alignment: .leading) {
- groupInfoView(action)
- .padding(.horizontal, 2)
- .padding(.top, 8)
- .padding(.bottom, 6)
- .overlay(DetermineWidth())
+ let v = ItemWithMeta {
+ CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary, showStatus: false, showEdited: false)
+ } content: { inlineMeta in
+ ZStack(alignment: Alignment(horizontal: .trailing, vertical: .lastTextBaseline)) {
+ ZStack {
+ VStack(alignment: .leading) {
+ groupInfoView(action)
+ .padding(.horizontal, 2)
+ .padding(.top, 8)
+ .padding(.bottom, 6)
+ .overlay(DetermineWidth())
- Divider().frame(width: frameWidth)
+ Divider().frame(width: frameWidth)
- if action {
- VStack(alignment: .leading, spacing: 2) {
- groupInvitationText()
+ if chat.chatInfo.groupInfo != nil {
+ Text(chatItem.chatDir.sent ? String.localizedStringWithFormat(NSLocalizedString("For %@ only", comment: ""), groupInvitation.localDisplayName) : NSLocalizedString("For you only", comment: ""))
+ .font(.caption)
+ .foregroundColor(theme.colors.secondary)
.overlay(DetermineWidth())
+ }
+
+ if action {
+ VStack(alignment: .leading, spacing: 2) {
+ groupInvitationText()
+ .overlay(DetermineWidth())
+ (
+ Text(chatIncognito ? "Tap to join incognito" : "Tap to join")
+ .foregroundColor(inProgress ? theme.colors.secondary : chatIncognito ? .indigo : theme.colors.primary)
+ .font(.callout)
+ + metaReserve(inlineMeta)
+ )
+ .overlay(DetermineWidth())
+ }
+ } else {
(
- Text(chatIncognito ? "Tap to join incognito" : "Tap to join")
- .foregroundColor(inProgress ? theme.colors.secondary : chatIncognito ? .indigo : theme.colors.primary)
- .font(.callout)
- + Text(verbatim: " ")
- + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showStatus: false, showEdited: false, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
+ groupInvitationText()
+ + metaReserve(inlineMeta)
)
.overlay(DetermineWidth())
}
- } else {
- (
- groupInvitationText()
- + Text(verbatim: " ")
- + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showStatus: false, showEdited: false, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
- )
- .overlay(DetermineWidth())
+ }
+ .padding(.bottom, 2)
+
+ if progressByTimeout {
+ ProgressView().scaleEffect(2)
}
}
- .padding(.bottom, 2)
- if progressByTimeout {
- ProgressView().scaleEffect(2)
+ if let inlineMeta {
+ inlineMeta
}
}
-
- CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary, showStatus: false, showEdited: false)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
+ .if(inlineMeta == nil) { $0.modifier(ChatItemClipped(chatItem, tailVisible: false)) }
}
- .padding(.horizontal, 12)
- .padding(.vertical, 6)
- .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
.textSelection(.disabled)
.onPreferenceChange(DetermineWidth.Key.self) { frameWidth = $0 }
.onChange(of: inProgress) { inProgress in
@@ -108,7 +120,7 @@ struct CIGroupInvitationView: View {
return HStack(alignment: .top) {
ProfileImage(
imageStr: groupInvitation.groupProfile.image,
- iconName: "person.2.circle.fill",
+ icon: Image(systemName: "person.2.circle.fill"),
size: 44,
color: color
)
@@ -129,6 +141,12 @@ struct CIGroupInvitationView: View {
.font(.callout)
}
+ private func metaReserve(_ inlineMeta: CIMetaView?) -> Text {
+ inlineMeta == nil
+ ? Text(verbatim: "")
+ : Text(verbatim: " ") + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showStatus: false, showEdited: false, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
+ }
+
private func groupInvitationStr() -> LocalizedStringKey {
if chatItem.chatDir.sent {
return "You sent group invitation"
@@ -146,8 +164,9 @@ struct CIGroupInvitationView: View {
struct CIGroupInvitationView_Previews: PreviewProvider {
static var previews: some View {
Group {
- CIGroupInvitationView(chat: Chat.sampleData, chatItem: ChatItem.getGroupInvitationSample(), groupInvitation: CIGroupInvitation.getSample(groupProfile: GroupProfile(displayName: "team", fullName: "team")), memberRole: .admin)
- CIGroupInvitationView(chat: Chat.sampleData, chatItem: ChatItem.getGroupInvitationSample(), groupInvitation: CIGroupInvitation.getSample(status: .accepted), memberRole: .admin)
+ let ci = previewDated(ChatItem.getGroupInvitationSample())
+ CIGroupInvitationView(chat: Chat.sampleData, chatItem: ci, groupInvitation: CIGroupInvitation.getSample(groupProfile: GroupProfile(displayName: "team", fullName: "team")), memberRole: .admin).modifier(ChatItemClipped(ci, tailVisible: true))
+ CIGroupInvitationView(chat: Chat.sampleData, chatItem: ci, groupInvitation: CIGroupInvitation.getSample(status: .accepted), memberRole: .admin).modifier(ChatItemClipped(ci, tailVisible: true))
}
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIImageView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIImageView.swift
index fb6ccb1ea3..469fc5a3fc 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIImageView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIImageView.swift
@@ -54,6 +54,7 @@ struct CIImageView: View {
if let prohibited = file.fileProhibited {
showProhibitedFileAlert(file, prohibited)
} else {
+ m.openWhenReceived(file) { _ in showFullScreenImage = true }
Task {
if let user = m.currentUser {
await receiveFile(user: user, fileId: file.fileId)
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CILinkView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CILinkView.swift
index 4eb187bcac..42259361b7 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CILinkView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CILinkView.swift
@@ -52,7 +52,7 @@ struct CILinkView: View {
func openBrowserAlert(uri: String) {
let (url, err) = sanitizeUri(uri)
if let url {
- let uriStr = url.uri.absoluteString
+ let uriStr = displayedUri(url.uri.absoluteString)
showAlert(
NSLocalizedString("Open link?", comment: "alert title"),
message: uriStr.count > 160 ? "\(uriStr.prefix(160))…" : uriStr,
@@ -90,9 +90,9 @@ func openBrowserAlert(uri: String) {
func showInvalidLinkAlert(_ uri: String, error: String? = nil) {
let message = if let error, !error.isEmpty {
- error + "\n" + uri
+ error + "\n" + displayedUri(uri)
} else {
- uri
+ displayedUri(uri)
}
showAlert(
NSLocalizedString("Invalid link", comment: "alert title"),
@@ -101,6 +101,25 @@ func showInvalidLinkAlert(_ uri: String, error: String? = nil) {
)
}
+func unicodeMarker(_ s: Unicode.Scalar) -> String {
+ String(format: "[U+%04X]", s.value)
+}
+
+func displayedUri(_ uri: String) -> String {
+ let authorityStart = uri.range(of: "://")?.upperBound ?? uri.startIndex
+ let authority = authorityStart ..< (uri[authorityStart...].firstIndex(where: { "/?#".contains($0) }) ?? uri.endIndex)
+ var shown = ""
+ for i in uri.unicodeScalars.indices {
+ let s = uri.unicodeScalars[i]
+ if s.properties.generalCategory == .format || (!s.isASCII && authority.contains(i)) {
+ shown += unicodeMarker(s)
+ } else {
+ shown.unicodeScalars.append(s)
+ }
+ }
+ return shown
+}
+
func sanitizeUri(_ s: String) -> (url: (uri: URL, sanitizedUri: URL?)?, error: String?) {
let parsed = parseSanitizeUri(s, safe: false)
return if let uri = URL(string: s), let uriInfo = parsed?.uriInfo {
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIMemberCreatedContactView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIMemberCreatedContactView.swift
index 4719c3dcdc..5442c94cd5 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIMemberCreatedContactView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIMemberCreatedContactView.swift
@@ -14,32 +14,35 @@ import SimpleXChat
struct CIMemberCreatedContactView: View {
@EnvironmentObject var m: ChatModel
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var chatItem: ChatItem
-
+
var body: some View {
- HStack(alignment: .bottom, spacing: 0) {
- switch chatItem.chatDir {
- case let .groupRcv(groupMember):
- if let contactId = groupMember.memberContactId {
- memberCreatedContactView(openText: "Open")
- .simultaneousGesture(TapGesture().onEnded {
- ItemsModel.shared.loadOpenChat("@\(contactId)") {
- dismissAllSheets(animated: true)
- }
- })
- } else {
- memberCreatedContactView()
+ ChatEventWithMeta(chatItem: chatItem) { ts in
+ HStack(alignment: .bottom, spacing: 0) {
+ switch chatItem.chatDir {
+ case let .groupRcv(groupMember):
+ if let contactId = groupMember.memberContactId {
+ memberCreatedContactView(openText: "Open", ts: ts)
+ .simultaneousGesture(TapGesture().onEnded {
+ ItemsModel.shared.loadOpenChat("@\(contactId)") {
+ dismissAllSheets(animated: true)
+ }
+ })
+ } else {
+ memberCreatedContactView(ts: ts)
+ }
+ default:
+ EmptyView()
}
- default:
- EmptyView()
}
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
+ .padding(terminal ? terminalEventPadding : EdgeInsets(top: 0, leading: 6, bottom: 6, trailing: 0))
+ .textSelection(.disabled)
}
- .padding(.leading, 6)
- .padding(.bottom, 6)
- .textSelection(.disabled)
}
-
- private func memberCreatedContactView(openText: LocalizedStringKey? = nil) -> some View {
+
+ private func memberCreatedContactView(openText: LocalizedStringKey? = nil, ts: Text) -> some View {
var r = eventText()
if let openText {
r = r
@@ -48,7 +51,7 @@ struct CIMemberCreatedContactView: View {
.foregroundColor(theme.colors.primary)
+ Text(verbatim: " ")
}
- r = r + chatItem.timestampText
+ r = r + ts
.fontWeight(.light)
.foregroundColor(theme.colors.secondary)
return r.font(.caption)
@@ -72,7 +75,7 @@ struct CIMemberCreatedContactView_Previews: PreviewProvider {
let content = CIContent.rcvGroupEvent(rcvGroupEvent: .memberCreatedContact)
let chatItem = ChatItem(
chatDir: .groupRcv(groupMember: GroupMember.sampleData),
- meta: CIMeta.getSample(1, .now, content.text, .rcvRead),
+ meta: CIMeta.getSample(1, previewDate, content.text, .rcvRead),
content: content,
quotedItem: nil,
file: nil
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIMetaView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIMetaView.swift
index 2984c3a286..e4099b108a 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIMetaView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIMetaView.swift
@@ -113,10 +113,13 @@ func ciMetaText(
showTimesamp: Bool,
signedFileVerified: Bool? = nil,
showSignature: Bool = true,
- showFileEncryption: Bool = true
+ showFileEncryption: Bool = true,
+ unbreakable: Bool = false
) -> Text {
var r = Text("")
var space: Text? = nil
+ let separator = unbreakable ? Text(verbatim: "\u{00A0}") : textSpace
+ let joiner = Text(verbatim: unbreakable ? "\u{2060}" : "")
let appendSpace = {
if let sp = space {
r = r + sp
@@ -125,19 +128,19 @@ func ciMetaText(
}
let resolved = colorMode.resolve(color)
if showEdited, meta.itemEdited {
- r = r + statusIconText("pencil", resolved)
+ r = r + statusIconText("pencil", resolved) + joiner
}
if meta.disappearing {
- r = r + statusIconText("timer", resolved).font(.caption2)
+ r = r + statusIconText("timer", resolved).font(.caption2) + joiner
let ttl = meta.itemTimed?.ttl
if ttl != chatTTL {
r = r + colored(Text(shortTimeText(ttl)), resolved)
}
- space = textSpace
+ space = separator
}
if showViaProxy, meta.sentViaProxy == true {
appendSpace()
- r = r + statusIconText("arrow.forward", resolved?.opacity(0.67)).font(.caption2)
+ r = r + statusIconText("arrow.forward", resolved?.opacity(0.67)).font(.caption2) + joiner
}
if showStatus {
appendSpace()
@@ -151,25 +154,25 @@ func ciMetaText(
} else if !meta.disappearing {
r = r + colorMode.statusSpacer(meta.itemStatus.sent)
}
- space = textSpace
+ space = separator
}
if let enc = encrypted, showFileEncryption {
appendSpace()
r = r + statusIconText(enc ? "lock" : "lock.open", resolved)
- space = textSpace
+ space = separator
}
if showSignature, meta.msgVerified?.verified == true && signedFileVerified != false {
appendSpace()
r = r + colored(Text(Image(systemName: "checkmark.seal")), resolved)
- space = textSpace
+ space = separator
} else if meta.msgVerified == .sigMissing {
appendSpace()
r = r + colored(Text(Image(systemName: "xmark.seal")), colorMode.resolve(.red))
- space = textSpace
+ space = separator
}
if showTimesamp {
appendSpace()
- r = r + colored(meta.timestampText, resolved)
+ r = r + colored(unbreakable ? Text(verbatim: formatTimestampMeta(meta.itemTs).replacingOccurrences(of: " ", with: "\u{00A0}")) : meta.timestampText, resolved)
}
return r.font(.caption)
}
@@ -193,13 +196,13 @@ struct CIMetaView_Previews: PreviewProvider {
static let metaColor = Color.secondary
static var previews: some View {
Group {
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .complete)), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .partial)), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndRcvd(msgRcptStatus: .ok, sndProgress: .complete)), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndRcvd(msgRcptStatus: .ok, sndProgress: .partial)), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndRcvd(msgRcptStatus: .badMsgHash, sndProgress: .complete)), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .complete), itemEdited: true), metaColor: metaColor)
- CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getDeletedContentSample(), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .complete)), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .partial)), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndRcvd(msgRcptStatus: .ok, sndProgress: .complete)), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndRcvd(msgRcptStatus: .ok, sndProgress: .partial)), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndRcvd(msgRcptStatus: .badMsgHash, sndProgress: .complete)), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .complete), itemEdited: true), metaColor: metaColor)
+ CIMetaView(chat: Chat.sampleData, chatItem: ChatItem.getDeletedContentSample(1, previewDate), metaColor: metaColor)
}
.previewLayout(.fixed(width: 360, height: 100))
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift
index bdd38cb4df..705339b1b0 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIRcvDecryptionError.swift
@@ -44,7 +44,11 @@ struct CIRcvDecryptionError: View {
}
var body: some View {
- viewBody()
+ ItemWithMeta {
+ CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
+ } content: { inlineMeta in
+ viewBody(inlineMeta)
+ }
.onAppear {
// for direct chat ConnectionStats are populated on opening chat, see ChatView onAppear
if case let .group(groupInfo, _) = chat.chatInfo,
@@ -70,48 +74,49 @@ struct CIRcvDecryptionError: View {
}
}
- private func viewBody() -> some View {
+ private func viewBody(_ inlineMeta: CIMetaView?) -> some View {
Group {
if case let .direct(contact) = chat.chatInfo,
let contactStats = contact.activeConn?.connectionStats {
if contactStats.ratchetSyncAllowed {
- decryptionErrorItemFixButton(syncSupported: true) {
+ decryptionErrorItemFixButton(syncSupported: true, inlineMeta) {
alert = .syncAllowedAlert { syncContactConnection(contact) }
}
} else if !contactStats.ratchetSyncSupported {
- decryptionErrorItemFixButton(syncSupported: false) {
+ decryptionErrorItemFixButton(syncSupported: false, inlineMeta) {
alert = .syncNotSupportedContactAlert
}
} else {
- basicDecryptionErrorItem()
+ basicDecryptionErrorItem(inlineMeta)
}
} else if case let .group(groupInfo, _) = chat.chatInfo,
case let .groupRcv(groupMember) = chatItem.chatDir,
let mem = m.getGroupMember(groupMember.groupMemberId),
let memberStats = mem.wrapped.activeConn?.connectionStats {
if memberStats.ratchetSyncAllowed {
- decryptionErrorItemFixButton(syncSupported: true) {
+ decryptionErrorItemFixButton(syncSupported: true, inlineMeta) {
alert = .syncAllowedAlert { syncMemberConnection(groupInfo, groupMember) }
}
} else if !memberStats.ratchetSyncSupported {
- decryptionErrorItemFixButton(syncSupported: false) {
+ decryptionErrorItemFixButton(syncSupported: false, inlineMeta) {
alert = .syncNotSupportedMemberAlert
}
} else {
- basicDecryptionErrorItem()
+ basicDecryptionErrorItem(inlineMeta)
}
} else {
- basicDecryptionErrorItem()
+ basicDecryptionErrorItem(inlineMeta)
}
}
.background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
+ .if(inlineMeta == nil) { $0.modifier(ChatItemClipped(chatItem, tailVisible: false)) }
}
- private func basicDecryptionErrorItem() -> some View {
- decryptionErrorItem { alert = .decryptionErrorAlert }
+ private func basicDecryptionErrorItem(_ inlineMeta: CIMetaView?) -> some View {
+ decryptionErrorItem(inlineMeta) { alert = .decryptionErrorAlert }
}
- private func decryptionErrorItemFixButton(syncSupported: Bool, _ onClick: @escaping (() -> Void)) -> some View {
+ private func decryptionErrorItemFixButton(syncSupported: Bool, _ inlineMeta: CIMetaView?, _ onClick: @escaping (() -> Void)) -> some View {
ZStack(alignment: .bottomTrailing) {
VStack(alignment: .leading, spacing: 2) {
HStack {
@@ -127,37 +132,45 @@ struct CIRcvDecryptionError: View {
+ Text("Fix connection")
.foregroundColor(syncSupported ? theme.colors.primary : theme.colors.secondary)
.font(.callout)
- + Text(verbatim: " ")
- + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
+ + metaReserve(inlineMeta)
)
}
.padding(.horizontal, 12)
- CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
- .padding(.horizontal, 12)
+ if let inlineMeta {
+ inlineMeta
+ .padding(.horizontal, 12)
+ }
}
.simultaneousGesture(TapGesture().onEnded(onClick))
.padding(.vertical, 6)
.textSelection(.disabled)
}
- private func decryptionErrorItem(_ onClick: @escaping (() -> Void)) -> some View {
+ private func decryptionErrorItem(_ inlineMeta: CIMetaView?, _ onClick: @escaping (() -> Void)) -> some View {
return ZStack(alignment: .bottomTrailing) {
HStack {
Text(chatItem.content.text)
.foregroundColor(.red)
.italic()
- + Text(verbatim: " ")
- + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
+ + metaReserve(inlineMeta)
}
.padding(.horizontal, 12)
- CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
- .padding(.horizontal, 12)
+ if let inlineMeta {
+ inlineMeta
+ .padding(.horizontal, 12)
+ }
}
.simultaneousGesture(TapGesture().onEnded(onClick))
.padding(.vertical, 6)
.textSelection(.disabled)
}
+ private func metaReserve(_ inlineMeta: CIMetaView?) -> Text {
+ inlineMeta == nil
+ ? Text(verbatim: "")
+ : Text(verbatim: " ") + ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp)
+ }
+
private func message() -> Text {
var message: Text
let why = Text(decryptErrorReason)
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIVideoView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIVideoView.swift
index 0df17dfe3d..0a664f8d96 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIVideoView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIVideoView.swift
@@ -120,6 +120,25 @@ struct CIVideoView: View {
}
}
+ private func playReceived(_ file: CIFile) {
+ setupPlayer(file)
+ if urlDecrypted == nil {
+ decrypt(file: file, completed: playVideo)
+ } else {
+ playVideo()
+ }
+ }
+
+ private func playVideo() {
+ if smallView {
+ showFullScreenPlayer = urlDecrypted != nil
+ } else if let urlDecrypted {
+ m.stopPreviousRecPlay = urlDecrypted
+ videoPlaying = true
+ player?.play()
+ }
+ }
+
private func setupPlayer(_ file: CIFile?) {
let newUrl = getLoadedVideo(file)
if newUrl == url {
@@ -424,6 +443,7 @@ struct CIVideoView: View {
if let prohibited = file.fileProhibited {
showProhibitedFileAlert(file, prohibited)
} else {
+ m.openWhenReceived(file, open: playReceived)
Task {
if let user = m.currentUser {
await receiveFile(user, file.fileId, false, false)
@@ -514,9 +534,9 @@ struct CIVideoView: View {
if let item = player.currentItem {
let dur = CMTimeGetSeconds(item.duration)
if !dur.isInfinite && !dur.isNaN {
- duration = Int(dur)
+ duration = wholeSeconds(dur)
}
- progress = Int(CMTimeGetSeconds(player.currentTime()))
+ progress = wholeSeconds(CMTimeGetSeconds(player.currentTime()))
// `if` prevents showing Play button while the playback seeks to start and then plays
if player.currentTime() != player.currentItem?.duration && player.currentTime() != .zero {
videoPlaying = player.timeControlStatus == .playing || player.timeControlStatus == .waitingToPlayAtSpecifiedRate
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift b/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift
index 64fa2a4dd3..a9e732af41 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/CIVoiceView.swift
@@ -14,6 +14,7 @@ import SimpleXChat
struct CIVoiceView: View {
@ObservedObject var chat: Chat
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var chatItem: ChatItem
let recordingFile: CIFile?
let duration: Int
@@ -36,7 +37,7 @@ struct CIVoiceView: View {
playbackSlider()
}
}
- } else if chatItem.chatDir.sent {
+ } else if chatItem.chatDir.sent && !terminal {
VStack (alignment: .trailing, spacing: 6) {
HStack {
if .playing == playbackState || (playbackTime ?? 0) > 0 || !allowMenu {
@@ -49,21 +50,28 @@ struct CIVoiceView: View {
metaView().padding(.trailing, 10)
}
} else {
- VStack (alignment: .leading, spacing: 6) {
- HStack {
- player()
- playerTime()
- if .playing == playbackState || (playbackTime ?? 0) > 0 || !allowMenu {
- playbackSlider()
+ ItemWithMeta {
+ metaView()
+ } content: { inlineMeta in
+ VStack (alignment: .leading, spacing: 6) {
+ HStack {
+ player()
+ playerTime()
+ if .playing == playbackState || (playbackTime ?? 0) > 0 || !allowMenu {
+ playbackSlider()
+ }
+ }
+ .frame(alignment: .leading)
+ if let inlineMeta {
+ inlineMeta.padding(.leading, -6)
}
}
- .frame(alignment: .leading)
- metaView().padding(.leading, -6)
}
}
}
- .padding(.top, 4)
- .padding(.bottom, 8)
+ .padding(.top, terminal ? 0 : 4)
+ .padding(.bottom, terminal ? terminalCardBottomGap(chatItem) : 8)
+ .padding(.leading, terminal ? chatItemTextPadding : 0)
}
private func player() -> some View {
@@ -142,6 +150,7 @@ struct VoiceMessagePlayer: View {
@ObservedObject var chat: Chat
@EnvironmentObject var chatModel: ChatModel
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var chatItem: ChatItem
var recordingFile: CIFile?
var recordingTime: TimeInterval
@@ -291,7 +300,7 @@ struct VoiceMessagePlayer: View {
.foregroundColor(color)
.padding(.leading, image == "play.fill" ? 4 : 0)
.frame(width: 56 * sizeMultiplier, height: 56 * sizeMultiplier)
- .background(showBackground ? chatItemFrameColor(chatItem, theme) : .clear)
+ .background(showBackground ? backgroundColor : .clear)
.clipShape(Circle())
if recordingTime > 0 {
ProgressCircle(length: recordingTime, progress: $playbackTime)
@@ -303,6 +312,11 @@ struct VoiceMessagePlayer: View {
private func downloadButton(_ recordingFile: CIFile, _ icon: String) -> some View {
playPauseIcon(icon, theme.colors.primary)
.simultaneousGesture(TapGesture().onEnded {
+ chatModel.openWhenReceived(recordingFile) { file in
+ if let recordingSource = getLoadedFileSource(file) {
+ startPlayback(recordingSource)
+ }
+ }
Task {
if let user = chatModel.currentUser {
await receiveFile(user: user, fileId: recordingFile.fileId)
@@ -336,6 +350,10 @@ struct VoiceMessagePlayer: View {
}
}
+ private var backgroundColor: Color {
+ terminal ? chatItemFrameContextColor(chatItem, theme) : chatItemFrameColor(chatItem, theme)
+ }
+
private func fileStatusIcon(_ image: String, _ size: CGFloat) -> some View {
Image(systemName: image)
.resizable()
@@ -343,7 +361,7 @@ struct VoiceMessagePlayer: View {
.frame(width: size * sizeMultiplier, height: size * sizeMultiplier)
.foregroundColor(Color(uiColor: .tertiaryLabel))
.frame(width: 56 * sizeMultiplier, height: 56 * sizeMultiplier)
- .background(showBackground ? chatItemFrameColor(chatItem, theme) : .clear)
+ .background(showBackground ? backgroundColor : .clear)
.clipShape(Circle())
}
@@ -351,7 +369,7 @@ struct VoiceMessagePlayer: View {
ProgressView()
.frame(width: 30 * sizeMultiplier, height: 30 * sizeMultiplier)
.frame(width: 56 * sizeMultiplier, height: 56 * sizeMultiplier)
- .background(showBackground ? chatItemFrameColor(chatItem, theme) : .clear)
+ .background(showBackground ? backgroundColor : .clear)
.clipShape(Circle())
}
@@ -440,30 +458,34 @@ struct CIVoiceView_Previews: PreviewProvider {
let im = ItemsModel.shared
let sentVoiceMessage: ChatItem = ChatItem(
chatDir: .directSnd,
- meta: CIMeta.getSample(1, .now, "", .sndSent(sndProgress: .complete), itemEdited: true),
+ meta: CIMeta.getSample(1, previewDate, "", .sndSent(sndProgress: .complete), itemEdited: true),
content: .sndMsgContent(msgContent: .voice(text: "", duration: 30)),
quotedItem: nil,
file: CIFile.getSample(fileStatus: .sndComplete)
)
let voiceMessageWtFile = ChatItem(
chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "", .rcvRead),
+ meta: CIMeta.getSample(1, previewDate, "", .rcvRead),
content: .rcvMsgContent(msgContent: .voice(text: "", duration: 30)),
quotedItem: nil,
file: nil
)
Group {
+ let ci1 = previewDated(ChatItem.getVoiceMsgContentSample())
CIVoiceView(
chat: Chat.sampleData,
- chatItem: ChatItem.getVoiceMsgContentSample(),
+ chatItem: ci1,
recordingFile: CIFile.getSample(fileName: "voice.m4a", fileSize: 65536, fileStatus: .rcvComplete),
duration: 30,
allowMenu: Binding.constant(true)
)
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentVoiceMessage, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getVoiceMsgContentSample(), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getVoiceMsgContentSample(fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: voiceMessageWtFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true))
+ .modifier(ChatItemClipped(ci1, tailVisible: true))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentVoiceMessage, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true)).modifier(ChatItemClipped(sentVoiceMessage, tailVisible: true))
+ let ci2 = previewDated(ChatItem.getVoiceMsgContentSample())
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = previewDated(ChatItem.getVoiceMsgContentSample(fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: voiceMessageWtFile, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: .constant(true)).modifier(ChatItemClipped(voiceMessageWtFile, tailVisible: true))
}
.previewLayout(.fixed(width: 360, height: 360))
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/DeletedItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/DeletedItemView.swift
index fb5d36ab12..0de4f022b8 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/DeletedItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/DeletedItemView.swift
@@ -17,25 +17,35 @@ struct DeletedItemView: View {
var chatItem: ChatItem
var body: some View {
- HStack(alignment: .bottom, spacing: 0) {
- Text(chatItem.content.text)
- .foregroundColor(theme.colors.secondary)
- .italic()
+ ItemWithMeta {
CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
- .padding(.horizontal, 12)
+ } content: { inlineMeta in
+ HStack(alignment: .lastTextBaseline, spacing: 0) {
+ Text(chatItem.content.text)
+ .foregroundColor(theme.colors.secondary)
+ .italic()
+ if let inlineMeta {
+ inlineMeta
+ .padding(.horizontal, 12)
+ }
+ }
+ .padding(.leading, 12)
+ .padding(.trailing, inlineMeta == nil ? 12 : 0)
+ .padding(.vertical, 6)
+ .background(chatItemFrameColor(chatItem, theme))
+ .if(inlineMeta == nil) { $0.modifier(ChatItemClipped(chatItem, tailVisible: false)) }
+ .textSelection(.disabled)
}
- .padding(.leading, 12)
- .padding(.vertical, 6)
- .background(chatItemFrameColor(chatItem, theme))
- .textSelection(.disabled)
}
}
struct DeletedItemView_Previews: PreviewProvider {
static var previews: some View {
Group {
- DeletedItemView(chat: Chat.sampleData, chatItem: ChatItem.getDeletedContentSample())
- DeletedItemView(chat: Chat.sampleData, chatItem: ChatItem.getDeletedContentSample(dir: .groupRcv(groupMember: GroupMember.sampleData)))
+ let ci1 = ChatItem.getDeletedContentSample(1, previewDate)
+ DeletedItemView(chat: Chat.sampleData, chatItem: ci1).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem.getDeletedContentSample(dir: .groupRcv(groupMember: GroupMember.sampleData), previewDate)
+ DeletedItemView(chat: Chat.sampleData, chatItem: ci2).modifier(ChatItemClipped(ci2, tailVisible: true))
}
.previewLayout(.fixed(width: 360, height: 200))
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift
index 04f36c97a4..c19b1c3a93 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/EmojiItemView.swift
@@ -17,13 +17,23 @@ struct EmojiItemView: View {
var chatItem: ChatItem
var body: some View {
- VStack(spacing: 1) {
- emojiText(chatItem.content.text)
- .padding(.top, 8)
- .padding(.horizontal, 6)
+ ItemWithMeta(metaReserved: true) {
CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
- .padding(.bottom, 8)
- .padding(.horizontal, 12)
+ } content: { inlineMeta in
+ if let inlineMeta {
+ VStack(spacing: 1) {
+ emojiText(chatItem.content.text)
+ .padding(.top, 8)
+ .padding(.horizontal, 6)
+ inlineMeta
+ .padding(.bottom, 8)
+ .padding(.horizontal, 12)
+ }
+ } else {
+ emojiText(chatItem.content.text)
+ .modifier(MessageLastLine())
+ .padding(EdgeInsets(top: 0, leading: chatItemTextPadding, bottom: terminalCardBottomGap(chatItem), trailing: chatItemTextPadding))
+ }
}
}
}
@@ -36,8 +46,8 @@ func emojiText(_ text: String) -> Text {
struct EmojiItemView_Previews: PreviewProvider {
static var previews: some View {
Group{
- EmojiItemView(chat: Chat.sampleData, chatItem: ChatItem.getSample(1, .directSnd, .now, "🙂", .sndSent(sndProgress: .complete)))
- EmojiItemView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directRcv, .now, "👍"))
+ EmojiItemView(chat: Chat.sampleData, chatItem: ChatItem.getSample(1, .directSnd, previewDate, "🙂", .sndSent(sndProgress: .complete)))
+ EmojiItemView(chat: Chat.sampleData, chatItem: ChatItem.getSample(2, .directRcv, previewDate, "👍"))
}
.previewLayout(.fixed(width: 360, height: 70))
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift b/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift
index 123f7289bb..9f9ec9136d 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/FramedCIVoiceView.swift
@@ -15,6 +15,7 @@ import SimpleXChat
// Spec: spec/client/chat-view.md#FramedCIVoiceView
struct FramedCIVoiceView: View {
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
@ObservedObject var chat: Chat
var chatItem: ChatItem
let recordingFile: CIFile?
@@ -35,7 +36,7 @@ struct FramedCIVoiceView: View {
chatItem: chatItem,
recordingFile: recordingFile,
recordingTime: TimeInterval(duration),
- showBackground: false,
+ showBackground: terminal,
seek: $seek,
audioPlayer: $audioPlayer,
playbackState: $playbackState,
@@ -54,10 +55,10 @@ struct FramedCIVoiceView: View {
playbackSlider()
}
}
- .padding(.top, 6)
- .padding(.leading, 6)
- .padding(.trailing, 12)
- .padding(.bottom, chatItem.content.text.isEmpty ? 10 : 0)
+ .padding(.top, terminal ? terminalCardTopGap(chatItem) : 6)
+ .padding(.leading, terminal ? chatItemTextPadding : 6)
+ .padding(.trailing, terminal ? 0 : 12)
+ .padding(.bottom, terminal ? 0 : chatItem.content.text.isEmpty ? 10 : 0)
}
private func playbackSlider() -> some View {
@@ -82,24 +83,27 @@ struct FramedCIVoiceView_Previews: PreviewProvider {
let im = ItemsModel.shared
let sentVoiceMessage: ChatItem = ChatItem(
chatDir: .directSnd,
- meta: CIMeta.getSample(1, .now, "", .sndSent(sndProgress: .complete), itemEdited: true),
+ meta: CIMeta.getSample(1, previewDate, "", .sndSent(sndProgress: .complete), itemEdited: true),
content: .sndMsgContent(msgContent: .voice(text: "Hello there", duration: 30)),
quotedItem: nil,
file: CIFile.getSample(fileStatus: .sndComplete)
)
let voiceMessageWithQuote: ChatItem = ChatItem(
chatDir: .directSnd,
- meta: CIMeta.getSample(1, .now, "", .sndSent(sndProgress: .complete), itemEdited: true),
+ meta: CIMeta.getSample(1, previewDate, "", .sndSent(sndProgress: .complete), itemEdited: true),
content: .sndMsgContent(msgContent: .voice(text: "", duration: 30)),
- quotedItem: CIQuote.getSample(1, .now, "Hi", chatDir: .directRcv),
+ quotedItem: CIQuote.getSample(1, previewDate, "Hi", chatDir: .directRcv),
file: CIFile.getSample(fileStatus: .sndComplete)
)
Group {
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentVoiceMessage, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getVoiceMsgContentSample(text: "Hello there"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getVoiceMsgContentSample(text: "Hello there", fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getVoiceMsgContentSample(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: voiceMessageWithQuote, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: sentVoiceMessage, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(sentVoiceMessage, tailVisible: true))
+ let ci1 = previewDated(ChatItem.getVoiceMsgContentSample(text: "Hello there"))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = previewDated(ChatItem.getVoiceMsgContentSample(text: "Hello there", fileStatus: .rcvTransfer(rcvProgress: 7, rcvTotal: 10)))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = previewDated(ChatItem.getVoiceMsgContentSample(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: voiceMessageWithQuote, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(voiceMessageWithQuote, tailVisible: true))
}
.environment(\.revealed, false)
.previewLayout(.fixed(width: 360, height: 360))
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift
index f822970ea4..752cefb743 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/FramedItemView.swift
@@ -10,10 +10,14 @@
import SwiftUI
import SimpleXChat
+private let quoteBarSpacing: CGFloat = 10
+
// Spec: spec/client/chat-view.md#FramedItemView
struct FramedItemView: View {
@EnvironmentObject var m: ChatModel
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
+ @AppStorage(DEFAULT_CHAT_ITEM_ROUNDNESS) private var roundness = defaultChatItemRoundness
@ObservedObject var chat: Chat
@ObservedObject var im: ItemsModel
var chatItem: ChatItem
@@ -27,105 +31,118 @@ struct FramedItemView: View {
@State private var useWhiteMetaColor: Bool = false
@State var showFullScreenImage = false
@Binding var allowMenu: Bool
+ var endButton: AnyView? = nil
@State private var showFullscreenGallery: Bool = false
var body: some View {
- let v = ZStack(alignment: .bottomTrailing) {
- VStack(alignment: .leading, spacing: 0) {
- if chatItem.isReport {
- if chatItem.meta.itemDeleted == nil {
- let txt = chatItem.chatDir.sent ?
- Text("Only you and moderators see it") :
- Text("Only sender and moderators see it")
-
- framedItemHeader(icon: "flag", iconColor: .red, caption: txt.italic())
- } else {
- framedItemHeader(icon: "flag", caption: Text("archived report").italic())
- }
- } else if let di = chatItem.meta.itemDeleted {
- switch di {
- case let .moderated(_, byGroupMember):
- framedItemHeader(icon: "flag", caption: Text("moderated by \(byGroupMember.displayName)").italic())
- case .blocked:
- framedItemHeader(icon: "hand.raised", caption: Text("blocked").italic())
- case .blockedByAdmin:
- framedItemHeader(icon: "hand.raised", caption: Text("blocked by admin").italic())
- case .deleted:
- framedItemHeader(icon: "trash", caption: Text("marked deleted").italic())
- }
- } else if chatItem.meta.isLive {
- framedItemHeader(caption: Text("LIVE"))
- }
+ let v = ItemWithMeta(
+ showMeta: chatItem.content.msgContent != nil,
+ metaReserved: metaPlacement.reserved,
+ overlayMeta: captionlessMedia ? AnyView(CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary, invertedMaterial: true)) : nil,
+ endButton: endButton,
+ lastBlockGap: terminalCardBottomGap(chatItem)
+ ) {
+ CIMetaView(
+ chat: chat,
+ chatItem: chatItem,
+ metaColor: theme.colors.secondary,
+ invertedMaterial: useWhiteMetaColor && !terminal
+ )
+ } content: { inlineMeta in
+ ZStack(alignment: metaPlacement.reserved ? Alignment(horizontal: .trailing, vertical: .lastTextBaseline) : .bottomTrailing) {
+ VStack(alignment: .leading, spacing: 0) {
+ if chatItem.isReport {
+ if chatItem.meta.itemDeleted == nil {
+ let txt = chatItem.chatDir.sent ?
+ Text("Only you and moderators see it") :
+ Text("Only sender and moderators see it")
- if let qi = chatItem.quotedItem {
- ciQuoteView(qi)
- .simultaneousGesture(TapGesture().onEnded {
- if let ci = im.reversedChatItems.first(where: { $0.id == qi.itemId }) {
- withAnimation {
- scrollToItem(ci.id)
- }
- } else if let id = qi.itemId {
- if (chatItem.isReport && im.secondaryIMFilter != nil) {
- scrollToItemId = id
+ framedItemHeader(icon: "flag", iconColor: .red, caption: txt.italic())
+ } else {
+ framedItemHeader(icon: "flag", caption: Text("archived report").italic())
+ }
+ } else if let di = chatItem.meta.itemDeleted {
+ switch di {
+ case let .moderated(_, byGroupMember):
+ framedItemHeader(icon: "flag", caption: Text("moderated by \(byGroupMember.displayName)").italic())
+ case .blocked:
+ framedItemHeader(icon: "hand.raised", caption: Text("blocked").italic())
+ case .blockedByAdmin:
+ framedItemHeader(icon: "hand.raised", caption: Text("blocked by admin").italic())
+ case .deleted:
+ framedItemHeader(icon: "trash", caption: Text("marked deleted").italic())
+ }
+ } else if chatItem.meta.isLive {
+ framedItemHeader(caption: Text("LIVE"))
+ }
+
+ if let qi = chatItem.quotedItem {
+ ciQuoteView(qi)
+ .simultaneousGesture(TapGesture().onEnded {
+ if let ci = im.reversedChatItems.first(where: { $0.id == qi.itemId }) {
+ withAnimation {
+ scrollToItem(ci.id)
+ }
+ } else if let id = qi.itemId {
+ if (chatItem.isReport && im.secondaryIMFilter != nil) {
+ scrollToItemId = id
+ } else {
+ scrollToItem(id)
+ }
} else {
- scrollToItem(id)
+ showQuotedItemDoesNotExistAlert()
}
- } else {
- showQuotedItemDoesNotExistAlert()
- }
- })
- } else if let itemForwarded = chatItem.meta.itemForwarded {
- let twoRowHeader: Bool = if chat.chatInfo.chatType == .local {
- itemForwarded.chatTypeApiIdMsgId != nil || itemForwarded.sourceGroupLink != nil
- } else {
- switch itemForwarded {
- case let .group(_, _, _, _, _, _, groupType): groupType != nil
- case .groupLink: true
- default: false
- }
- }
- if twoRowHeader {
- let caption: LocalizedStringKey = chat.chatInfo.chatType == .local ? "saved from" : "forwarded from"
- headerFrame(pad: true) {
- VStack(alignment: .leading, spacing: 4) {
- headerRow(icon: "arrowshape.turn.up.forward", caption: Text(caption).italic())
- Text(itemForwarded.chatName)
- .font(.subheadline)
- .lineLimit(1)
+ })
+ } else if let itemForwarded = chatItem.meta.itemForwarded {
+ let twoRowHeader: Bool = if chat.chatInfo.chatType == .local {
+ itemForwarded.chatTypeApiIdMsgId != nil || itemForwarded.sourceGroupLink != nil
+ } else {
+ switch itemForwarded {
+ case let .group(_, _, _, _, _, _, groupType): groupType != nil
+ case .groupLink: true
+ default: false
}
}
- .simultaneousGesture(TapGesture().onEnded {
- if let (chatType, apiId, msgId) = itemForwarded.chatTypeApiIdMsgId {
- im.loadOpenChatNoWait("\(chatType.rawValue)\(apiId)", msgId)
- } else if let link = itemForwarded.sourceGroupLink {
- planAndConnect(link, theme: theme, dismiss: false)
+ if twoRowHeader {
+ let caption: LocalizedStringKey = chat.chatInfo.chatType == .local ? "saved from" : "forwarded from"
+ headerFrame(pad: true) {
+ VStack(alignment: .leading, spacing: 4) {
+ headerRow(icon: "arrowshape.turn.up.forward", caption: Text(caption).italic())
+ Text(itemForwarded.chatName)
+ .font(.subheadline)
+ .lineLimit(1)
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .subheadline), theme.colors.secondary, theme)) }
+ }
}
- })
- } else {
- framedItemHeader(icon: "arrowshape.turn.up.forward", caption: Text(itemForwarded.text(chat.chatInfo.chatType)).italic(), pad: true)
+ .simultaneousGesture(TapGesture().onEnded {
+ if let (chatType, apiId, msgId) = itemForwarded.chatTypeApiIdMsgId {
+ im.loadOpenChatNoWait("\(chatType.rawValue)\(apiId)", msgId)
+ } else if let link = itemForwarded.sourceGroupLink {
+ planAndConnect(link, theme: theme, dismiss: false)
+ }
+ })
+ } else {
+ framedItemHeader(icon: "arrowshape.turn.up.forward", caption: Text(itemForwarded.text(chat.chatInfo.chatType)).italic(), pad: true)
+ }
}
+
+ ChatItemContentView(chat: chat, im: im, chatItem: chatItem, msgContentView: framedMsgContentView)
+ .padding(chatItem.content.msgContent != nil ? 0 : 4)
+ .overlay(DetermineWidth())
}
- ChatItemContentView(chat: chat, im: im, chatItem: chatItem, msgContentView: framedMsgContentView)
- .padding(chatItem.content.msgContent != nil ? 0 : 4)
- .overlay(DetermineWidth())
- }
-
- if let content = chatItem.content.msgContent {
- CIMetaView(
- chat: chat,
- chatItem: chatItem,
- metaColor: theme.colors.secondary,
- invertedMaterial: useWhiteMetaColor
- )
- .padding(.horizontal, 12)
- .padding(.bottom, 6)
- .overlay(DetermineWidth())
- .accessibilityLabel("")
+ if let inlineMeta {
+ inlineMeta
+ .padding(.horizontal, 12)
+ .padding(.bottom, 6)
+ .overlay(DetermineWidth())
+ .accessibilityLabel("")
+ }
}
}
- .background { chatItemFrameColorMaybeImageOrVideo(chatItem, theme).modifier(ChatTailPadding()) }
+ .background { if !terminal { chatItemFrameColorMaybeImageOrVideo(chatItem, theme).modifier(ChatTailPadding()) } }
.onPreferenceChange(DetermineWidth.Key.self) { msgWidth = $0 }
+ .padding(.bottom, terminal && metaPlacement.gapBelowBlock ? terminalCardBottomGap(chatItem) : 0)
if let (title, text) = chatItem.meta.itemStatus.statusInfo ?? chatItem.meta.msgVerified?.sigMissingInfo {
v.simultaneousGesture(TapGesture().onEnded {
@@ -141,22 +158,33 @@ struct FramedItemView: View {
}
}
+ static func showsEmoji(_ ci: ChatItem) -> Bool {
+ ci.formattedText == nil && ci.file == nil && !ci.meta.isLive && isShortEmoji(ci.content.text)
+ }
+
@ViewBuilder private func framedMsgContentView() -> some View {
- if chatItem.formattedText == nil && chatItem.file == nil && !chatItem.meta.isLive && isShortEmoji(chatItem.content.text) {
- VStack {
+ if Self.showsEmoji(chatItem) {
+ if terminal {
emojiText(chatItem.content.text)
- Text("")
+ .modifier(MessageLastLine())
+ .padding(EdgeInsets(top: terminalCardTopGap(chatItem), leading: chatItemTextPadding, bottom: terminalCardBottomGap(chatItem), trailing: chatItemTextPadding))
+ } else {
+ VStack(spacing: 4) {
+ emojiText(chatItem.content.text)
+ Text("").font(.caption)
+ }
+ .padding(.vertical, 6)
+ .padding(.horizontal, 12)
+ .overlay(DetermineWidth())
+ .frame(minWidth: msgWidth, alignment: .center)
+ .padding(.bottom, 2)
}
- .padding(.vertical, 6)
- .padding(.horizontal, 12)
- .overlay(DetermineWidth())
- .frame(minWidth: msgWidth, alignment: .center)
- .padding(.bottom, 2)
} else {
switch (chatItem.content.msgContent) {
case let .image(text, _):
CIImageView(chatItem: chatItem, scrollToItem: scrollToItem, preview: preview, maxWidth: maxWidth, imgWidth: imgWidth, showFullScreenImage: $showFullscreenGallery)
.overlay(DetermineWidth())
+ .if(terminal) { terminalBlock($0) }
if text == "" && !chatItem.meta.isLive {
Color.clear
.frame(width: 0, height: 0)
@@ -172,6 +200,7 @@ struct FramedItemView: View {
case let .video(text, _, duration):
CIVideoView(chatItem: chatItem, preview: preview, duration: duration, maxWidth: maxWidth, videoWidth: videoWidth, showFullscreenPlayer: $showFullscreenGallery)
.overlay(DetermineWidth())
+ .if(terminal) { terminalBlock($0) }
if text == "" && !chatItem.meta.isLive {
Color.clear
.frame(width: 0, height: 0)
@@ -196,6 +225,7 @@ struct FramedItemView: View {
ciMsgContentView(chatItem, txtPrefix: reason.attrString)
case let .link(_, preview):
CILinkView(linkPreview: preview, maxWidth: maxWidth)
+ .if(terminal) { terminalBlock($0.frame(maxWidth: maxWidth).padding(.bottom, 8), chatItemFrameContextColor(chatItem, theme)) }
ciMsgContentView(chatItem)
case let .chat(text, chatLink, ownerSig):
let hasText = text != chatLink.connLinkStr
@@ -204,6 +234,7 @@ struct FramedItemView: View {
.simultaneousGesture(TapGesture().onEnded {
planAndConnect(chatLink.connLinkStr, linkOwnerSig: ownerSig, theme: theme, dismiss: false)
})
+ .if(terminal) { terminalBlock($0.frame(maxWidth: maxWidth).fixedSize(horizontal: true, vertical: false), chatItemFrameContextColor(chatItem, theme)) }
if hasText {
ciMsgContentView(chatItem, stripLink: chatLink.connLinkStr)
}
@@ -237,6 +268,7 @@ struct FramedItemView: View {
caption
.font(.caption)
.lineLimit(1)
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), theme.colors.secondary, theme)) }
}
}
@@ -244,12 +276,12 @@ struct FramedItemView: View {
let v = content()
.foregroundColor(theme.colors.secondary)
.padding(.horizontal, 12)
- .padding(.top, 6)
- .padding(.bottom, pad || (chatItem.quotedItem == nil && chatItem.meta.itemForwarded == nil) ? 6 : 0)
+ .padding(.top, terminal ? terminalHeaderTopGap : 6)
+ .padding(.bottom, terminal ? terminalHeaderBottomGap : pad || (chatItem.quotedItem == nil && chatItem.meta.itemForwarded == nil) ? 6 : 0)
.overlay(DetermineWidth())
.frame(minWidth: msgWidth, alignment: .leading)
- .background(chatItemFrameContextColor(chatItem, theme))
- if let mediaWidth = maxMediaWidth(), mediaWidth < maxWidth {
+ .background(terminal ? Color.clear : chatItemFrameContextColor(chatItem, theme))
+ if let mediaWidth = mediaLimit {
v.frame(maxWidth: mediaWidth, alignment: .leading)
} else {
v
@@ -262,40 +294,42 @@ struct FramedItemView: View {
switch (qi.content) {
case let .image(_, image):
if let uiImage = imageFromBase64(image) {
- ciQuotedMsgView(qi)
- .padding(.trailing, 70).frame(minWidth: msgWidth, alignment: .leading)
+ quotedMsgOrGap(qi)
+ .padding(.trailing, terminal ? 68 + chatItemTextPadding : 70).frame(minWidth: quoteMinWidth, alignment: .leading)
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 68, height: 68)
.clipped()
+ .if(terminal) { $0.clipShape(RoundedRectangle(cornerRadius: msgRectMaxRadius * roundness)).padding(.trailing, chatItemTextPadding) }
} else {
ciQuotedMsgView(qi)
}
case let .video(_, image, _):
if let uiImage = imageFromBase64(image) {
- ciQuotedMsgView(qi)
- .padding(.trailing, 70).frame(minWidth: msgWidth, alignment: .leading)
+ quotedMsgOrGap(qi)
+ .padding(.trailing, terminal ? 68 + chatItemTextPadding : 70).frame(minWidth: quoteMinWidth, alignment: .leading)
Image(uiImage: uiImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 68, height: 68)
.clipped()
+ .if(terminal) { $0.clipShape(RoundedRectangle(cornerRadius: msgRectMaxRadius * roundness)).padding(.trailing, chatItemTextPadding) }
} else {
ciQuotedMsgView(qi)
}
case .file:
ciQuotedMsgView(qi)
- .padding(.trailing, 20).frame(minWidth: msgWidth, alignment: .leading)
+ .padding(.trailing, 20).frame(minWidth: quoteMinWidth, alignment: .leading)
ciQuoteIconView("doc.fill")
case .voice:
ciQuotedMsgView(qi)
- .padding(.trailing, 20).frame(minWidth: msgWidth, alignment: .leading)
+ .padding(.trailing, 20).frame(minWidth: quoteMinWidth, alignment: .leading)
ciQuoteIconView("mic.fill")
case let .chat(text, chatLink, _):
let prefix = NSAttributedString(string: chatLink.displayName + (text != chatLink.connLinkStr ? " - " : ""))
ciQuotedMsgView(qi, stripLink: chatLink.connLinkStr, prefix: prefix)
- .padding(.trailing, 20).frame(minWidth: msgWidth, alignment: .leading)
+ .padding(.trailing, 20).frame(minWidth: quoteMinWidth, alignment: .leading)
ciQuoteIconView(chatLink.smallIconName)
default:
ciQuotedMsgView(qi)
@@ -303,24 +337,34 @@ struct FramedItemView: View {
}
// if enable this always, size of the framed voice message item will be incorrect after end of playback
.overlay { if case .voice = chatItem.content.msgContent {} else { DetermineWidth() } }
- .frame(minWidth: msgWidth, alignment: .leading)
- .background(backgroundColor)
- .environment(\.containerBackground, UIColor(backgroundColor))
- if let mediaWidth = maxMediaWidth(), mediaWidth < maxWidth {
+ .frame(minWidth: quoteMinWidth, alignment: .leading)
+ .background(terminal ? Color.clear : backgroundColor)
+ .environment(\.containerBackground, UIColor(terminal ? terminalBackgroundColor(theme) : backgroundColor))
+ .if(terminal) { terminalQuote($0) }
+ if let mediaWidth = mediaLimit {
v.frame(maxWidth: mediaWidth, alignment: .leading)
} else {
v
}
}
-
+
+ @ViewBuilder private func quotedMsgOrGap(_ qi: CIQuote) -> some View {
+ if terminal && qi.text.isEmpty && qi.getSender(membership()) == nil {
+ Color.clear.frame(width: chatItemTextPadding - quoteBarSpacing, height: 0)
+ } else {
+ ciQuotedMsgView(qi)
+ }
+ }
+
private func ciQuotedMsgView(_ qi: CIQuote, stripLink: String? = nil, prefix: NSAttributedString? = nil) -> some View {
Group {
if let sender = qi.getSender(membership()) {
- VStack(alignment: .leading, spacing: 2) {
+ VStack(alignment: .leading, spacing: terminal ? 0 : 2) {
Text(sender)
- .font(.caption)
+ .font(terminal ? .system(size: terminalNameSize) : .caption)
.foregroundColor(qi.chatDir == .groupSnd ? .accentColor : theme.colors.secondary)
.lineLimit(1)
+ .if(terminal) { $0.modifier(terminalLineBox(UIFont.systemFont(ofSize: terminalNameSize), nil, theme)) }
ciQuotedMsgTextView(qi, lines: 2, stripLink: stripLink, prefix: prefix)
}
} else {
@@ -328,15 +372,15 @@ struct FramedItemView: View {
}
}
.fixedSize(horizontal: false, vertical: true)
- .padding(.top, 6)
- .padding(.horizontal, 12)
+ .padding(.top, terminal ? 0 : 6)
+ .padding(terminal ? .trailing : .horizontal, 12)
}
@inline(__always)
private func ciQuotedMsgTextView(_ qi: CIQuote, lines: Int, stripLink: String? = nil, prefix: NSAttributedString? = nil) -> some View {
- MsgContentView(chat: chat, text: qi.text, formattedText: qi.formattedText, textStyle: .subheadline, prefix: prefix, stripLink: stripLink)
+ MsgContentView(chat: chat, text: qi.text, formattedText: qi.formattedText, markdownBlocks: qi.markdownBlocks, textStyle: .subheadline, prefix: prefix, stripLink: stripLink, textColor: terminal ? theme.colors.onSurface.opacity(0.7) : theme.colors.onSurface)
.lineLimit(lines)
- .padding(.bottom, 6)
+ .padding(.bottom, terminal ? 0 : 6)
}
private func ciQuoteIconView(_ image: String) -> some View {
@@ -345,9 +389,28 @@ struct FramedItemView: View {
.aspectRatio(contentMode: .fit)
.foregroundColor(Color(uiColor: .tertiaryLabel))
.frame(width: 18, height: 18)
- .padding(.top, 6)
+ .padding(.top, terminal ? 0 : 6)
.padding(.trailing, 6)
}
+
+ private func terminalQuote(_ quote: some View) -> some View {
+ HStack(alignment: .top, spacing: quoteBarSpacing) {
+ quoteBar()
+ quote
+ }
+ .fixedSize(horizontal: false, vertical: true)
+ .padding(.leading, chatItemTextPadding)
+ .overlay { if case .voice = chatItem.content.msgContent {} else { DetermineWidth() } }
+ .padding(.top, chatItem.hasHeaderAboveQuote ? terminalParagraphGap : 0)
+ }
+
+ private func terminalBlock(_ block: some View, _ background: Color = .clear) -> some View {
+ block
+ .background(background)
+ .clipShape(RoundedRectangle(cornerRadius: msgRectMaxRadius * roundness))
+ .padding(.leading, chatItemTextPadding)
+ .padding(.top, terminalCardTopGap(chatItem))
+ }
private func membership() -> GroupMember? {
switch chat.chatInfo {
@@ -364,22 +427,29 @@ struct FramedItemView: View {
chat: chat,
text: text,
formattedText: ft,
+ markdownBlocks: text == "" ? nil : ci.markdownBlocks,
textStyle: .body,
meta: ci.meta,
mentions: ci.mentions,
userMemberId: chat.chatInfo.groupInfo?.membership.memberId,
rightToLeft: rtl,
prefix: txtPrefix,
- stripLink: stripLink
+ stripLink: stripLink,
+ blockLayout: true,
+ cardColor: ci.chatDir.sent ? theme.appColors.sentQuote : theme.appColors.receivedQuote,
+ encrypted: ci.encryptedFile,
+ signedFileVerified: ci.file?.loaded,
+ ruleMinWidth: terminal ? max(0, msgWidth - 2 * chatItemTextPadding) : 0
)
- .environment(\.containerBackground, UIColor(chatItemFrameColor(ci, theme)))
+ .environment(\.containerBackground, UIColor(terminal ? terminalBackgroundColor(theme) : chatItemFrameColor(ci, theme)))
.multilineTextAlignment(rtl ? .trailing : .leading)
- .padding(.vertical, 6)
+ .padding(.vertical, terminal ? 0 : 6)
+ .padding(.top, terminal ? terminalTextTopGap(ci) : 0)
.padding(.horizontal, 12)
.overlay(DetermineWidth())
.frame(minWidth: 0, alignment: .leading)
- if let mediaWidth = maxMediaWidth(), mediaWidth < maxWidth {
+ if let mediaWidth = mediaLimit {
v.frame(maxWidth: mediaWidth, alignment: .leading)
} else {
v
@@ -389,6 +459,7 @@ struct FramedItemView: View {
@ViewBuilder private func ciFileView(_ ci: ChatItem, _ text: String) -> some View {
CIFileView(chat: chat, file: chatItem.file, meta: chatItem.meta)
.overlay(DetermineWidth())
+ .padding(.top, terminal ? terminalCardTopGap(ci) : 0)
if text != "" || ci.meta.isLive {
ciMsgContentView (chatItem)
}
@@ -404,6 +475,35 @@ struct FramedItemView: View {
}
}
+ private var mediaLimit: CGFloat? {
+ guard let mediaWidth = maxMediaWidth() else { return nil }
+ return if terminal {
+ captionlessMedia ? mediaWidth + chatItemTextPadding : nil
+ } else {
+ mediaWidth < maxWidth ? mediaWidth : nil
+ }
+ }
+
+ private var quoteMinWidth: CGFloat {
+ terminal ? 0 : msgWidth
+ }
+
+ private var captionlessMedia: Bool {
+ switch chatItem.content.msgContent {
+ case let .image(text, _), let .video(text, _, _): !chatItem.meta.isLive && text.isEmpty
+ default: false
+ }
+ }
+
+ private var metaPlacement: (reserved: Bool, gapBelowBlock: Bool) {
+ switch chatItem.content.msgContent {
+ case let .voice(text, _): (text != "", text == "")
+ case let .file(text), let .unknown(_, text): (true, chatItem.file != nil && text == "" && !chatItem.meta.isLive)
+ case let .chat(text, chatLink, _): text != chatLink.connLinkStr ? (true, false) : (false, true)
+ default: (!captionlessMedia, captionlessMedia)
+ }
+ }
+
private func showQuotedItemDoesNotExistAlert() {
AlertManager.shared.showAlertMsg(
title: "No message",
@@ -450,14 +550,22 @@ struct FramedItemView_Previews: PreviewProvider {
static var previews: some View {
let im = ItemsModel.shared
Group{
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello", quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directSnd)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directRcv)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "Hello too", chatDir: .directRcv)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this covers -"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this text has the time on the same line "), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "https://simplex.chat"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "chaT@simplex.chat"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
+ let ci1 = ChatItem.getSample(1, .directSnd, previewDate, "hello")
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello", quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directSnd))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directRcv))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = ChatItem.getSample(2, .directSnd, previewDate, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "Hello too", chatDir: .directRcv))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci4, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this covers -")
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci5, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci5, tailVisible: true))
+ let ci6 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this text has the time on the same line ")
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci6, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci6, tailVisible: true))
+ let ci7 = ChatItem.getSample(2, .directRcv, previewDate, "https://simplex.chat")
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci7, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci7, tailVisible: true))
+ let ci8 = ChatItem.getSample(2, .directRcv, previewDate, "chaT@simplex.chat")
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci8, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci8, tailVisible: true))
}
.previewLayout(.fixed(width: 360, height: 200))
}
@@ -467,16 +575,26 @@ struct FramedItemView_Edited_Previews: PreviewProvider {
static var previews: some View {
let im = ItemsModel.shared
Group {
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello", quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directSnd), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directRcv), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "Hello too", chatDir: .directRcv), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this covers -", .rcvRead, itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this text has the time on the same line ", .rcvRead, itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "https://simplex.chat", .rcvRead, itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "chaT@simplex.chat", .rcvRead, itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello", quotedItem: CIQuote.getSample(1, .now, "hi there hello hello hello ther hello hello", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAYAC4AwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJS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2Ovh7bfB7wHN8pvoo/shMZ4LfaSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello there this is a long text", quotedItem: CIQuote.getSample(1, .now, "hi there", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAYAC4AwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABA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yQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemEdited: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
+ let ci1 = ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello", quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directSnd), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directRcv), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = ChatItem.getSample(2, .directSnd, previewDate, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "Hello too", chatDir: .directRcv), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci4, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this covers -", .rcvRead, itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci5, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci5, tailVisible: true))
+ let ci6 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this text has the time on the same line ", .rcvRead, itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci6, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci6, tailVisible: true))
+ let ci7 = ChatItem.getSample(2, .directRcv, previewDate, "https://simplex.chat", .rcvRead, itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci7, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci7, tailVisible: true))
+ let ci8 = ChatItem.getSample(2, .directRcv, previewDate, "chaT@simplex.chat", .rcvRead, itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci8, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci8, tailVisible: true))
+ let ci9 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello", quotedItem: CIQuote.getSample(1, previewDate, "hi there hello hello hello ther hello hello", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAYAC4AwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIB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tof8Ex/jPq+k+IPHelan491HQlljtI7KGWyikWUqSkryNCzJlcgc4JPHNcZ4V+Iv7c37TGgJ8N/2Ovh7bfB7wHN8pvoo/shMZ4LfaSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci9, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci9, tailVisible: true))
+ let ci10 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello there this is a long text", quotedItem: CIQuote.getSample(1, previewDate, "hi there", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAYAC4AwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoe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WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemEdited: true)
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci10, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci10, tailVisible: true))
}
.environment(\.revealed, false)
.previewLayout(.fixed(width: 360, height: 200))
@@ -487,16 +605,26 @@ struct FramedItemView_Deleted_Previews: PreviewProvider {
static var previews: some View {
let im = ItemsModel.shared
Group {
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello", quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directSnd), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "hi", chatDir: .directRcv), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directSnd, .now, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, .now, "Hello too", chatDir: .directRcv), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this covers -", .rcvRead, itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too!!! this text has the time on the same line ", .rcvRead, itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "https://simplex.chat", .rcvRead, itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "chaT@simplex.chat", .rcvRead, itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello", quotedItem: CIQuote.getSample(1, .now, "hi there hello hello hello ther hello hello", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgA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n2/98+bj9K5oYTOqMpSpyoyb3k4yjJ2015Xqac/BNSbrPD4mlKW6hKlJf8AgUkpP5n5zfta/tof8Ex/jPq+k+IPHelan491HQlljtI7KGWyikWUqSkryNCzJlcgc4JPHNcZ4V+Iv7c37TGgJ8N/2Ovh7bfB7wHN8pvoo/shMZ4LfaSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
- FramedItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), .now, "hello there this is a long text", quotedItem: CIQuote.getSample(1, .now, "hi there", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADAAQAAAABAAAAYAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgAYAC4AwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElK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faSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true))
+ let ci1 = ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello", quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directSnd), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = ChatItem.getSample(2, .directSnd, previewDate, "https://simplex.chat", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "hi", chatDir: .directRcv), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = ChatItem.getSample(2, .directSnd, previewDate, "👍", .sndSent(sndProgress: .complete), quotedItem: CIQuote.getSample(1, previewDate, "Hello too", chatDir: .directRcv), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci4, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this covers -", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci5, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci5, tailVisible: true))
+ let ci6 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too!!! this text has the time on the same line ", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci6, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci6, tailVisible: true))
+ let ci7 = ChatItem.getSample(2, .directRcv, previewDate, "https://simplex.chat", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci7, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci7, tailVisible: true))
+ let ci8 = ChatItem.getSample(2, .directRcv, previewDate, "chaT@simplex.chat", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci8, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci8, tailVisible: true))
+ let ci9 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello", quotedItem: CIQuote.getSample(1, previewDate, "hi there hello hello hello ther hello hello", chatDir: .directSnd, image: "data:image/jpg;base64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+Hm6VR7uNrS/xRekvzPuMo45xOGoQweOpRxFCPwqd1KH/XuorSh8m0uiPwz0L/AIKEf8E3vi6miH4saHd6Xc6B5gs4tWs3vYIPNILAGFpA65UcSLxjgCvtS1/4KT/sLWVlHFZePrCGCJAqRJa3K7VHQBRFxj0xXv8A48/Zc/Zx+J0z3Xj3wPoupzyHLTS2cfnE+8iqH/WvGP8Ah23+w953n/8ACu9PznOPMn2/98+bj9K5oYTOqMpSpyoyb3k4yjJ2015Xqac/BNSbrPD4mlKW6hKlJf8AgUkpP5n5zfta/tof8Ex/jPq+k+IPHelan491HQlljtI7KGWyikWUqSkryNCzJlcgc4JPHNcZ4V+Iv7c37TGgJ8N/2Ovh7bfB7wHN8pvoo/shMZ4LfaSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci9, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci9, tailVisible: true))
+ let ci10 = ChatItem.getSample(1, .groupRcv(groupMember: GroupMember.sampleData), previewDate, "hello there this is a long text", quotedItem: CIQuote.getSample(1, previewDate, "hi there", chatDir: .directSnd, image: "data:image/jpg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAuKADA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sLWVlHFZePrCGCJAqRJa3K7VHQBRFxj0xXv8A48/Zc/Zx+J0z3Xj3wPoupzyHLTS2cfnE+8iqH/WvGP8Ah23+w953n/8ACu9PznOPMn2/98+bj9K5oYTOqMpSpyoyb3k4yjJ2015Xqac/BNSbrPD4mlKW6hKlJf8AgUkpP5n5zfta/tof8Ex/jPq+k+IPHelan491HQlljtI7KGWyikWUqSkryNCzJlcgc4JPHNcZ4V+Iv7c37TGgJ8N/2Ovh7bfB7wHN8pvoo/shMZ4LfaSiMxx1MERf/ar9sPAn7LH7N3wxmS68B+BtF02eM5WaOzjMwI9JGBf9a98AAGBWSyDF16kquKrqPN8Xso8rfrN3lY9SXG+WYPDww2W4SdRQ+B4io5xjre6pRtTvfW+up+cv7H//AATg+FX7MdynjzxHMfFnjeTLvqt2vyQO/wB77OjFtpOeZGLSH1AOK/Rqiivo8FgaGEpKjh4KMV/V33fmz4LNs5xuZ4h4rHVXOb6vouyWyS6JJIKKKK6zzAooooAKKKKAILr/AI9pP90/yrjq7G6/49pP90/yrjqAP//Z"), itemDeleted: .deleted(deletedTs: previewDate))
+ FramedItemView(chat: Chat.sampleData, im: im, chatItem: ci10, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil), allowMenu: Binding.constant(true)).modifier(ChatItemClipped(ci10, tailVisible: true))
}
.environment(\.revealed, false)
.previewLayout(.fixed(width: 360, height: 200))
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/IntegrityErrorItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/IntegrityErrorItemView.swift
index d831333c20..03ee0bc1a9 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/IntegrityErrorItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/IntegrityErrorItemView.swift
@@ -62,18 +62,26 @@ struct CIMsgError: View {
var onTap: () -> Void
var body: some View {
- HStack(alignment: .bottom, spacing: 0) {
- Text(chatItem.content.text)
- .foregroundColor(.red)
- .italic()
+ ItemWithMeta {
CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
- .padding(.horizontal, 12)
+ } content: { inlineMeta in
+ HStack(alignment: .bottom, spacing: 0) {
+ Text(chatItem.content.text)
+ .foregroundColor(.red)
+ .italic()
+ if let inlineMeta {
+ inlineMeta
+ .padding(.horizontal, 12)
+ }
+ }
+ .padding(.leading, 12)
+ .padding(.trailing, inlineMeta == nil ? 12 : 0)
+ .padding(.vertical, 6)
+ .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
+ .if(inlineMeta == nil) { $0.modifier(ChatItemClipped(chatItem, tailVisible: false)) }
+ .textSelection(.disabled)
+ .simultaneousGesture(TapGesture().onEnded(onTap))
}
- .padding(.leading, 12)
- .padding(.vertical, 6)
- .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
- .textSelection(.disabled)
- .simultaneousGesture(TapGesture().onEnded(onTap))
}
}
@@ -98,6 +106,7 @@ struct RcvMsgErrorItemView: View {
struct IntegrityErrorItemView_Previews: PreviewProvider {
static var previews: some View {
- IntegrityErrorItemView(chat: Chat.sampleData, msgError: .msgBadHash, chatItem: ChatItem.getIntegrityErrorSample())
+ let ci = previewDated(ChatItem.getIntegrityErrorSample())
+ IntegrityErrorItemView(chat: Chat.sampleData, msgError: .msgBadHash, chatItem: ci).modifier(ChatItemClipped(ci, tailVisible: true))
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift
new file mode 100644
index 0000000000..555ff9d429
--- /dev/null
+++ b/apps/ios/Shared/Views/Chat/ChatItem/MarkdownFileView.swift
@@ -0,0 +1,223 @@
+import SwiftUI
+import SimpleXChat
+import Ink
+
+private let MAX_MARKDOWN_VIEW_SIZE: Int64 = 1_048_576
+private let MAX_MARKDOWN_LINE_LENGTH = 15_000
+private let MAX_MARKDOWN_NESTING = 16
+private let MAX_MARKDOWN_LINK_NESTING = 4
+private let MAX_MARKDOWN_TABLE_ROWS = 200
+private let MAX_MARKDOWN_IMAGE_DIMENSION: CGFloat = 4320
+private let MAX_MARKDOWN_IMAGE_PIXELS: CGFloat = 2160 * 4320
+
+func isMarkdownFile(_ file: CIFile) -> Bool {
+ let ext = (file.fileName as NSString).pathExtension.lowercased()
+ return file.fileSize <= MAX_MARKDOWN_VIEW_SIZE && (ext == "md" || ext == "markdown")
+}
+
+func showMarkdownFile(_ file: CIFile) {
+ guard let fileSource = getLoadedFileSource(file) else { return }
+ Task {
+ do {
+ let data = try getFileData(getAppFilePath(fileSource.filePath), fileSource.cryptoArgs)
+ let text = decodedText(data)
+ let lines = text.components(separatedBy: "\n")
+ let html = withinMarkdownLimits(lines) ? htmlShowingTagsAsText(text) : nil
+ let shownLines = lines.flatMap(chunkedLine)
+ let hasBidiControls = text.unicodeScalars.contains(where: isBidiControl)
+ await MainActor.run {
+ showAppSheet {
+ MarkdownFileView(file: file, fileSource: fileSource, lines: shownLines, html: html, hasBidiControls: hasBidiControls)
+ }
+ }
+ } catch {
+ await MainActor.run {
+ showAlert(NSLocalizedString("Error reading file", comment: "alert title"), message: error.localizedDescription)
+ }
+ }
+ }
+}
+
+private func decodedText(_ data: Data) -> String {
+ var text = String.UnicodeScalarView()
+ var parser = Unicode.UTF8.ForwardParser()
+ var bytes = data.makeIterator()
+ while true {
+ switch parser.parseScalar(from: &bytes) {
+ case let .valid(encoded): text.append(replacingControlChar(Unicode.UTF8.decode(encoded)))
+ case let .error(length): text.append(contentsOf: repeatElement("?" as Unicode.Scalar, count: length))
+ case .emptyInput: return String(text).replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
+ }
+ }
+}
+
+private func replacingControlChar(_ s: Unicode.Scalar) -> Unicode.Scalar {
+ s.value < 0x20 && s != "\t" && s != "\n" && s != "\r" ? "?" : s
+}
+
+// decodedText replaces control characters, so the text has no U+0001 of its own
+private let lessThanStandIn = "\u{1}"
+
+private func htmlShowingTagsAsText(_ text: String) -> String {
+ MarkdownParser(modifiers: [imagesWithinBudget()])
+ .html(from: text.replacingOccurrences(of: "<", with: lessThanStandIn, options: .literal))
+ .replacingOccurrences(of: lessThanStandIn, with: "<", options: .literal)
+}
+
+private func withinMarkdownLimits(_ lines: [String]) -> Bool {
+ var tableRows = 0
+ var linkNesting = 0
+ for line in lines {
+ tableRows = line.contains("|") ? tableRows + 1 : 0
+ if line.count > MAX_MARKDOWN_LINE_LENGTH || nestingLevel(line) > MAX_MARKDOWN_NESTING || tableRows > MAX_MARKDOWN_TABLE_ROWS || !linkNestingWithinLimit(line, &linkNesting) {
+ return false
+ }
+ }
+ return true
+}
+
+private func linkNestingWithinLimit(_ line: String, _ nesting: inout Int) -> Bool {
+ if line.isEmpty { nesting = 0 }
+ for c in line {
+ if c == "[" {
+ nesting += 1
+ if nesting > MAX_MARKDOWN_LINK_NESTING { return false }
+ } else if c == "]" && nesting > 0 {
+ nesting -= 1
+ }
+ }
+ return true
+}
+
+private func nestingLevel(_ line: String) -> Int {
+ let content = line.drop(while: { $0 == " " || $0 == "\t" || $0 == ">" })
+ let prefix = line[.." }.count
+ let listItem = content.first.map { "-*+".contains($0) || $0.isNumber } ?? false
+ return quotes + (listItem ? (prefix.count - quotes) / 2 : 0)
+}
+
+private func chunkedLine(_ line: String) -> [String] {
+ let chars = Array(line)
+ return stride(from: 0, to: max(chars.count, 1), by: MAX_MARKDOWN_LINE_LENGTH).map {
+ String(chars[$0 ..< min($0 + MAX_MARKDOWN_LINE_LENGTH, chars.count)])
+ }
+}
+
+private func escapedHTML(_ s: Substring) -> String {
+ s.replacingOccurrences(of: "&", with: "&")
+ .replacingOccurrences(of: "<", with: "<")
+ .replacingOccurrences(of: ">", with: ">")
+}
+
+private func imagesWithinBudget() -> Modifier {
+ var pixels = MAX_MARKDOWN_IMAGE_PIXELS
+ return Modifier(target: .images) { image in
+ let src = image.html.dropFirst(" "
+ }
+}
+
+private func isBidiControl(_ s: Unicode.Scalar) -> Bool {
+ [0x061C, 0x200E, 0x200F].contains(s.value) || (0x202A...0x202E).contains(s.value) || (0x2066...0x2069).contains(s.value)
+}
+
+private func withInvisibleCharMarkers(_ line: String) -> Text {
+ var text = Text(verbatim: "")
+ var plain = ""
+ for s in line.unicodeScalars {
+ if s.properties.generalCategory == .format {
+ text = text + Text(verbatim: plain) + Text(verbatim: unicodeMarker(s)).foregroundColor(.orange)
+ plain = ""
+ } else {
+ plain.unicodeScalars.append(s)
+ }
+ }
+ return text + Text(verbatim: plain)
+}
+
+private func openMarkdownFileLink(_ url: URL) {
+ let uri = url.absoluteString
+ let parsed = parseSimpleXMarkdown(uri)
+ let format = parsed?.count == 1 ? parsed?.first?.format : nil
+ switch format {
+ case let .simplexLink(_, _, simplexUri, _)?:
+ if let simplexUrl = URL(string: simplexUri) {
+ ChatModel.shared.appOpenUrl = simplexUrl
+ } else {
+ showInvalidLinkAlert(uri)
+ }
+ case .uri? where uri.hasPrefix("https://") || uri.hasPrefix("http://"):
+ openBrowserAlert(uri: uri)
+ default:
+ showInvalidLinkAlert(uri)
+ }
+}
+
+struct MarkdownFileView: View {
+ @AppStorage(DEFAULT_MARKDOWN_FILE_TEXT_VIEW) private var textView = false
+ let file: CIFile
+ let fileSource: CryptoFile
+ let lines: [String]
+ let html: String?
+ let hasBidiControls: Bool
+
+ var body: some View {
+ NavigationView {
+ VStack(spacing: 0) {
+ if hasBidiControls {
+ Text("This file has text direction characters. The text can be shown in a different order than it is written.")
+ .foregroundColor(.orange)
+ .padding()
+ }
+ if let html, !textView {
+ ConditionsWebView(html: html, openLink: openMarkdownFileLink)
+ .padding(.horizontal)
+ } else {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(lines.indices, id: \.self) { i in
+ withInvisibleCharMarkers(lines[i])
+ .font(.system(.body, design: .monospaced))
+ .textSelection(.enabled)
+ }
+ }
+ .padding()
+ }
+ }
+ }
+ .modifier(ThemedBackground())
+ .navigationTitle(file.fileName)
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItemGroup(placement: .navigationBarTrailing) {
+ if html != nil {
+ Button {
+ textView.toggle()
+ } label: {
+ Image(systemName: textView ? "doc.richtext" : "chevron.left.forwardslash.chevron.right")
+ }
+ }
+ Button {
+ saveCryptoFile(fileSource)
+ } label: {
+ Image(systemName: "square.and.arrow.up")
+ }
+ }
+ }
+ }
+ .navigationViewStyle(.stack)
+ }
+}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MarkedDeletedItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MarkedDeletedItemView.swift
index 953f4e8c82..9bfbffc18a 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/MarkedDeletedItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/MarkedDeletedItemView.swift
@@ -20,13 +20,18 @@ struct MarkedDeletedItemView: View {
var chatItem: ChatItem
var body: some View {
- (Text(mergedMarkedDeletedText).italic() + textSpace + chatItem.timestampText)
- .font(.caption)
- .foregroundColor(theme.colors.secondary)
- .padding(.horizontal, 12)
- .padding(.vertical, 6)
- .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
- .textSelection(.disabled)
+ ItemWithMeta {
+ CIMetaView(chat: chat, chatItem: chatItem, metaColor: theme.colors.secondary)
+ } content: { inlineMeta in
+ (inlineMeta == nil ? Text(mergedMarkedDeletedText).italic() : Text(mergedMarkedDeletedText).italic() + textSpace + chatItem.timestampText)
+ .font(.caption)
+ .foregroundColor(theme.colors.secondary)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background { chatItemFrameColor(chatItem, theme).modifier(ChatTailPadding()) }
+ .if(inlineMeta == nil) { $0.modifier(ChatItemClipped(chatItem, tailVisible: false)) }
+ .textSelection(.disabled)
+ }
}
var mergedMarkedDeletedText: LocalizedStringKey {
@@ -86,11 +91,12 @@ struct MarkedDeletedItemView: View {
struct MarkedDeletedItemView_Previews: PreviewProvider {
static var previews: some View {
Group {
+ let ci = ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: previewDate))
MarkedDeletedItemView(
chat: Chat.sampleData,
im: ItemsModel.shared,
- chatItem: ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: .now))
- ).environment(\.revealed, true)
+ chatItem: ci
+ ).environment(\.revealed, true).modifier(ChatItemClipped(ci, tailVisible: true))
}
.previewLayout(.fixed(width: 360, height: 200))
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift
index c9d8858fa1..b07a36cf07 100644
--- a/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItem/MsgContentView.swift
@@ -29,9 +29,11 @@ struct MsgContentView: View {
@ObservedObject var chat: Chat
@Environment(\.showTimestamp) var showTimestamp: Bool
@Environment(\.containerBackground) var containerBackground: UIColor
+ @Environment(\.terminalLayout) private var terminal
@EnvironmentObject var theme: AppTheme
var text: String
var formattedText: [FormattedText]? = nil
+ var markdownBlocks: [MarkdownBlock]? = nil
var textStyle: UIFont.TextStyle
var sender: String? = nil
var meta: CIMeta? = nil
@@ -40,6 +42,12 @@ struct MsgContentView: View {
var rightToLeft = false
var prefix: NSAttributedString? = nil
var stripLink: String? = nil
+ var blockLayout = false
+ var cardColor: Color? = nil
+ var encrypted: Bool? = nil
+ var signedFileVerified: Bool? = nil
+ var textColor: Color? = nil
+ var ruleMinWidth: CGFloat = 0
@State private var showSecrets: Set = []
@State private var typingIdx = 0
@State private var timer: Timer?
@@ -49,9 +57,10 @@ struct MsgContentView: View {
@AppStorage(DEFAULT_SHOW_SENT_VIA_RPOXY) private var showSentViaProxy = false
@AppStorage(DEFAULT_PRIVACY_SHOW_SIGNATURE) private var showSignature = true
+ @AppStorage(DEFAULT_PRIVACY_SHOW_FILE_ENCRYPTION) private var showFileEncryption = true
var body: some View {
- let v = msgContentView()
+ let v = contentView()
if meta?.isLive == true {
v.onAppear {
let descr = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body)
@@ -95,11 +104,76 @@ struct MsgContentView: View {
typingIdx = 0
}
+ @ViewBuilder
+ private func contentView() -> some View {
+ let fts = if let stripLink { stripFormattedTextLink(formattedText, stripLink) } else { formattedText }
+ if blockLayout, let fts, !fts.isEmpty, let blocks = markdownBlocks, prefix == nil || !blockTextRanges(blocks).isEmpty {
+ MarkdownBlocksView(
+ formattedText: fts,
+ blocks: blocks,
+ text: text,
+ textStyle: textStyle,
+ cardColor: cardColor ?? theme.appColors.receivedQuote,
+ rightToLeft: rightToLeft,
+ blockText: { index, range, font, secretStart, last, textAlpha in blockTextView(fts, blocks, index, range, font, secretStart, last, textAlpha) },
+ metaLine: { metaLineView(afterEmptyLines: $0) },
+ marksLastBlock: terminal && meta?.isLive != true,
+ ruleWidthText: terminal ? meta.map { reserveSpaceForMeta($0) } : nil,
+ ruleMinWidth: ruleMinWidth,
+ chatHeadings: true
+ )
+ } else {
+ msgContentView()
+ }
+ }
+
+ private func blockTextView(_ fts: [FormattedText], _ blocks: [MarkdownBlock], _ index: Int, _ range: Range, _ font: UIFont, _ secretStart: Int, _ last: Bool, _ textAlpha: Double) -> some View {
+ let r = messageText(
+ text,
+ fts,
+ markdownBlocks: blocks,
+ textStyle: textStyle,
+ sender: index == 0 ? sender : nil,
+ mentions: mentions,
+ userMemberId: userMemberId,
+ showSecrets: showSecrets,
+ commands: chat.chatInfo.useCommands && chat.chatInfo.sndReady,
+ backgroundColor: containerBackground,
+ prefix: index == 0 ? prefix : nil,
+ range: range,
+ baseFont: font,
+ secretStart: secretStart,
+ textColor: UIColor(messageColor)
+ )
+ let s = r.string
+ let t: Text
+ if last, let mt = meta {
+ if mt.isLive {
+ s.append(typingIndicator(mt.recent))
+ }
+ t = Text(AttributedString(s)) + reserveSpaceForMeta(mt)
+ } else {
+ t = Text(AttributedString(s))
+ }
+ let bodyFont = UIFont.preferredFont(forTextStyle: textStyle)
+ let box = terminal ? terminalLineBox(font, messageColor.opacity(textAlpha), theme, capsOf: font.pointSize > bodyFont.pointSize ? bodyFont : nil) : nil
+ return msgTextView(r, t, box)
+ }
+
+ @ViewBuilder
+ private func metaLineView(afterEmptyLines: Bool) -> some View {
+ if let mt = meta, !terminal || mt.isLive || afterEmptyLines {
+ ((mt.isLive ? Text(AttributedString(typingIndicator(mt.recent))) : Text(verbatim: "")) + reserveSpaceForMeta(mt, newLine: false))
+ .if(terminal && afterEmptyLines) { $0.modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: textStyle), messageColor, theme)) }
+ }
+ }
+
@inline(__always)
private func msgContentView() -> some View {
let r = messageText(
text,
formattedText,
+ markdownBlocks: blockLayout ? nil : markdownBlocks,
textStyle: textStyle,
sender: sender,
mentions: mentions,
@@ -108,7 +182,8 @@ struct MsgContentView: View {
commands: chat.chatInfo.useCommands && chat.chatInfo.sndReady,
backgroundColor: containerBackground,
prefix: prefix,
- stripLink: stripLink
+ stripLink: stripLink,
+ textColor: UIColor(messageColor)
)
let s = r.string
let t: Text
@@ -120,7 +195,21 @@ struct MsgContentView: View {
} else {
t = Text(AttributedString(s))
}
- return msgTextResultView(r, t, showSecrets: $showSecrets, sendCommand: { cmd in sendCommandMsg(chat, cmd) })
+ let box = terminal ? terminalLineBox(UIFont.preferredFont(forTextStyle: textStyle), messageColor, theme) : nil
+ return msgTextView(r, t, box)
+ }
+
+ @ViewBuilder private func msgTextView(_ r: MsgTextResult, _ t: Text, _ box: TerminalLineBox?) -> some View {
+ let v = msgTextResultView(r, t, showSecrets: $showSecrets, sendCommand: { cmd in sendCommandMsg(chat, cmd) }, lineSpacing: box?.spacing ?? 0)
+ if let box {
+ v.modifier(box)
+ } else {
+ v
+ }
+ }
+
+ private var messageColor: Color {
+ textColor ?? messageTextColor(theme)
}
@inline(__always)
@@ -131,11 +220,24 @@ struct MsgContentView: View {
}
@inline(__always)
- private func reserveSpaceForMeta(_ mt: CIMeta) -> Text {
- (rightToLeft ? textNewLine : Text(verbatim: " ")) + ciMetaText(mt, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, showSignature: showSignature)
+ private func reserveSpaceForMeta(_ mt: CIMeta, newLine: Bool = true) -> Text {
+ if terminal {
+ let separator = rightToLeft && newLine ? textNewLine : metaCopyJoiner(rightToLeft) + Text(verbatim: "\u{00A0}\u{00A0}\u{00A0}")
+ return separator + ciMetaText(mt, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: encrypted, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, signedFileVerified: signedFileVerified, showSignature: showSignature, showFileEncryption: showFileEncryption, unbreakable: true)
+ }
+ return (rightToLeft && newLine ? textNewLine : Text(verbatim: " ")) + ciMetaText(mt, chatTTL: chat.chatInfo.timedMessagesTTL, encrypted: nil, colorMode: .transparent, showViaProxy: showSentViaProxy, showTimesamp: showTimestamp, showSignature: showSignature)
}
}
+private func withLineSpacing(_ s: NSAttributedString, _ lineSpacing: CGFloat) -> NSAttributedString {
+ if lineSpacing <= 0 { return s }
+ let spaced = NSMutableAttributedString(attributedString: s)
+ let style = NSMutableParagraphStyle()
+ style.lineSpacing = lineSpacing
+ spaced.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: spaced.length))
+ return spaced
+}
+
func msgTextResultView(
_ r: MsgTextResult,
_ t: Text,
@@ -143,10 +245,11 @@ func msgTextResultView(
sendCommand: ((String) -> Void)? = nil,
openModal: ((Format) -> Void)? = nil,
centered: Bool = false,
- smallFont: Bool = false
+ smallFont: Bool = false,
+ lineSpacing: CGFloat = 0
) -> some View {
t.if(r.hasSecrets, transform: hiddenSecretsView)
- .if(r.handleTaps) { $0.overlay(handleTextTaps(r.string, showSecrets: showSecrets, sendCommand: sendCommand, openModal: openModal, centered: centered, smallFont: smallFont)) }
+ .if(r.handleTaps) { $0.overlay(handleTextTaps(r.string, showSecrets: showSecrets, sendCommand: sendCommand, openModal: openModal, centered: centered, smallFont: smallFont, lineSpacing: lineSpacing)) }
}
// smallFont parameter is used to pad height, otherwise CTFrameGetLines fails to see them as lines - it's needed if font is not .body
@@ -157,7 +260,8 @@ private func handleTextTaps(
sendCommand: ((String) -> Void)? = nil,
openModal: ((Format) -> Void)? = nil,
centered: Bool,
- smallFont: Bool
+ smallFont: Bool,
+ lineSpacing: CGFloat
) -> some View {
return GeometryReader { g in
Rectangle()
@@ -166,7 +270,7 @@ private func handleTextTaps(
.simultaneousGesture(DragGesture(minimumDistance: 0).onEnded { event in
let t = event.translation
if t.width * t.width + t.height * t.height > 100 { return }
- let framesetter = CTFramesetterCreateWithAttributedString(s as CFAttributedString)
+ let framesetter = CTFramesetterCreateWithAttributedString(withLineSpacing(s, lineSpacing) as CFAttributedString)
let paddedSize = smallFont ? CGSize(width: g.size.width, height: g.size.height + 1.0) : g.size
let path = CGPath(rect: CGRect(origin: .zero, size: paddedSize), transform: nil)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, s.length), path, nil)
@@ -317,8 +421,11 @@ private struct FullProfileDescriptionView: View {
.listRowBackground(Color.clear)
Section {
- let r = markdownText(description, showSecrets: showSecrets, backgroundColor: theme.colors.background)
- msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
+ let parsed = parseSimpleXMarkdownText(description)
+ MarkdownView(
+ text: description, formattedText: parsed?.formattedText, markdownBlocks: parsed?.markdownBlocks,
+ backgroundColor: theme.colors.background, cardColor: theme.appColors.receivedQuote, showSecrets: $showSecrets
+ )
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
}
@@ -338,9 +445,11 @@ func markdownText(
showSecrets: Set? = nil,
backgroundColor: Color
) -> MsgTextResult {
- messageText(
+ let parsed = parseSimpleXMarkdownText(s)
+ return messageText(
s,
- parseSimpleXMarkdown(s),
+ parsed?.formattedText,
+ markdownBlocks: parsed?.markdownBlocks,
textStyle: textStyle,
sender: sender,
preview: preview,
@@ -396,6 +505,7 @@ func markdownProfileDescription(
func messageText(
_ text: String,
_ formattedText: [FormattedText]?,
+ markdownBlocks: [MarkdownBlock]? = nil,
textStyle: UIFont.TextStyle = .body,
sender: String?,
preview: Bool = false,
@@ -405,21 +515,25 @@ func messageText(
commands: Bool = false,
backgroundColor: UIColor,
prefix: NSAttributedString? = nil,
- stripLink: String? = nil
+ stripLink: String? = nil,
+ range: Range? = nil,
+ baseFont: UIFont? = nil,
+ secretStart: Int = 0,
+ textColor: UIColor = .label
) -> MsgTextResult {
let text = if let stripLink { stripTextLink(text, stripLink) } else { text }
let formattedText = if let stripLink { stripFormattedTextLink(formattedText, stripLink) } else { formattedText }
let res = NSMutableAttributedString()
- let descr = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
- let font = UIFont.preferredFont(forTextStyle: textStyle)
+ let descr = baseFont?.fontDescriptor ?? UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
+ let font = baseFont ?? UIFont.preferredFont(forTextStyle: textStyle)
let plain: [NSAttributedString.Key: Any] = [
.font: font,
- .foregroundColor: UIColor.label
+ .foregroundColor: textColor
]
let secretColor = backgroundColor.withAlphaComponent(1)
- var link: [NSAttributedString.Key: Any]?
var hasSecrets = false
var handleTaps = false
+ var secretIdx: Int = secretStart
if let sender {
if preview {
@@ -437,19 +551,57 @@ func messageText(
}
if let fts = formattedText, fts.count > 0 {
+ if let range {
+ let start = min(max(range.lowerBound, 0), fts.count)
+ appendSegments(fts[start.. (descr: UIFontDescriptor, font: UIFont) {
+ if !heading { return (descr, font) }
+ let d = descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]])
+ return (d, UIFont(descriptor: d, size: d.pointSize))
+ }
+
+ func appendSegments(_ fts: ArraySlice, _ heading: Bool) {
+ let (descr, font) = segmentFonts(heading)
+ let plain: [NSAttributedString.Key: Any] = [
+ .font: font,
+ .foregroundColor: textColor
+ ]
+ var link: [NSAttributedString.Key: Any]?
var bold: UIFont?
var italic: UIFont?
var snippet: UIFont?
var small: UIFont?
var mention: UIFont?
- var secretIdx: Int = 0
for ft in fts {
var t = ft.text
var attrs = plain
switch (ft.format) {
- case .bold:
- bold = bold ?? UIFont(descriptor: descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]]), size: descr.pointSize)
- attrs[.font] = bold
+ case let .bold(singleStar):
+ if singleStar {
+ italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize)
+ attrs[.font] = italic
+ } else {
+ bold = bold ?? UIFont(descriptor: descr.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]]), size: descr.pointSize)
+ attrs[.font] = bold
+ }
case .italic:
italic = italic ?? UIFont(descriptor: descr.withSymbolicTraits(.traitItalic) ?? descr, size: descr.pointSize)
attrs[.font] = italic
@@ -490,12 +642,13 @@ func messageText(
attrs[webLinkAttrKey] = true
handleTaps = true
}
+ t = displayedUri(t)
case let .hyperLink(text, uri):
attrs = linkAttrs()
if let text { t = text }
if !preview {
attrs[linkAttrKey] = uri
- attrs[webLinkAttrKey] = true
+ if !ft.isEmailLink { attrs[webLinkAttrKey] = true }
handleTaps = true
}
case let .simplexLink(text, linkType, simplexUri, smpHosts):
@@ -512,10 +665,10 @@ func messageText(
t = viaHost(smpHosts)
}
case let .command(cmdStr):
- snippet = snippet ?? UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: .regular)
- attrs[.font] = snippet
- t = "/" + cmdStr
if !preview && commands {
+ snippet = snippet ?? UIFont.monospacedSystemFont(ofSize: descr.pointSize, weight: .regular)
+ attrs[.font] = snippet
+ t = "/" + cmdStr
attrs[.foregroundColor] = uiLinkColor
attrs[commandAttrKey] = t
handleTaps = true
@@ -562,24 +715,397 @@ func messageText(
attrs[modalAttrKey] = Format.modal(modalName: modalName, text: text)
handleTaps = true
}
+ case .escape: t = ""
+ case let .markup(token):
+ if range != nil { t = token.drawnText } else if markdownBlocks != nil { t = token.previewText }
case .unknown: ()
case .none: ()
}
res.append(NSAttributedString(string: t, attributes: attrs))
}
- } else {
- res.append(NSMutableAttributedString(string: text, attributes: plain))
- }
-
- return (string: res, hasSecrets: hasSecrets, handleTaps: handleTaps)
- func linkAttrs() -> [NSAttributedString.Key: Any] {
- link = link ?? [
- .font: font,
- .foregroundColor: uiLinkColor,
- .underlineStyle: NSUnderlineStyle.single.rawValue
- ]
- return link!
+ func linkAttrs() -> [NSAttributedString.Key: Any] {
+ link = link ?? [
+ .font: font,
+ .foregroundColor: uiLinkColor,
+ .underlineStyle: NSUnderlineStyle.single.rawValue
+ ]
+ return link!
+ }
+ }
+}
+
+let swipeExclusionSpace = "swipeExclusion"
+
+private let maxGridCells = 1000
+
+struct SwipeExclusionFrames: PreferenceKey {
+ static var defaultValue: [CGRect] = []
+
+ static func reduce(value: inout [CGRect], nextValue: () -> [CGRect]) {
+ value += nextValue()
+ }
+}
+
+struct MarkdownView: View {
+ @EnvironmentObject var theme: AppTheme
+ var text: String
+ var formattedText: [FormattedText]?
+ var markdownBlocks: [MarkdownBlock]?
+ var sender: String? = nil
+ var mentions: [String: CIMention]? = nil
+ var userMemberId: String? = nil
+ var backgroundColor: Color
+ var cardColor: Color
+ @Binding var showSecrets: Set
+
+ var body: some View {
+ if let fts = formattedText, !fts.isEmpty, let blocks = markdownBlocks {
+ MarkdownBlocksView(
+ formattedText: fts,
+ blocks: blocks,
+ text: text,
+ textStyle: .body,
+ cardColor: cardColor,
+ rightToLeft: isRightToLeft(text),
+ blockText: { index, range, font, secretStart, _, _ in
+ let r = messageText(
+ text, fts, markdownBlocks: blocks, sender: index == 0 ? sender : nil, mentions: mentions, userMemberId: userMemberId,
+ showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor), range: range, baseFont: font, secretStart: secretStart,
+ textColor: UIColor(messageTextColor(theme))
+ )
+ msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
+ },
+ metaLine: { _ in EmptyView() }
+ )
+ } else {
+ let r = messageText(text, formattedText, sender: sender, mentions: mentions, userMemberId: userMemberId, showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor), textColor: UIColor(messageTextColor(theme)))
+ msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
+ }
+ }
+}
+
+private struct BlocksLayout {
+ let font: UIFont
+ let starts: [Int]
+ let secrets: [Int]
+ let trailingEmptyLines: Int
+ let lastIsText: Bool
+
+ init(_ fts: [FormattedText], _ blocks: [MarkdownBlock], _ textStyle: UIFont.TextStyle, text: String) {
+ font = UIFont.preferredFont(forTextStyle: textStyle)
+ starts = blocks.reduce(into: [0]) { $0.append($0[$0.count - 1] + $1.textRanges.count) }
+ secrets = fts.reduce(into: [0]) { $0.append($0[$0.count - 1] + ($1.isSecret ? 1 : 0)) }
+ trailingEmptyLines = emptyLines(fts, blocks.last?.endIndex ?? 0, fts.count, between: text.unicodeScalars.last != "\n")
+ lastIsText = switch blocks.last {
+ case .paragraph, .heading, .quote, .list: trailingEmptyLines == 0
+ default: false
+ }
+ }
+}
+
+struct MarkdownBlocksView: View {
+ @AppStorage(DEFAULT_CHAT_ITEM_ROUNDNESS) private var roundness = defaultChatItemRoundness
+ @Environment(\.terminalLayout) private var terminal
+ var formattedText: [FormattedText]
+ var blocks: [MarkdownBlock]
+ var text: String
+ var textStyle: UIFont.TextStyle
+ var cardColor: Color
+ var rightToLeft: Bool
+ @ViewBuilder var blockText: (_ index: Int, _ range: Range, _ font: UIFont, _ secretStart: Int, _ last: Bool, _ textAlpha: Double) -> BlockText
+ @ViewBuilder var metaLine: (_ afterEmptyLines: Bool) -> MetaLine
+ var marksLastBlock = false
+ var ruleWidthText: Text? = nil
+ var ruleMinWidth: CGFloat = 0
+ var chatHeadings = false
+
+ var body: some View {
+ let l = BlocksLayout(formattedText, blocks, textStyle, text: text)
+ VStack(alignment: .leading, spacing: 0) {
+ emptyLinesGap(leadingEmptyLines(formattedText, blocks), l, between: false)
+ ForEach(Array(blocks.enumerated()), id: \.offset) { k, block in
+ let emptyHeight = k > 0 ? emptyLinesHeight(emptyLines(formattedText, blocks[k - 1].endIndex, block.startIndex, between: true), l) : 0
+ if k > 0 && terminal && (blocks[k - 1].isCard || block.isCard) {
+ Color.clear.frame(width: 0, height: max(terminalParagraphGap, emptyHeight))
+ } else if k > 0 && terminal && blocks[k - 1].isHeading && !block.isHeading {
+ Color.clear.frame(width: 0, height: terminalHeadingBottomGap + emptyHeight)
+ } else if k > 0 && terminal && block.isHeading {
+ Color.clear.frame(width: 0, height: terminalLevelStep + emptyHeight)
+ } else if emptyHeight > 0 {
+ Color.clear.frame(width: 0, height: emptyHeight)
+ }
+ blockView(block, l.starts[k], l, last: k == blocks.count - 1 && l.trailingEmptyLines == 0)
+ }
+ emptyLinesGap(l.trailingEmptyLines, l)
+ if !l.lastIsText {
+ metaLine(l.trailingEmptyLines > 0)
+ }
+ }
+ .multilineTextAlignment(.leading)
+ .environment(\.layoutDirection, rightToLeft ? .rightToLeft : .leftToRight)
+ }
+
+ private func text(_ index: Int, _ r: SegmentRange, _ font: UIFont, _ l: BlocksLayout, textAlpha: Double = 1) -> BlockText {
+ blockText(index, r.from.. some View {
+ switch block {
+ case let .paragraph(content):
+ text(start, content, l.font, l)
+ case let .heading(level, content):
+ text(start, content, terminal || chatHeadings ? terminalHeadingFont(l.font, level) : headingFont(l.font, level), l)
+ case let .quote(content):
+ HStack(alignment: .top, spacing: 10) {
+ quoteBar()
+ text(start, content, l.font, l, textAlpha: 0.72).opacity(0.72)
+ }
+ .fixedSize(horizontal: false, vertical: true)
+ case let .list(items):
+ let entries = listEntries(items, 0)
+ ForEach(Array(entries.enumerated()), id: \.offset) { j, e in
+ if j > 0 {
+ emptyLinesGap(emptyLines(formattedText, entries[j - 1].entry.content.to, e.entry.content.from, between: true), l)
+ }
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(e.entry.number ?? "•").font(.system(size: l.font.pointSize))
+ text(start + j, e.entry.content, l.font, l)
+ }
+ .padding(.leading, 20 * CGFloat(e.level))
+ }
+ case let .codeBlock(_, content):
+ CodeBlockCard(color: cardColor, radius: 12 * roundness, copyText: codeText(content)) {
+ text(start, content, monospacedFont(l.font), l).fixedSize(horizontal: true, vertical: false)
+ }
+ .if(terminal) { cardMargins($0, last) }
+ case let .table(columns, header, rows):
+ tableView(columns, [header] + rows, start, l)
+ .if(terminal) { cardMargins($0.alignmentGuide(.lastTextBaseline) { d in d[explicit: .lastTextBaseline] ?? d[.bottom] - 4 + l.font.descender }, last) }
+ case .rule:
+ if terminal {
+ cardMargins(terminalRule(), last)
+ } else {
+ Rectangle().fill(Color(uiColor: .secondaryLabel).opacity(0.35)).frame(height: 1).padding(.vertical, 6)
+ }
+ }
+ }
+
+ private func cardMargins(_ block: some View, _ last: Bool) -> some View {
+ block
+ .if(last && marksLastBlock) { $0.modifier(MessageLastBlock()) }
+ .padding(.bottom, last && !marksLastBlock ? terminalParagraphGap : 0)
+ }
+
+ @ViewBuilder private func terminalRule() -> some View {
+ let rule = Rectangle().fill(Color(uiColor: .secondaryLabel).opacity(0.35)).frame(height: 1)
+ if let ruleWidthText, blocks.allSatisfy({ if case .rule = $0 { true } else { false } }) {
+ ruleWidthText.fixedSize().hidden().frame(minWidth: ruleMinWidth, alignment: .leading).frame(height: 1).overlay(rule)
+ } else {
+ rule
+ }
+ }
+
+ @ViewBuilder private func tableView(_ columns: [TableAlign], _ tableRows: [[SegmentRange]], _ start: Int, _ l: BlocksLayout) -> some View {
+ let rowStarts = tableRows.reduce(into: [start]) { $0.append($0[$0.count - 1] + $1.count) }
+ let columnCount = max(columns.count, tableRows.map(\.count).max() ?? 0)
+ let lineColor = Color(uiColor: .secondaryLabel).opacity(0.35)
+ let radius = 12 * roundness
+ if #available(iOS 16, *) {
+ if columnCount * tableRows.count <= maxGridCells {
+ HScroll {
+ Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {
+ ForEach(Array(tableRows.enumerated()), id: \.offset) { r, row in
+ GridRow {
+ ForEach(0.. some View {
+ let source = tableSource(tableRows)
+ return CodeBlockCard(color: cardColor, radius: radius, copyText: source) {
+ Text(verbatim: source).font(.system(size: l.font.pointSize * 0.875, design: .monospaced)).fixedSize(horizontal: true, vertical: false)
+ }
+ }
+
+ @ViewBuilder private func emptyLinesGap(_ lines: Int, _ l: BlocksLayout, between: Bool = true) -> some View {
+ if lines > 0 {
+ Color.clear.frame(width: 0, height: emptyLinesHeight(lines, l, between: between))
+ }
+ }
+
+ private func emptyLinesHeight(_ lines: Int, _ l: BlocksLayout, between: Bool = true) -> CGFloat {
+ if terminal { return CGFloat(lines) * terminalParagraphGap }
+ let height = CGFloat(lines) * (l.font.lineHeight + l.font.leading)
+ return between && lines > 0 ? height + l.font.leading : height
+ }
+
+ private func codeText(_ r: SegmentRange) -> String {
+ let start = min(max(r.from, 0), formattedText.count)
+ return formattedText[start.. String {
+ let start = min(max((tableRows.first?.first?.from ?? 1) - 1, 0), formattedText.count)
+ let end = min((tableRows.last?.last?.to ?? 0) + 1, formattedText.count)
+ return formattedText[start.. Int {
+ let start = min(max(from, 0), fts.count)
+ let lineBreaks = fts[start.. Int {
+ emptyLines(fts, 0, blocks.first?.startIndex ?? 0, between: false)
+}
+
+let quoteBarWidth: CGFloat = 4
+
+func quoteBar() -> some View {
+ RoundedRectangle(cornerRadius: 2).fill(Color(uiColor: .label).opacity(0.16)).frame(width: quoteBarWidth)
+}
+
+private func headingFont(_ font: UIFont, _ level: Int) -> UIFont {
+ let scale: CGFloat = switch level {
+ case 1: 1.5
+ case 2: 1.3
+ case 3: 1.15
+ default: 1
+ }
+ return UIFont(descriptor: boldFont(font).fontDescriptor, size: font.pointSize * scale)
+}
+
+private func terminalHeadingFont(_ font: UIFont, _ level: Int) -> UIFont {
+ UIFont(descriptor: boldFont(font).fontDescriptor, size: font.pointSize * pow(terminalHeadingRatio, CGFloat(max(0, 3 - level))))
+}
+
+private func boldFont(_ font: UIFont) -> UIFont {
+ UIFont(descriptor: font.fontDescriptor.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: UIFont.Weight.bold]]), size: font.pointSize)
+}
+
+private func monospacedFont(_ font: UIFont) -> UIFont {
+ UIFont.monospacedSystemFont(ofSize: font.pointSize * 0.875, weight: .regular)
+}
+
+private func cellAlignment(_ align: TableAlign) -> Alignment {
+ switch align {
+ case .right: .trailing
+ case .center: .center
+ default: .leading
+ }
+}
+
+private struct CodeBlockCard: View {
+ @EnvironmentObject var theme: AppTheme
+ var color: Color
+ var radius: CGFloat
+ var copyText: String
+ @ViewBuilder var content: () -> Content
+ @State private var showCopy = false
+
+ var body: some View {
+ HScroll {
+ content()
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .overlay(alignment: .topTrailing) {
+ if showCopy {
+ Button {
+ UIPasteboard.general.string = copyText
+ showCopy = false
+ } label: {
+ Image(systemName: "doc.on.doc")
+ .foregroundColor(theme.colors.primary)
+ .frame(width: 28, height: 28)
+ .background(color)
+ .clipShape(RoundedRectangle(cornerRadius: radius * 2 / 3))
+ }
+ .padding(4)
+ }
+ }
+ .background(color)
+ .clipShape(RoundedRectangle(cornerRadius: radius))
+ .onTapGesture { showCopy.toggle() }
+ }
+}
+
+private struct HScroll: View {
+ @ViewBuilder var content: () -> Content
+
+ var body: some View {
+ if #available(iOS 16, *) {
+ ViewThatFits(in: .horizontal) {
+ content()
+ scrollView()
+ }
+ } else {
+ scrollView()
+ }
+ }
+
+ private func scrollView() -> some View {
+ ScrollView(.horizontal, showsIndicators: false) {
+ content()
+ }
+ .background {
+ GeometryReader { g in
+ Color.clear.preference(key: SwipeExclusionFrames.self, value: [g.frame(in: .named(swipeExclusionSpace))])
+ }
+ }
}
}
@@ -607,7 +1133,9 @@ func stripTextLink(_ text: String, _ link: String) -> String {
func stripFormattedTextLink(_ ft: [FormattedText]?, _ link: String) -> [FormattedText]? {
guard var ft, ft.last?.text == link else { return ft }
ft.removeLast()
- if let i = ft.indices.last, ft[i].format == nil, ft[i].text.hasSuffix("\n") {
+ if let i = ft.indices.last, case .markup = ft[i].format {
+ ft.removeLast()
+ } else if let i = ft.indices.last, ft[i].format == nil, ft[i].text.hasSuffix("\n") {
ft[i].text = String(ft[i].text.dropLast())
if ft[i].text.isEmpty { ft.removeLast() }
}
@@ -616,7 +1144,7 @@ func stripFormattedTextLink(_ ft: [FormattedText]?, _ link: String) -> [Formatte
struct MsgContentView_Previews: PreviewProvider {
static var previews: some View {
- let chatItem = ChatItem.getSample(1, .directSnd, .now, "hello")
+ let chatItem = ChatItem.getSample(1, .directSnd, previewDate, "hello")
return MsgContentView(
chat: Chat.sampleData,
text: chatItem.text,
diff --git a/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift b/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift
new file mode 100644
index 0000000000..f8ff86e3d3
--- /dev/null
+++ b/apps/ios/Shared/Views/Chat/ChatItem/TerminalItemView.swift
@@ -0,0 +1,427 @@
+import SwiftUI
+import SimpleXChat
+
+extension EnvironmentValues {
+ struct TerminalLayout: EnvironmentKey {
+ static let defaultValue: Bool = false
+ }
+
+ var terminalLayout: Bool {
+ get { self[TerminalLayout.self] }
+ set { self[TerminalLayout.self] = newValue }
+ }
+}
+
+let chatItemTextPadding: CGFloat = 12
+var terminalParagraphGap: CGFloat { terminalGap(terminalGapBodySize * terminalLineHeightRatio / 3) }
+var terminalLevelStep: CGFloat { terminalGap(4.75) }
+var terminalHeadingBottomGap: CGFloat { terminalLevelStep / 2 }
+var terminalHeaderTopGap: CGFloat { terminalGap(2.5) }
+var terminalHeaderBottomGap: CGFloat { terminalGap(1.5) }
+var terminalMetaGap: CGFloat { terminalGap(6) }
+var terminalNameSize: CGFloat { bodyScaled(13.5 * 17 / 16) }
+let terminalHeadingRatio: CGFloat = 1.25
+private let terminalLineHeightRatio: CGFloat = 22 / 16
+private let terminalLineHeightContrastSlope: CGFloat = 0.1515
+private let terminalGapBodySize: CGFloat = 16
+private let terminalNameRepeatInterval: TimeInterval = 7.5 * 60
+
+func terminalGap(_ size: CGFloat) -> CGFloat {
+ size * UIFont.preferredFont(forTextStyle: .body).pointSize / terminalGapBodySize
+}
+
+func bodyScaled(_ points: CGFloat) -> CGFloat {
+ UIFontMetrics(forTextStyle: .body).scaledValue(for: points)
+}
+
+func messageTextColor(_ theme: AppTheme) -> Color {
+ theme.colors.onSurface.opacity(theme.colors.isLight ? 1 : 0.95)
+}
+
+func terminalBackgroundColor(_ theme: AppTheme) -> Color {
+ theme.wallpaper.background ?? theme.wallpaper.type.defaultBackgroundColor(theme.base, theme.colors.background)
+}
+
+struct TerminalLineBox: ViewModifier {
+ var spacing: CGFloat
+ var top: CGFloat
+ var bottom: CGFloat
+
+ func body(content: Content) -> some View {
+ content
+ .lineSpacing(spacing)
+ .padding(.top, top)
+ .padding(.bottom, bottom)
+ }
+}
+
+func terminalLineBox(_ font: UIFont, _ color: Color?, _ theme: AppTheme, capsOf bodyFont: UIFont? = nil) -> TerminalLineBox {
+ if let bodyFont {
+ let bodyLineHeight = bodyFont.pointSize * terminalLineHeightRatio
+ let body = proportionalExtra(bodyFont, bodyLineHeight)
+ return TerminalLineBox(
+ spacing: max(0, bodyLineHeight * font.pointSize / bodyFont.pointSize - font.lineHeight),
+ top: body.top + bodyFont.ascender - bodyFont.capHeight - (font.ascender - font.capHeight),
+ bottom: body.bottom - bodyFont.descender + font.descender
+ )
+ }
+ let lineHeight = terminalLineHeight(font, color, theme)
+ let extra = proportionalExtra(font, lineHeight)
+ return TerminalLineBox(spacing: max(0, lineHeight - font.lineHeight), top: extra.top, bottom: extra.bottom)
+}
+
+func terminalLineHeight(_ font: UIFont, _ color: Color?, _ theme: AppTheme) -> CGFloat {
+ font.pointSize * terminalLineHeightRatio * contrastLineHeightFactor(color, theme)
+}
+
+private func proportionalExtra(_ font: UIFont, _ lineHeight: CGFloat) -> (top: CGFloat, bottom: CGFloat) {
+ let extra = max(0, lineHeight - font.lineHeight)
+ let ascent = font.ascender
+ let descent = -font.descender
+ return (extra * ascent / (ascent + descent), extra * descent / (ascent + descent))
+}
+
+private func contrastLineHeightFactor(_ color: Color?, _ theme: AppTheme) -> CGFloat {
+ guard let color else { return 1 }
+ let background = UIColor(theme.colors.background)
+ let textContrast = lightnessContrast(UIColor(messageTextColor(theme)), background)
+ let weight = textContrast > 0 ? min(max(lightnessContrast(UIColor(color), background) / textContrast, 0), 1) : 1
+ return 1 - terminalLineHeightContrastSlope * (1 - weight)
+}
+
+private func lightnessContrast(_ color: UIColor, _ background: UIColor) -> CGFloat {
+ abs(lightness(composited(color, over: background)) - lightness(background))
+}
+
+private func lightness(_ color: UIColor) -> CGFloat {
+ let y = luminance(color)
+ return y > 216 / 24389 ? 116 * pow(y, 1 / 3) - 16 : y * 24389 / 27
+}
+
+private func luminance(_ color: UIColor) -> CGFloat {
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
+ color.getRed(&r, green: &g, blue: &b, alpha: &a)
+ func linear(_ v: CGFloat) -> CGFloat {
+ v <= 0.04045 ? v / 12.92 : pow((v + 0.055) / 1.055, 2.4)
+ }
+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
+}
+
+private func composited(_ color: UIColor, over background: UIColor) -> UIColor {
+ var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
+ var br: CGFloat = 0, bg: CGFloat = 0, bb: CGFloat = 0, ba: CGFloat = 0
+ color.getRed(&r, green: &g, blue: &b, alpha: &a)
+ background.getRed(&br, green: &bg, blue: &bb, alpha: &ba)
+ return UIColor(red: r * a + br * (1 - a), green: g * a + bg * (1 - a), blue: b * a + bb * (1 - a), alpha: 1)
+}
+
+func terminalItemShowsSender(_ item: ChatItem, _ older: ChatItem?) -> Bool {
+ guard item.content.hasTerminalSender else { return false }
+ guard let older else { return true }
+ return !older.content.hasTerminalSender || !sameSender(item, older) || item.meta.itemTs.timeIntervalSince(older.meta.itemTs) >= terminalNameRepeatInterval
+}
+
+private func sameSender(_ item: ChatItem, _ older: ChatItem) -> Bool {
+ item.channelIsSender || older.channelIsSender
+ ? item.channelIsSender && older.channelIsSender
+ : item.chatDir.sameDirection(older.chatDir)
+}
+
+func terminalRowGap(_ item: ChatItem, _ older: ChatItem?, separated: Bool, largeGap: Bool, hasSenderRow: Bool) -> CGFloat {
+ guard let older, !separated else { return 0 }
+ return largeGap || hasSenderRow || !item.isOneLine || !older.isOneLine || !older.reactions.isEmpty
+ ? terminalParagraphGap
+ : 0
+}
+
+func terminalItemStartsWithCard(_ item: ChatItem, revealed: Bool) -> Bool {
+ if item.meta.itemDeleted != nil && (!revealed || item.isDeletedContent) { return true }
+ if item.quotedItem != nil { return !item.hasHeaderAboveQuote }
+ if item.hasQuoteOrHeader { return false }
+ guard let mc = item.content.msgContent else {
+ switch item.content {
+ case .sndCall, .rcvCall: return false
+ default: return true
+ }
+ }
+ return terminalMediaCard(item) || item.markdownBlocks?.first?.isCard == true || mc.isText && isShortEmoji(mc.text) || FramedItemView.showsEmoji(item)
+}
+
+func terminalCardTopGap(_ item: ChatItem) -> CGFloat {
+ item.hasQuoteOrHeader ? terminalParagraphGap : 0
+}
+
+func terminalCardBottomGap(_ item: ChatItem) -> CGFloat {
+ item.reactions.isEmpty ? 0 : terminalParagraphGap
+}
+
+func terminalTextTopGap(_ item: ChatItem) -> CGFloat {
+ if item.textAtItemTop {
+ 0
+ } else if item.quotedItem != nil || terminalMediaCard(item) || item.markdownBlocks?.first?.isCard == true {
+ startsWithEmptyLine(item) ? 0 : terminalParagraphGap
+ } else if item.startsWithHeading {
+ terminalLevelStep
+ } else {
+ 0
+ }
+}
+
+private func startsWithEmptyLine(_ item: ChatItem) -> Bool {
+ if let fts = item.formattedText, let blocks = item.markdownBlocks {
+ leadingEmptyLines(fts, blocks) > 0
+ } else {
+ item.content.text.first?.isNewline == true && !item.isReport
+ }
+}
+
+private func terminalMediaCard(_ item: ChatItem) -> Bool {
+ switch item.content.msgContent {
+ case .link, .image, .video, .voice, .file, .chat: true
+ case .unknown: item.file != nil
+ case .text, .report, nil: false
+ }
+}
+
+private enum MessageLastLineRight: AlignmentID {
+ static func defaultValue(in d: ViewDimensions) -> CGFloat { d[.trailing] }
+}
+
+private enum MessageLastBlockBottom: AlignmentID {
+ static func defaultValue(in d: ViewDimensions) -> CGFloat { d[.bottom] }
+}
+
+struct MessageLastLine: ViewModifier {
+ fileprivate static let right = HorizontalAlignment(MessageLastLineRight.self)
+
+ func body(content: Content) -> some View {
+ content.alignmentGuide(Self.right) { $0[.trailing] }
+ }
+}
+
+struct MessageLastBlock: ViewModifier {
+ fileprivate static let bottom = VerticalAlignment(MessageLastBlockBottom.self)
+
+ func body(content: Content) -> some View {
+ content
+ .modifier(MessageLastLine())
+ .alignmentGuide(Self.bottom) { $0[.bottom] }
+ }
+}
+
+func metaCopyJoiner(_ rightToLeft: Bool) -> Text {
+ Text(verbatim: rightToLeft ? "\u{2060}\u{200F}" : "\u{2060}\u{200E}")
+}
+
+struct ItemWithMeta: View {
+ @EnvironmentObject private var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
+ var showMeta = true
+ var metaReserved = false
+ var overlayMeta: AnyView? = nil
+ var endButton: AnyView? = nil
+ var lastBlockGap: CGFloat = 0
+ @ViewBuilder var meta: () -> Meta
+ @ViewBuilder var content: (_ inlineMeta: Meta?) -> Content
+
+ var body: some View {
+ if terminal && showMeta {
+ terminalBody
+ } else {
+ content(showMeta && !terminal ? meta() : nil)
+ }
+ }
+
+ @ViewBuilder private var terminalBody: some View {
+ if #available(iOS 16, *) {
+ TerminalMetaLayout(metaReserved: metaReserved, hasOverlay: overlayMeta != nil, hasEndButton: endButton != nil, lastBlockGap: lastBlockGap) {
+ ZStack(alignment: .topLeading) {
+ content(nil)
+ }
+ metaBox(meta(), theme.colors.secondary)
+ if let overlayMeta {
+ metaBox(overlayMeta, nil)
+ }
+ if let endButton {
+ endButton.padding(.trailing, chatItemTextPadding)
+ }
+ }
+ } else {
+ HStack(alignment: .lastTextBaseline, spacing: 0) {
+ content(nil).frame(maxWidth: .infinity, alignment: .leading)
+ if let endButton {
+ endButton
+ }
+ metaBox(meta(), theme.colors.secondary)
+ }
+ }
+ }
+
+ @ViewBuilder private func metaBox(_ meta: some View, _ lineHeightColor: Color?) -> some View {
+ let v = meta
+ .modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .caption1), lineHeightColor, theme))
+ .padding(.trailing, chatItemTextPadding)
+ if overlayMeta != nil {
+ v.frame(maxWidth: .infinity, maxHeight: .infinity).clipped()
+ } else {
+ v
+ }
+ }
+}
+
+@available(iOS 16, *)
+private struct TerminalMetaLayout: Layout {
+ var metaReserved: Bool
+ var hasOverlay: Bool
+ var hasEndButton: Bool
+ var lastBlockGap: CGFloat
+
+ private struct Placement {
+ var size: CGSize
+ var contentProposal: ProposedViewSize
+ var meta: CGRect?
+ var overlay: CGRect?
+ var endButton: CGRect?
+ }
+
+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
+ placement(proposal.width, subviews).size
+ }
+
+ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
+ let p = placement(bounds.width, subviews)
+ subviews[0].place(at: bounds.origin, proposal: p.contentProposal)
+ place(subviews[1], p.meta, bounds)
+ if hasOverlay {
+ place(subviews[2], p.overlay, bounds)
+ }
+ if hasEndButton {
+ place(subviews[hasOverlay ? 3 : 2], p.endButton, bounds)
+ }
+ }
+
+ private func place(_ subview: LayoutSubview, _ frame: CGRect?, _ bounds: CGRect) {
+ if let frame {
+ subview.place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), proposal: ProposedViewSize(frame.size))
+ } else {
+ subview.place(at: bounds.origin, proposal: .zero)
+ }
+ }
+
+ private func placement(_ proposedWidth: CGFloat?, _ subviews: Subviews) -> Placement {
+ let width = proposedWidth.flatMap { $0.isFinite ? $0 : nil }
+ let meta = subviews[1].sizeThatFits(.unspecified)
+ let overlay = hasOverlay ? subviews[2].sizeThatFits(.unspecified) : nil
+ let endButton = hasEndButton ? subviews[hasOverlay ? 3 : 2].sizeThatFits(.unspecified) : nil
+ let reservedWidth = max(!metaReserved && overlay == nil ? meta.width : 0, endButton?.width ?? 0)
+ let contentProposal = ProposedViewSize(width: width.map { max(0, $0 - reservedWidth) }, height: nil)
+ let content = subviews[0].dimensions(in: contentProposal)
+ let rowWidth = width ?? max(content.width + reservedWidth, meta.width)
+ let gap = terminalMetaGap
+ let metaBelow = content[explicit: MessageLastLine.right].map { $0 + meta.width > rowWidth } ?? false
+ let metaBaseline = subviews[1].dimensions(in: .unspecified)[explicit: .firstTextBaseline]
+ ?? (meta.height + UIFont.preferredFont(forTextStyle: .caption1).capHeight) / 2
+ let textBaseline = overlay == nil ? content[explicit: .lastTextBaseline] : nil
+ let metaTop = max(0, metaBelow
+ ? content.height + gap
+ : textBaseline.map { $0 - metaBaseline } ?? content.height - gap - meta.height
+ )
+ let blockGap = content[explicit: MessageLastBlock.bottom].map { abs($0 - content.height) < 0.5 } == true ? lastBlockGap : 0
+ let overlayFrame: CGRect? = if let overlay, content.width + meta.width > rowWidth {
+ CGRect(x: content.width - overlay.width, y: max(0, content.height - gap - overlay.height), width: overlay.width, height: overlay.height)
+ } else {
+ nil
+ }
+ let endButtonFrame: CGRect? = endButton.map {
+ CGRect(x: rowWidth - $0.width, y: max(0, ((overlayFrame == nil ? metaTop : content.height) - $0.height) / 2), width: $0.width, height: $0.height)
+ }
+ return Placement(
+ size: CGSize(
+ width: rowWidth,
+ height: max(content.height + blockGap, metaTop + meta.height, overlayFrame?.height ?? 0, endButtonFrame?.maxY ?? 0)
+ ),
+ contentProposal: contentProposal,
+ meta: overlayFrame == nil ? CGRect(x: rowWidth - meta.width, y: metaTop, width: meta.width, height: meta.height) : nil,
+ overlay: overlayFrame,
+ endButton: endButtonFrame
+ )
+ }
+}
+
+struct ChatEventWithMeta: View {
+ @EnvironmentObject private var theme: AppTheme
+ @Environment(\.layoutDirection) private var layoutDirection
+ var chatItem: ChatItem
+ @ViewBuilder var content: (_ ts: Text) -> Content
+
+ var body: some View {
+ ItemWithMeta(metaReserved: true) {
+ eventMetaText(color: theme.colors.secondary)
+ } content: { inlineMeta in
+ content(
+ inlineMeta == nil
+ ? (metaCopyJoiner(layoutDirection == .rightToLeft) + Text(verbatim: "\u{00A0}\u{00A0}") + eventMetaText(colorMode: .transparent, unbreakable: true)).fontWeight(.regular)
+ : chatItem.timestampText
+ )
+ }
+ }
+
+ private func eventMetaText(color: Color = .clear, colorMode: MetaColorMode = .normal, unbreakable: Bool = false) -> Text {
+ ciMetaText(chatItem.meta, chatTTL: nil, encrypted: nil, color: color, colorMode: colorMode, showStatus: false, showEdited: false, showViaProxy: false, showTimesamp: true, unbreakable: unbreakable)
+ }
+}
+
+let terminalEventPadding = EdgeInsets(top: 0, leading: chatItemTextPadding, bottom: 0, trailing: chatItemTextPadding)
+
+struct ChatItemSender {
+ var name: Text
+ var badge: LocalBadge?
+ var role: String?
+ var own: Bool
+ var image: AnyView?
+}
+
+struct TerminalChatItemRow: View {
+ @EnvironmentObject private var theme: AppTheme
+ var sender: ChatItemSender?
+ var gutter: CGFloat
+ var topGap: CGFloat
+ var contentStartsWithCard: Bool
+ @ViewBuilder var content: () -> Content
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 0) {
+ if gutter > 0 {
+ ZStack(alignment: .topLeading) {
+ Color.clear.frame(width: gutter, height: 0)
+ sender?.image?.padding(.leading, chatItemTextPadding)
+ }
+ }
+ VStack(alignment: .leading, spacing: 0) {
+ if let sender {
+ senderNameAndRole(sender)
+ .padding(.leading, chatItemTextPadding)
+ .padding(.bottom, contentStartsWithCard ? terminalParagraphGap : 0)
+ }
+ content()
+ }
+ }
+ .padding(.top, topGap)
+ }
+
+ private func senderNameAndRole(_ sender: ChatItemSender) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 0) {
+ NameWithBadge(sender.name.font(.body.weight(.semibold)).foregroundColor(sender.own ? theme.colors.primary : theme.colors.secondary), sender.badge)
+ .lineLimit(1)
+ if let role = sender.role {
+ Text(role)
+ .font(.body.weight(.medium))
+ .foregroundColor(theme.colors.secondary)
+ .lineLimit(1)
+ .padding(.leading, 15)
+ .layoutPriority(1)
+ }
+ }
+ .modifier(terminalLineBox(UIFont.preferredFont(forTextStyle: .body), nil, theme))
+ }
+}
diff --git a/apps/ios/Shared/Views/Chat/ChatItemForwardingView.swift b/apps/ios/Shared/Views/Chat/ChatItemForwardingView.swift
index 92bab973c9..10c3d85dd7 100644
--- a/apps/ios/Shared/Views/Chat/ChatItemForwardingView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItemForwardingView.swift
@@ -129,11 +129,13 @@ struct ChatItemForwardingView: View {
}
}
-#Preview {
- ChatItemForwardingView(
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello")],
- fromChatInfo: .direct(contact: Contact.sampleData),
- composeState: Binding.constant(ComposeState(message: "hello"))
- ).environmentObject(CurrentColors.toAppTheme())
+struct ChatItemForwardingView_Previews: PreviewProvider {
+ static var previews: some View {
+ ChatItemForwardingView(
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello")],
+ fromChatInfo: .direct(contact: Contact.sampleData),
+ composeState: Binding.constant(ComposeState(message: "hello"))
+ ).environmentObject(CurrentColors.toAppTheme())
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItemInfoView.swift b/apps/ios/Shared/Views/Chat/ChatItemInfoView.swift
index 15effaeea6..54e0726554 100644
--- a/apps/ios/Shared/Views/Chat/ChatItemInfoView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItemInfoView.swift
@@ -164,6 +164,15 @@ struct ChatItemInfoView: View {
}
if let file = ci.file, let fileExpires = file.fileExpires {
infoRow(file.expired ? "File was available until" : "File available until", localTimestamp(fileExpires))
+ if noShownBadge() {
+ Button {
+ openBadgesView()
+ } label: {
+ Text("Support SimpleX to send larger files that stay available longer")
+ .multilineTextAlignment(.leading)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
}
if meta.msgVerified?.verified == true {
let signedText: LocalizedStringKey = ci.chatDir.sent ? "Signed" : "Signed & verified"
@@ -258,7 +267,7 @@ struct ChatItemInfoView: View {
private func itemVersionView(_ itemVersion: ChatItemVersion, _ maxWidth: CGFloat, current: Bool) -> some View {
let backgroundColor = chatItemFrameColor(ci, theme)
return VStack(alignment: .leading, spacing: 4) {
- textBubble(itemVersion.msgContent.text, itemVersion.formattedText, nil, backgroundColor: backgroundColor)
+ textBubble(itemVersion.msgContent.text, itemVersion.formattedText, itemVersion.markdownBlocks, nil, backgroundColor: backgroundColor)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(backgroundColor)
@@ -286,9 +295,12 @@ struct ChatItemInfoView: View {
.frame(maxWidth: maxWidth, alignment: .leading)
}
- @ViewBuilder private func textBubble(_ text: String, _ formattedText: [FormattedText]?, _ sender: String? = nil, backgroundColor: Color) -> some View {
+ @ViewBuilder private func textBubble(_ text: String, _ formattedText: [FormattedText]?, _ markdownBlocks: [MarkdownBlock]?, _ sender: String? = nil, backgroundColor: Color) -> some View {
if text != "" {
- TextBubble(text: text, formattedText: formattedText, sender: sender, mentions: ci.mentions, userMemberId: userMemberId, backgroundColor: backgroundColor)
+ TextBubble(
+ text: text, formattedText: formattedText, markdownBlocks: markdownBlocks, sender: sender, mentions: ci.mentions, userMemberId: userMemberId,
+ backgroundColor: backgroundColor, cardColor: ci.chatDir.sent ? theme.appColors.sentQuote : theme.appColors.receivedQuote
+ )
} else {
Text("no text")
.italic()
@@ -300,15 +312,19 @@ struct ChatItemInfoView: View {
@EnvironmentObject var theme: AppTheme
var text: String
var formattedText: [FormattedText]?
+ var markdownBlocks: [MarkdownBlock]?
var sender: String? = nil
var mentions: [String: CIMention]?
var userMemberId: String?
var backgroundColor: Color
+ var cardColor: Color
@State private var showSecrets: Set = []
var body: some View {
- let r = messageText(text, formattedText, sender: sender, mentions: mentions, userMemberId: userMemberId, showSecrets: showSecrets, backgroundColor: UIColor(backgroundColor))
- return msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
+ MarkdownView(
+ text: text, formattedText: formattedText, markdownBlocks: markdownBlocks, sender: sender, mentions: mentions, userMemberId: userMemberId,
+ backgroundColor: backgroundColor, cardColor: cardColor, showSecrets: $showSecrets
+ )
}
}
@@ -333,7 +349,7 @@ struct ChatItemInfoView: View {
private func quotedMsgView(_ qi: CIQuote, _ maxWidth: CGFloat) -> some View {
let backgroundColor = quotedMsgFrameColor(qi, theme)
return VStack(alignment: .leading, spacing: 4) {
- textBubble(qi.text, qi.formattedText, qi.getSender(nil), backgroundColor: backgroundColor)
+ textBubble(qi.text, qi.formattedText, qi.markdownBlocks, qi.getSender(nil), backgroundColor: backgroundColor)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(quotedMsgFrameColor(qi, theme))
@@ -602,6 +618,6 @@ func localTimestamp(_ date: Date) -> String {
struct ChatItemInfoView_Previews: PreviewProvider {
static var previews: some View {
- ChatItemInfoView(ci: ChatItem.getSample(1, .directSnd, .now, "hello"), userMemberId: Chat.sampleData.chatInfo.groupInfo?.membership.memberId, chatItemInfo: Binding.constant(nil))
+ ChatItemInfoView(ci: ChatItem.getSample(1, .directSnd, previewDate, "hello"), userMemberId: Chat.sampleData.chatInfo.groupInfo?.membership.memberId, chatItemInfo: Binding.constant(nil))
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatItemView.swift b/apps/ios/Shared/Views/Chat/ChatItemView.swift
index 1839651daa..9a17c23ab1 100644
--- a/apps/ios/Shared/Views/Chat/ChatItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItemView.swift
@@ -50,6 +50,7 @@ struct ChatItemView: View {
@Binding var scrollToItemId: ChatItem.ID?
var maxWidth: CGFloat = .infinity
@Binding var allowMenu: Bool
+ var endButton: AnyView?
init(
chat: Chat,
@@ -59,7 +60,8 @@ struct ChatItemView: View {
scrollToItemId: Binding = .constant(nil),
showMember: Bool = false,
maxWidth: CGFloat = .infinity,
- allowMenu: Binding = .constant(false)
+ allowMenu: Binding = .constant(false),
+ endButton: AnyView? = nil
) {
self.chat = chat
self.im = im
@@ -68,6 +70,7 @@ struct ChatItemView: View {
_scrollToItemId = scrollToItemId
self.maxWidth = maxWidth
_allowMenu = allowMenu
+ self.endButton = endButton
}
var body: some View {
@@ -116,7 +119,8 @@ struct ChatItemView: View {
maxWidth: maxWidth,
imgWidth: adjustedMaxWidth,
videoWidth: adjustedMaxWidth,
- allowMenu: $allowMenu
+ allowMenu: $allowMenu,
+ endButton: endButton
)
}
}
@@ -125,6 +129,7 @@ struct ChatItemContentView: View {
@EnvironmentObject var chatModel: ChatModel
@EnvironmentObject var theme: AppTheme
@Environment(\.revealed) var revealed: Bool
+ @Environment(\.terminalLayout) private var terminal
@ObservedObject var chat: Chat
@ObservedObject var im: ItemsModel
var chatItem: ChatItem
@@ -192,7 +197,9 @@ struct ChatItemContentView: View {
}
private func eventItemView() -> some View {
- CIEventView(eventText: eventItemViewText(theme.colors.secondary))
+ ChatEventWithMeta(chatItem: chatItem) { ts in
+ CIEventView(eventText: eventItemViewText(theme.colors.secondary, terminal ? ts : textSpace + ts))
+ }
}
private func pendingReviewEventItemText() -> Text {
@@ -202,17 +209,17 @@ struct ChatItemContentView: View {
.fontWeight(.bold)
}
- private func eventItemViewText(_ secondaryColor: Color) -> Text {
+ private func eventItemViewText(_ secondaryColor: Color, _ ts: Text) -> Text {
if !revealed, let t = mergedGroupEventText {
- return chatEventText(t + textSpace + chatItem.timestampText, secondaryColor)
+ return chatEventText(t + textSpace + ts, secondaryColor)
} else if let member = chatItem.memberDisplayName {
return Text(member + " ")
.font(.caption)
.foregroundColor(secondaryColor)
.fontWeight(.light)
- + chatEventText(chatItem, secondaryColor, isChannel: chat.chatInfo.isChannel)
+ + chatEventText(chatItem, secondaryColor, isChannel: chat.chatInfo.isChannel, ts: ts)
} else {
- return chatEventText(chatItem, secondaryColor, isChannel: chat.chatInfo.isChannel)
+ return chatEventText(chatItem, secondaryColor, isChannel: chat.chatInfo.isChannel, ts: ts)
}
}
@@ -282,23 +289,40 @@ func chatEventText(_ eventText: LocalizedStringKey, _ ts: Text, _ secondaryColor
chatEventText(Text(eventText) + textSpace + ts, secondaryColor)
}
-func chatEventText(_ ci: ChatItem, _ secondaryColor: Color, isChannel: Bool = false) -> Text {
- chatEventText("\(ci.content.text(isChannel: isChannel))", ci.timestampText, secondaryColor)
+func chatEventText(_ ci: ChatItem, _ secondaryColor: Color, isChannel: Bool = false, ts: Text) -> Text {
+ chatEventText("\(ci.content.text(isChannel: isChannel))", ts, secondaryColor)
+}
+
+func previewDated(_ chatItem: ChatItem) -> ChatItem {
+ var ci = chatItem
+ ci.meta.itemTs = previewDate
+ ci.meta.createdAt = previewDate
+ ci.meta.updatedAt = previewDate
+ return ci
}
struct ChatItemView_Previews: PreviewProvider {
static var previews: some View {
let im = ItemsModel.shared
Group{
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "hello there too"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "🙂"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "🙂🙂🙂🙂🙂"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(2, .directRcv, .now, "🙂🙂🙂🙂🙂🙂"), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getDeletedContentSample(), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: .now)), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "🙂", .sndSent(sndProgress: .complete), itemLive: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).environment(\.revealed, true)
- ChatItemView(chat: Chat.sampleData, im: im, chatItem: ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemLive: true), scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).environment(\.revealed, true)
+ let ci1 = ChatItem.getSample(1, .directSnd, previewDate, "hello")
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci1, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem.getSample(2, .directRcv, previewDate, "hello there too")
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci2, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = ChatItem.getSample(1, .directSnd, previewDate, "🙂")
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci3, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = ChatItem.getSample(2, .directRcv, previewDate, "🙂🙂🙂🙂🙂")
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci4, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = ChatItem.getSample(2, .directRcv, previewDate, "🙂🙂🙂🙂🙂🙂")
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci5, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci5, tailVisible: true))
+ let ci6 = ChatItem.getDeletedContentSample(1, previewDate)
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci6, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci6, tailVisible: true))
+ let ci7 = ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: previewDate))
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci7, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).modifier(ChatItemClipped(ci7, tailVisible: true))
+ let ci8 = ChatItem.getSample(1, .directSnd, previewDate, "🙂", .sndSent(sndProgress: .complete), itemLive: true)
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci8, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).environment(\.revealed, true).modifier(ChatItemClipped(ci8, tailVisible: true))
+ let ci9 = ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemLive: true)
+ ChatItemView(chat: Chat.sampleData, im: im, chatItem: ci9, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)).environment(\.revealed, true).modifier(ChatItemClipped(ci9, tailVisible: true))
}
.environment(\.revealed, false)
.previewLayout(.fixed(width: 360, height: 70))
@@ -311,70 +335,80 @@ struct ChatItemView_NonMsgContentDeleted_Previews: PreviewProvider {
let im = ItemsModel.shared
let ciFeatureContent = CIContent.rcvChatFeature(feature: .fullDelete, enabled: FeatureEnabled(forUser: false, forContact: false), param: nil)
Group{
- ChatItemView(
- chat: Chat.sampleData,
- im: im,
- chatItem: ChatItem(
- chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "1 skipped message", .rcvRead, itemDeleted: .deleted(deletedTs: .now)),
- content: .rcvIntegrityError(msgError: .msgSkipped(fromMsgId: 1, toMsgId: 2)),
- quotedItem: nil,
- file: nil
- ),
- scrollToItem: { _ in },
- scrollToItemId: Binding.constant(nil)
+ let ci1 = ChatItem(
+ chatDir: .directRcv,
+ meta: CIMeta.getSample(1, previewDate, "1 skipped message", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate)),
+ content: .rcvIntegrityError(msgError: .msgSkipped(fromMsgId: 1, toMsgId: 2)),
+ quotedItem: nil,
+ file: nil
)
ChatItemView(
chat: Chat.sampleData,
im: im,
- chatItem: ChatItem(
- chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "1 skipped message", .rcvRead),
- content: .rcvDecryptionError(msgDecryptError: .ratchetHeader, msgCount: 2),
- quotedItem: nil,
- file: nil
- ),
+ chatItem: ci1,
+ scrollToItem: { _ in },
+ scrollToItemId: Binding.constant(nil)
+ )
+ .modifier(ChatItemClipped(ci1, tailVisible: true))
+ let ci2 = ChatItem(
+ chatDir: .directRcv,
+ meta: CIMeta.getSample(1, previewDate, "1 skipped message", .rcvRead),
+ content: .rcvDecryptionError(msgDecryptError: .ratchetHeader, msgCount: 2),
+ quotedItem: nil,
+ file: nil
+ )
+ ChatItemView(
+ chat: Chat.sampleData,
+ im: im,
+ chatItem: ci2,
scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil)
)
- ChatItemView(
- chat: Chat.sampleData,
- im: im,
- chatItem: ChatItem(
- chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "received invitation to join group team as admin", .rcvRead, itemDeleted: .deleted(deletedTs: .now)),
- content: .rcvGroupInvitation(groupInvitation: CIGroupInvitation.getSample(status: .pending), memberRole: .admin),
- quotedItem: nil,
- file: nil
- ),
- scrollToItem: { _ in },
- scrollToItemId: Binding.constant(nil)
+ .modifier(ChatItemClipped(ci2, tailVisible: true))
+ let ci3 = ChatItem(
+ chatDir: .directRcv,
+ meta: CIMeta.getSample(1, previewDate, "received invitation to join group team as admin", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate)),
+ content: .rcvGroupInvitation(groupInvitation: CIGroupInvitation.getSample(status: .pending), memberRole: .admin),
+ quotedItem: nil,
+ file: nil
)
ChatItemView(
chat: Chat.sampleData,
im: im,
- chatItem: ChatItem(
- chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, "group event text", .rcvRead, itemDeleted: .deleted(deletedTs: .now)),
- content: .rcvGroupEvent(rcvGroupEvent: .memberAdded(groupMemberId: 1, profile: Profile.sampleData)),
- quotedItem: nil,
- file: nil
- ),
+ chatItem: ci3,
scrollToItem: { _ in },
scrollToItemId: Binding.constant(nil)
)
+ .modifier(ChatItemClipped(ci3, tailVisible: true))
+ let ci4 = ChatItem(
+ chatDir: .directRcv,
+ meta: CIMeta.getSample(1, previewDate, "group event text", .rcvRead, itemDeleted: .deleted(deletedTs: previewDate)),
+ content: .rcvGroupEvent(rcvGroupEvent: .memberAdded(groupMemberId: 1, profile: Profile.sampleData)),
+ quotedItem: nil,
+ file: nil
+ )
ChatItemView(
chat: Chat.sampleData,
im: im,
- chatItem: ChatItem(
- chatDir: .directRcv,
- meta: CIMeta.getSample(1, .now, ciFeatureContent.text, .rcvRead, itemDeleted: .deleted(deletedTs: .now)),
- content: ciFeatureContent,
- quotedItem: nil,
- file: nil
- ),
+ chatItem: ci4,
scrollToItem: { _ in },
scrollToItemId: Binding.constant(nil)
)
+ .modifier(ChatItemClipped(ci4, tailVisible: true))
+ let ci5 = ChatItem(
+ chatDir: .directRcv,
+ meta: CIMeta.getSample(1, previewDate, ciFeatureContent.text, .rcvRead, itemDeleted: .deleted(deletedTs: previewDate)),
+ content: ciFeatureContent,
+ quotedItem: nil,
+ file: nil
+ )
+ ChatItemView(
+ chat: Chat.sampleData,
+ im: im,
+ chatItem: ci5,
+ scrollToItem: { _ in },
+ scrollToItemId: Binding.constant(nil)
+ )
+ .modifier(ChatItemClipped(ci5, tailVisible: true))
}
.environment(\.revealed, true)
.previewLayout(.fixed(width: 360, height: 70))
diff --git a/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift b/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift
index 0b074c6370..02ea691887 100644
--- a/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift
+++ b/apps/ios/Shared/Views/Chat/ChatItemsMerger.swift
@@ -213,6 +213,13 @@ enum MergedItem: Identifiable, Hashable, Equatable {
}
}
+ var revealed: Bool {
+ switch self {
+ case .single: true
+ case let .grouped(_, revealed, _, _, _, _, _, _): revealed
+ }
+ }
+
func hasUnread() -> Bool {
switch self {
case let .single(item, _, _): item.item.isRcvNew
@@ -275,7 +282,7 @@ struct ListItem: Hashable {
// using meta.hashValue instead of parts takes much more time so better to use partial meta here
func genHash(_ prevRevealed: Bool, _ nextRevealed: Bool) -> String {
- "\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextRevealed)"
+ "\(item.meta.itemId) \(item.meta.updatedAt.hashValue) \(item.meta.itemEdited) \(item.meta.itemDeleted?.hashValue ?? 0) \(item.meta.itemTimed?.hashValue ?? 0) \(item.meta.itemStatus.hashValue) \(item.meta.sentViaProxy ?? false) \(item.mergeCategory?.hashValue ?? 0) \(chatDirHash(item.chatDir)) \(item.reactions.hashValue) \(item.meta.isRcvNew) \(item.text.hash) \(item.file?.hashValue ?? 0) \(item.quotedItem?.itemId ?? 0) \(unreadBefore) \(prevItem?.id ?? 0) \(chatDirHash(prevItem?.chatDir)) \(prevItem?.mergeCategory?.hashValue ?? 0) \(prevRevealed) \(nextItem?.id ?? 0) \(chatDirHash(nextItem?.chatDir)) \(nextItem?.mergeCategory?.hashValue ?? 0) \(nextItem?.reactions.isEmpty ?? true) \(nextItem?.isOneLine ?? false) \(nextRevealed)"
}
}
diff --git a/apps/ios/Shared/Views/Chat/ChatView.swift b/apps/ios/Shared/Views/Chat/ChatView.swift
index d18d8ae145..293282fb26 100644
--- a/apps/ios/Shared/Views/Chat/ChatView.swift
+++ b/apps/ios/Shared/Views/Chat/ChatView.swift
@@ -12,7 +12,11 @@ import SimpleXChat
import SwiftyGif
import Combine
-private let memberImageSize: CGFloat = 34
+private let memberImageBaseSize: CGFloat = 34
+
+func scaledMemberImageSize(_ font: DynamicTypeSize) -> CGFloat {
+ memberImageBaseSize * dynamicSize(font).profileImageSize / dynamicSize(.large).profileImageSize
+}
private func shouldShowAvatar(_ current: ChatItem, _ older: ChatItem?) -> Bool {
let oldIsGroupRcv = switch older?.chatDir {
@@ -45,6 +49,7 @@ struct ChatView: View {
@State var theme: AppTheme = buildTheme()
@Environment(\.dismiss) var dismiss
@Environment(\.colorScheme) var colorScheme
+ @Environment(\.dynamicTypeSize) private var userFont
@Environment(\.presentationMode) var presentationMode
@Environment(\.scenePhase) var scenePhase
@State @ObservedObject var chat: Chat
@@ -94,6 +99,10 @@ struct ChatView: View {
let userSupportScopeInfo: GroupChatScopeInfo = .memberSupport(groupMember_: nil)
+ private var terminal: Bool {
+ chat.chatInfo.activeChatLayout(profileChatLayout(ChatModel.shared.currentUser)) == .terminal
+ }
+
// Spec: spec/client/chat-view.md#body
var body: some View {
if #available(iOS 16.0, *) {
@@ -120,11 +129,12 @@ struct ChatView: View {
let backgroundColor = theme.wallpaper.background ?? wallpaperType.defaultBackgroundColor(theme.base, theme.colors.background)
let tintColor = theme.wallpaper.tint ?? wallpaperType.defaultTintColor(theme.base)
Color.clear.ignoresSafeArea(.all)
- .if(wallpaperImage != nil && im.secondaryIMFilter == nil) { view in
+ .if(!terminal && wallpaperImage != nil && im.secondaryIMFilter == nil) { view in
view.modifier(
ChatViewBackground(image: wallpaperImage!, imageType: wallpaperType, background: backgroundColor, tint: tintColor)
)
}
+ .if(terminal && im.secondaryIMFilter == nil) { $0.background(backgroundColor) }
VStack(spacing: 0) {
ZStack(alignment: .bottomTrailing) {
if userMemberKnockingChat {
@@ -367,7 +377,7 @@ struct ChatView: View {
theme = buildTheme()
closeSearch()
mergedItems.boxedValue = MergedItems.create(im, revealedItems)
- scrollView.updateItems(mergedItems.boxedValue.items)
+ scrollView.updateItems(mergedItems.boxedValue.items, true)
if let openAround = chatModel.openAroundItemId, let index = mergedItems.boxedValue.indexInParentItems[openAround] {
scrollView.scrollToItem(index)
@@ -907,7 +917,7 @@ struct ChatView: View {
return Group {
if case .chatBanner = ci.content {
VStack {
- ChatBannerView(chat: $chat)
+ ChatBannerView(chat: chat)
.padding(.bottom, 90)
.padding(.top, 8)
@@ -923,12 +933,13 @@ struct ChatView: View {
// left padding (see .leading padding below), so they get the full row width here
// too — otherwise the reserved avatar inset would leave a gap on the right
let channelReceivedNoAvatar = channelReceived && !shouldShowAvatar(mergedItem.newest().item, mergedItem.oldest().nextItem)
+ let avatarColumn = scaledMemberImageSize(userFont) + 8
let maxWidth = cInfo.chatType == .group
? channelReceivedNoAvatar
? g.size.width - 26
: voiceNoFrame || channelReceived
- ? (g.size.width - 28) - 42
- : (g.size.width - 28) * 0.84 - 42
+ ? (g.size.width - 28) - avatarColumn
+ : (g.size.width - 28) * 0.84 - avatarColumn
: voiceNoFrame
? (g.size.width - 32)
: (g.size.width - 32) * 0.84
@@ -941,6 +952,8 @@ struct ChatView: View {
scrollToItem: scrollToItem,
scrollToItemId: $scrollToItemId,
merged: mergedItem,
+ olderRow: mergedItems.boxedValue.items.indices.contains(index + 1) ? mergedItems.boxedValue.items[index + 1] : nil,
+ listWidth: g.size.width,
maxWidth: maxWidth,
composeState: $composeState,
selectedMember: $selectedMember,
@@ -957,6 +970,7 @@ struct ChatView: View {
// crashes on Cell size calculation without this line
.environmentObject(ChatModel.shared)
.environmentObject(theme) // crashes without this line when scrolling to the first unread in EndlessScrollVIew
+ .environment(\.terminalLayout, terminal)
.id(ci.id) // Required to trigger `onAppear` on iOS15
}
.onAppear {
@@ -985,6 +999,9 @@ struct ChatView: View {
mergedItems.boxedValue = MergedItems.create(im, revealed)
scrollView.updateItems(mergedItems.boxedValue.items)
}
+ .onChange(of: terminal) { _ in
+ scrollView.updateItems(mergedItems.boxedValue.items, true)
+ }
.onChange(of: chat.id) { _ in
allowLoadMoreItems = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
@@ -1004,7 +1021,7 @@ struct ChatView: View {
struct ChatBannerView: View {
@EnvironmentObject var theme: AppTheme
@AppStorage(DEFAULT_CHAT_ITEM_ROUNDNESS) private var roundness = defaultChatItemRoundness
- @Binding @ObservedObject var chat: Chat
+ @ObservedObject var chat: Chat
var body: some View {
let v = VStack(spacing: 8) {
@@ -1692,10 +1709,12 @@ struct ChatView: View {
}
// Spec: spec/client/chat-view.md#ChatItemWithMenu
- private struct ChatItemWithMenu: View {
+ struct ChatItemWithMenu: View {
@ObservedObject var im: ItemsModel
@EnvironmentObject var m: ChatModel
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
+ @Environment(\.dynamicTypeSize) private var userFont
@AppStorage(DEFAULT_PROFILE_IMAGE_CORNER_RADIUS) private var profileRadius = defaultProfileImageCorner
@Binding @ObservedObject var chat: Chat
@ObservedObject var dummyModel: ChatItemDummyModel = .shared
@@ -1705,6 +1724,8 @@ struct ChatView: View {
let scrollToItem: (ChatItem.ID) -> Void
@Binding var scrollToItemId: ChatItem.ID?
let merged: MergedItem
+ let olderRow: MergedItem?
+ let listWidth: CGFloat
let maxWidth: CGFloat
@Binding var composeState: ComposeState
@Binding var selectedMember: GMember?
@@ -1735,9 +1756,14 @@ struct ChatView: View {
@State private var markReadTask: Task? = nil
@State private var actionSheet: SomeActionSheet? = nil
@State private var swipeOffset: CGFloat = 0
+ @State private var swipeExclusionFrames: [CGRect] = []
var revealed: Bool { revealedItems.contains(chatItem.id) }
+ private var memberImageSize: CGFloat {
+ scaledMemberImageSize(userFont)
+ }
+
typealias ItemSeparation = (timestamp: Bool, largeGap: Bool, date: Date?)
private func reveal(_ yes: Bool) -> Void {
@@ -1774,7 +1800,7 @@ struct ChatView: View {
} else {
nil
}
- let showAvatar = shouldShowAvatar(item, merged.oldest().nextItem)
+ let showAvatar = terminal ? terminalItemShowsSender(item, merged.oldest().nextItem) : shouldShowAvatar(item, merged.oldest().nextItem)
let single = switch merged {
case .single: true
default: false
@@ -1925,7 +1951,9 @@ struct ChatView: View {
_ itemSeparation: ItemSeparation
) -> some View {
let bottomPadding: Double = itemSeparation.largeGap ? 10 : 2
- if case .channelRcv = ci.chatDir,
+ if terminal {
+ terminalItemRow(range, showAvatar, ci, itemSeparation)
+ } else if case .channelRcv = ci.chatDir,
case let .group(groupInfo, _) = chat.chatInfo {
if showAvatar {
VStack(alignment: .leading, spacing: 4) {
@@ -1959,7 +1987,7 @@ struct ChatView: View {
}
.font(.caption)
.foregroundStyle(.secondary)
- .padding(.leading, memberImageSize + 14 + (selectedChatItems != nil && ci.canBeDeletedForSelf ? 12 + 24 : 0))
+ .padding(.leading, memberImageSize + 10 + (selectedChatItems != nil && ci.canBeDeletedForSelf ? 12 + 24 : 0))
.padding(.top, 3)
}
HStack(alignment: .center, spacing: 0) {
@@ -1968,7 +1996,7 @@ struct ChatView: View {
.padding(.trailing, 12)
}
HStack(alignment: .top, spacing: 10) {
- ProfileImage(imageStr: groupInfo.image, iconName: groupInfo.chatIconName, size: memberImageSize, backgroundColor: theme.colors.background)
+ ProfileImage(imageStr: groupInfo.image, icon: Image(systemName: groupInfo.chatIconName), size: memberImageSize, backgroundColor: theme.colors.background)
.simultaneousGesture(TapGesture().onEnded {
showChatInfoSheet = true
})
@@ -2042,7 +2070,7 @@ struct ChatView: View {
}
.font(.caption)
.foregroundStyle(.secondary)
- .padding(.leading, memberImageSize + 14 + (selectedChatItems != nil && ci.canBeDeletedForSelf ? 12 + 24 : 0))
+ .padding(.leading, memberImageSize + 10 + (selectedChatItems != nil && ci.canBeDeletedForSelf ? 12 + 24 : 0))
.padding(.top, 3) // this is in addition to message sequence gap
}
HStack(alignment: .center, spacing: 0) {
@@ -2052,7 +2080,7 @@ struct ChatView: View {
}
HStack(alignment: .top, spacing: 10) {
if ci.meta.showGroupAsSender {
- ProfileImage(imageStr: groupInfo.image, iconName: groupInfo.chatIconName, size: memberImageSize, backgroundColor: theme.colors.background)
+ ProfileImage(imageStr: groupInfo.image, icon: Image(systemName: groupInfo.chatIconName), size: memberImageSize, backgroundColor: theme.colors.background)
.simultaneousGesture(TapGesture().onEnded {
showChatInfoSheet = true
})
@@ -2118,8 +2146,106 @@ struct ChatView: View {
}
}
+ private func terminalItemRow(_ range: ClosedRange?, _ showSender: Bool, _ ci: ChatItem, _ itemSeparation: ItemSeparation) -> some View {
+ let selecting = selectedChatItems != nil && ci.canBeDeletedForSelf
+ let leading: CGFloat = selecting ? 4 + 24 : 0
+ let gutter = chat.chatInfo.chatType == .group ? memberImageSize + chatItemTextPadding : 0
+ let older = merged.oldest().nextItem
+ let topGap = terminalRowGap(
+ ci,
+ older,
+ separated: terminalRowsSeparated(olderRow),
+ largeGap: older.map { getItemSeparation($0, merged.oldest().item).largeGap } ?? false,
+ hasSenderRow: showSender
+ )
+ return ZStack(alignment: .leading) {
+ if selecting {
+ SelectedChatItem(ciId: ci.id, selectedChatItems: $selectedChatItems)
+ .padding(.leading, 8)
+ }
+ TerminalChatItemRow(
+ sender: showSender ? chatItemSender(ci, range) : nil,
+ gutter: gutter,
+ topGap: topGap,
+ contentStartsWithCard: terminalItemStartsWithCard(ci, revealed: revealed)
+ ) {
+ chatItemWithMenu(ci, range, min(maxWidth, listWidth - leading - gutter - 2 * chatItemTextPadding), itemSeparation)
+ }
+ .padding(.leading, leading)
+ }
+ .padding(.bottom, index == 0 && itemSeparation.largeGap ? 8 : itemSeparation.date == nil ? 0 : terminalLevelStep)
+ .background(selectedChatItems?.contains(ci.id) == true ? theme.colors.primary.opacity(0.1) : Color.clear)
+ }
+
+ private func terminalRowsSeparated(_ olderRow: MergedItem?) -> Bool {
+ guard let olderRow else { return false }
+ let newest = olderRow.newest()
+ if case .chatBanner = newest.item.content { return true }
+ return getItemSeparation(newest.item, olderRow.revealed ? newest.prevItem : nil).date != nil
+ }
+
+ private func chatItemSender(_ ci: ChatItem, _ range: ClosedRange?) -> ChatItemSender {
+ let cInfo = chat.chatInfo
+ switch (ci.chatDir, cInfo) {
+ case let (_, .group(groupInfo, _)) where ci.channelIsSender:
+ return ChatItemSender(name: Text(groupInfo.chatViewName), role: NSLocalizedString("channel", comment: "shown as sender role for channel messages"), own: ci.chatDir.sent, image: groupSenderImage(groupInfo))
+ case (.directRcv, _):
+ return ChatItemSender(name: Text(cInfo.displayName), badge: cInfo.nameBadge, own: false)
+ case let (.groupRcv(member), .group(groupInfo, _)):
+ if ci.meta.showGroupAsSender {
+ return ChatItemSender(name: Text(groupInfo.chatViewName), role: NSLocalizedString("group", comment: "shown on group welcome message"), own: false, image: groupSenderImage(groupInfo))
+ }
+ let (prevMember, memCount): (GroupMember?, Int) = if let range { m.getPrevHiddenMember(member, range) } else { (nil, 1) }
+ return ChatItemSender(
+ name: Text(memberNames(member, prevMember, memCount)),
+ badge: prevMember == nil && memCount == 1 ? member.nameBadge : nil,
+ role: memCount == 1 ? senderRole(member, groupInfo) : nil,
+ own: false,
+ image: AnyView(
+ MemberProfileImage(member, size: memberImageSize, backgroundColor: theme.colors.background)
+ .simultaneousGesture(TapGesture().onEnded {
+ if let mem = m.getGroupMember(member.groupMemberId) {
+ selectedMember = mem
+ } else {
+ let mem = GMember.init(member)
+ m.groupMembers.append(mem)
+ m.groupMembersIndexes[member.groupMemberId] = m.groupMembers.count - 1
+ selectedMember = mem
+ }
+ })
+ )
+ )
+ case let (.groupSnd, .group(groupInfo, _)):
+ let membership = groupInfo.membership
+ return ChatItemSender(
+ name: Text(membership.displayName),
+ badge: membership.nameBadge,
+ role: senderRole(membership, groupInfo),
+ own: true,
+ image: AnyView(MemberProfileImage(membership, size: memberImageSize, backgroundColor: theme.colors.background))
+ )
+ default:
+ return cInfo.incognito
+ ? ChatItemSender(name: Text("Incognito"), own: true)
+ : ChatItemSender(name: Text(m.currentUser?.displayName ?? ""), badge: m.currentUser?.profile.localBadge, own: true)
+ }
+ }
+
+ private func groupSenderImage(_ groupInfo: GroupInfo) -> AnyView {
+ AnyView(
+ ProfileImage(imageStr: groupInfo.image, icon: Image(systemName: groupInfo.chatIconName), size: memberImageSize, backgroundColor: theme.colors.background)
+ .simultaneousGesture(TapGesture().onEnded { showChatInfoSheet = true })
+ )
+ }
+
+ private func senderRole(_ member: GroupMember, _ groupInfo: GroupInfo) -> String? {
+ member.memberRole > .member ? member.memberRole.text(isChannel: groupInfo.isChannel) : nil
+ }
+
func chatItemWithMenu(_ ci: ChatItem, _ range: ClosedRange?, _ maxWidth: CGFloat, _ itemSeparation: ItemSeparation) -> some View {
- let alignment: Alignment = ci.chatDir.sent ? .trailing : .leading
+ let alignEnd = ci.chatDir.sent && !terminal
+ let alignment: Alignment = alignEnd ? .trailing : .leading
+ let markedDeleted = ci.meta.itemDeleted != nil && (!revealed || ci.isDeletedContent)
let live = composeState.liveMessage != nil
let canReply = ci.meta.itemDeleted == nil && !ci.isLiveDummy && !live && !ci.localNote && selectedChatItems == nil && chat.chatInfo.sendMsgEnabled
return ZStack(alignment: .trailing) {
@@ -2128,9 +2254,9 @@ struct ChatView: View {
.foregroundColor(.secondary)
.opacity(min(1, -swipeOffset / 30))
.offset(x: swipeOffset + 40)
- VStack(alignment: alignment.horizontal, spacing: 3) {
+ VStack(alignment: alignment.horizontal, spacing: terminal ? 0 : 3) {
HStack {
- if ci.chatDir.sent {
+ if alignEnd {
goToItemButton(true)
}
ChatItemView(
@@ -2140,28 +2266,32 @@ struct ChatView: View {
scrollToItem: scrollToItem,
scrollToItemId: $scrollToItemId,
maxWidth: maxWidth,
- allowMenu: $allowMenu
+ allowMenu: $allowMenu,
+ endButton: terminal && !searchIsNotBlank && ci.meta.itemForwarded?.chatTypeApiIdMsgId != nil ? AnyView(goToItemButton(false)) : nil
)
.environment(\.revealed, revealed)
.environment(\.showTimestamp, itemSeparation.timestamp)
- .modifier(ChatItemClipped(ci, tailVisible: itemSeparation.largeGap && (ci.meta.itemDeleted == nil || revealed)))
+ .if(!terminal) { $0.modifier(ChatItemClipped(ci, tailVisible: itemSeparation.largeGap && (ci.meta.itemDeleted == nil || revealed))) }
.contextMenu { menu(ci, range, live: live) }
.accessibilityLabel("")
- if !ci.chatDir.sent {
+ if !alignEnd && (!terminal || searchIsNotBlank || markedDeleted) {
goToItemButton(false)
}
}
if ci.content.msgContent != nil && (ci.meta.itemDeleted == nil || revealed) && ci.reactions.count > 0 {
chatItemReactions(ci)
- .padding(.bottom, 4)
+ .padding(.leading, terminal ? chatItemTextPadding - 6 : 0)
+ .padding(.bottom, terminal ? 0 : 4)
}
}
+ .coordinateSpace(name: swipeExclusionSpace)
+ .onPreferenceChange(SwipeExclusionFrames.self) { swipeExclusionFrames = $0 }
.offset(x: swipeOffset)
.contentShape(Rectangle())
.simultaneousGesture(
- DragGesture(minimumDistance: 10)
+ DragGesture(minimumDistance: 10, coordinateSpace: .named(swipeExclusionSpace))
.onChanged { value in
- guard canReply else { return }
+ guard canReply, !swipeExclusionFrames.contains(where: { $0.contains(value.startLocation) }) else { return }
let x = value.translation.width
if x < 0 {
swipeOffset = max(x * 0.63, -56)
@@ -2227,7 +2357,7 @@ struct ChatView: View {
}
}
}
- .frame(maxWidth: maxWidth, maxHeight: .infinity, alignment: alignment)
+ .frame(maxWidth: terminal ? .infinity : maxWidth, maxHeight: .infinity, alignment: alignment)
.frame(minWidth: 0, maxWidth: .infinity, alignment: alignment)
.sheet(isPresented: $showChatItemInfoSheet, onDismiss: {
chatItemInfo = nil
@@ -3326,15 +3456,15 @@ struct ChatView_Previews: PreviewProvider {
chatModel.chatId = "@1"
let im = ItemsModel.shared
im.reversedChatItems = [
- ChatItem.getSample(1, .directSnd, .now, "hello"),
- ChatItem.getSample(2, .directRcv, .now, "hi"),
- ChatItem.getSample(3, .directRcv, .now, "hi there"),
- ChatItem.getDeletedContentSample(4),
- ChatItem.getSample(5, .directRcv, .now, "hello again"),
- ChatItem.getSample(6, .directSnd, .now, "hi there!!!"),
- ChatItem.getSample(7, .directSnd, .now, "how are you?"),
- ChatItem.getSample(8, .directSnd, .now, "👍👍👍👍"),
- ChatItem.getSample(9, .directSnd, .now, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
+ ChatItem.getSample(1, .directSnd, previewDate, "hello"),
+ ChatItem.getSample(2, .directRcv, previewDate, "hi"),
+ ChatItem.getSample(3, .directRcv, previewDate, "hi there"),
+ ChatItem.getDeletedContentSample(4, previewDate),
+ ChatItem.getSample(5, .directRcv, previewDate, "hello again"),
+ ChatItem.getSample(6, .directSnd, previewDate, "hi there!!!"),
+ ChatItem.getSample(7, .directSnd, previewDate, "how are you?"),
+ ChatItem.getSample(8, .directSnd, previewDate, "👍👍👍👍"),
+ ChatItem.getSample(9, .directSnd, previewDate, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
]
@State var showChatInfo = false
return ChatView(
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeChatLinkView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeChatLinkView.swift
index 650ea8a87f..78f29c3b60 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeChatLinkView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeChatLinkView.swift
@@ -11,7 +11,7 @@ struct ComposeChatLinkView: View {
HStack(alignment: .center, spacing: 8) {
ProfileImage(
imageStr: chatLink.image,
- iconName: chatLink.iconName,
+ icon: Image(systemName: chatLink.iconName),
size: 44
)
.padding(.leading, 12)
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift
index caa4e2a501..f1c0bee3c1 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeView.swift
@@ -299,17 +299,40 @@ func chatItemPreview(chatItem: ChatItem) -> ComposePreview {
// Spec: spec/client/compose.md#UploadContent
enum UploadContent: Equatable {
case simpleImage(image: UIImage)
+ case imageFile(image: UIImage, url: URL)
case animatedImage(image: UIImage)
case video(image: UIImage, url: URL, duration: Int)
var uiImage: UIImage {
switch self {
case let .simpleImage(image): return image
+ case let .imageFile(image, _): return image
case let .animatedImage(image): return image
case let .video(image, _, _): return image
}
}
+ func imagePreview() async -> String? {
+ if case let .imageFile(_, url) = self, let preview = resizeImageFileToStrSize(url, maxDataSize: 14000) {
+ return preview
+ }
+ return await resizeImageToStrSize(uiImage, maxDataSize: 14000)
+ }
+
+ static func loadImageFileFromURL(url: URL) -> UploadContent? {
+ let content = loadFromURL(url: url)
+ guard case let .simpleImage(image)? = content else { return content }
+ let tempUrl = URL(fileURLWithPath: generateNewFileName(getTempFilesDirectory().path + "/" + "image", url.pathExtension, fullPath: true))
+ do {
+ try FileManager.default.copyItem(at: url, to: tempUrl)
+ } catch let err {
+ logger.error("UploadContent copyItem error: \(err.localizedDescription)")
+ return content
+ }
+ _ = ChatModel.shared.filesToDelete.insert(tempUrl)
+ return .imageFile(image: image, url: tempUrl)
+ }
+
static func loadFromURL(url: URL) -> UploadContent? {
do {
let data = try Data(contentsOf: url)
@@ -338,6 +361,18 @@ enum UploadContent: Equatable {
}
}
+// A badge only helps below the largest badge's limit, and not in incognito chats, so outside that
+// the alert is informational as before.
+func showLargeFileAlert(_ fileSize: Int64, incognito: Bool, senderProfile: LocalProfile?) {
+ let title = NSLocalizedString("Large file!", comment: "file alert title")
+ let message = largeFileMessage(fileSize, incognito: incognito, badgeIssue: expiredBadgeReason(fileSize, senderProfile))
+ if !incognito && fileSize <= MAX_FILE_SIZE_XFTP_LEGEND && noShownBadge() {
+ showAlert(title, message: message) { [supportSimpleXAlertAction, okAlertAction] }
+ } else {
+ showAlert(title, message: message)
+ }
+}
+
// Spec: spec/client/compose.md#ComposeView
struct ComposeView: View {
@EnvironmentObject var chatModel: ChatModel
@@ -637,7 +672,7 @@ struct ComposeView: View {
Task {
var media: [(String, UploadContent)] = []
for content in selected {
- if let img = await resizeImageToStrSize(content.uiImage, maxDataSize: 14000) {
+ if let img = await content.imagePreview() {
media.append((img, content))
await MainActor.run {
composeState = composeState.copy(preview: .mediaPreviews(mediaPreviews: media))
@@ -668,10 +703,7 @@ struct ComposeView: View {
fileSize <= maxFileSize {
composeState = composeState.copy(preview: .filePreview(fileName: fileURL.lastPathComponent, file: fileURL))
} else {
- showAlert(
- NSLocalizedString("Large file!", comment: "file alert title"),
- message: largeFileMessage(Int64(fileSize ?? 0), incognito: sendIncognito, badgeIssue: expiredBadgeReason(Int64(fileSize ?? 0), sendProfile))
- )
+ showLargeFileAlert(Int64(fileSize ?? 0), incognito: sendIncognito, senderProfile: sendProfile)
}
} catch {
logger.error("ComposeView fileImporter error \(error.localizedDescription)")
@@ -758,6 +790,7 @@ struct ComposeView: View {
let connectedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connStatus == .ready && $0.wrapped.activeConn?.connFailedErr == nil }.count
let failedCount = relayMembers.filter { !relayMemberRemoved($0.wrapped.memberStatus) && $0.wrapped.activeConn?.connFailedErr != nil }.count
let total = relayMembers.count > 0 ? relayMembers.count : hostnames.count
+ guard total > 0 || chatModel.membersLoaded else { return nil }
let noActiveRelays = connectedCount == 0 && (removedCount + failedCount) == total
return (hostnames, relayMembers, connectedCount, removedCount, failedCount, total, noActiveRelays)
}
@@ -1242,7 +1275,7 @@ struct ComposeView: View {
// Spec: spec/client/compose.md#addMediaContent
private func addMediaContent(_ content: UploadContent) async {
- if let img = await resizeImageToStrSize(content.uiImage, maxDataSize: 14000) {
+ if let img = await content.imagePreview() {
var newMedia: [(String, UploadContent?)] = []
if case var .mediaPreviews(media) = composeState.preview {
media.append((img, content))
@@ -1562,6 +1595,8 @@ struct ComposeView: View {
return switch uploadContent {
case let .simpleImage(image):
(saveImage(image), .image(text: text, image: previewImage))
+ case let .imageFile(image, url):
+ (imageCryptoFile(url, image), .image(text: text, image: previewImage))
case let .animatedImage(image):
(saveAnimImage(image), .image(text: text, image: previewImage))
case let .video(_, url, duration):
@@ -1571,6 +1606,13 @@ struct ComposeView: View {
}
}
+ func imageCryptoFile(_ url: URL, _ image: UIImage) -> CryptoFile? {
+ let file = saveImageFile(url) ?? saveImage(image)
+ removeFile(url)
+ ChatModel.shared.filesToDelete.remove(url)
+ return file
+ }
+
func updateMessage(_ ei: ChatItem, live: Bool) async -> ChatItem? {
if let oldMsgContent = ei.content.msgContent {
do {
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeVoiceView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeVoiceView.swift
index 441a68fccb..48e72e2c05 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeVoiceView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ComposeVoiceView.swift
@@ -15,12 +15,16 @@ enum VoiceMessagePlaybackState {
case paused
}
+func wholeSeconds(_ time: TimeInterval) -> Int {
+ Int(exactly: time.rounded(.towardZero)) ?? 0
+}
+
func voiceMessageTime(_ time: TimeInterval) -> String {
- durationText(Int(time))
+ durationText(wholeSeconds(time))
}
func voiceMessageTime_(_ time: TimeInterval?) -> String {
- durationText(Int(time ?? 0))
+ durationText(wholeSeconds(time ?? 0))
}
struct ComposeVoiceView: View {
@@ -157,7 +161,7 @@ struct ComposeVoiceView: View {
var seek: (TimeInterval) -> Void
var body: some View {
- Slider(value: Binding(get: { progress ?? TimeInterval(0) }, set: { seek($0) }), in: 0 ... length)
+ Slider(value: Binding(get: { progress ?? TimeInterval(0) }, set: { seek($0) }), in: 0 ... max(length, 0))
.frame(maxWidth: .infinity)
.frame(height: 4)
.tint(theme.colors.primary)
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextContactRequestActionsView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextContactRequestActionsView.swift
index 82c89cd43d..8637321ad2 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextContactRequestActionsView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextContactRequestActionsView.swift
@@ -90,8 +90,10 @@ struct ContextContactRequestActionsView: View {
}
}
-#Preview {
- ContextContactRequestActionsView(
- contactRequestId: 1
- )
+struct ContextContactRequestActionsView_Previews: PreviewProvider {
+ static var previews: some View {
+ ContextContactRequestActionsView(
+ contactRequestId: 1
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextItemView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextItemView.swift
index 1f328b2061..f7f8d2982e 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextItemView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextItemView.swift
@@ -71,7 +71,7 @@ struct ContextItemView: View {
}
private func contextMsgPreview(_ contextItem: ChatItem) -> some View {
- let r = messageText(contextItem.text, contextItem.formattedText, sender: nil, preview: true, mentions: contextItem.mentions, userMemberId: nil, showSecrets: nil, backgroundColor: UIColor(background), stripLink: contextItem.content.msgContent?.chatLinkStr)
+ let r = messageText(contextItem.text, contextItem.formattedText, markdownBlocks: contextItem.markdownBlocks, sender: nil, preview: true, mentions: contextItem.mentions, userMemberId: nil, showSecrets: nil, backgroundColor: UIColor(background), stripLink: contextItem.content.msgContent?.chatLinkStr)
let t = attachment() + Text(AttributedString(r.string))
return t.if(r.hasSecrets, transform: hiddenSecretsView)
@@ -98,7 +98,7 @@ struct ContextItemView: View {
struct ContextItemView_Previews: PreviewProvider {
static var previews: some View {
- let contextItem: ChatItem = ChatItem.getSample(1, .directSnd, .now, "hello")
+ let contextItem: ChatItem = ChatItem.getSample(1, .directSnd, previewDate, "hello")
return ContextItemView(chat: Chat.sampleData, contextItems: [contextItem], contextIcon: "pencil.circle", cancelContextItem: {}, contextIconForeground: Color.red)
}
}
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextMemberContactActionsView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextMemberContactActionsView.swift
index 9a73b2b5d4..c9fa58471d 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextMemberContactActionsView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextMemberContactActionsView.swift
@@ -102,9 +102,11 @@ func acceptMemberContactRequest(_ contact: Contact, inProgress: Binding? =
}
}
-#Preview {
- ContextMemberContactActionsView(
- contact: Contact.sampleData,
- groupDirectInv: GroupDirectInvitation.sampleData
- )
+struct ContextMemberContactActionsView_Previews: PreviewProvider {
+ static var previews: some View {
+ ContextMemberContactActionsView(
+ contact: Contact.sampleData,
+ groupDirectInv: GroupDirectInvitation.sampleData
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextPendingMemberActionsView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextPendingMemberActionsView.swift
index e9913053ea..8bbbb71d6e 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextPendingMemberActionsView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextPendingMemberActionsView.swift
@@ -98,9 +98,11 @@ func acceptMember(_ groupInfo: GroupInfo, _ member: GroupMember, _ role: GroupMe
}
}
-#Preview {
- ContextPendingMemberActionsView(
- groupInfo: GroupInfo.sampleData,
- member: GroupMember.sampleData
- )
+struct ContextPendingMemberActionsView_Previews: PreviewProvider {
+ static var previews: some View {
+ ContextPendingMemberActionsView(
+ groupInfo: GroupInfo.sampleData,
+ member: GroupMember.sampleData
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextProfilePickerView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextProfilePickerView.swift
index 9047eaf84b..4803b57719 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/ContextProfilePickerView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/ContextProfilePickerView.swift
@@ -300,9 +300,11 @@ struct ContextProfilePickerView: View {
}
}
-#Preview {
- ContextProfilePickerView(
- chat: Chat.sampleData,
- selectedUser: User.sampleData
- )
+struct ContextProfilePickerView_Previews: PreviewProvider {
+ static var previews: some View {
+ ContextProfilePickerView(
+ chat: Chat.sampleData,
+ selectedUser: User.sampleData
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/NativeTextEditor.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/NativeTextEditor.swift
index 225e83c014..dbded8e39b 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/NativeTextEditor.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/NativeTextEditor.swift
@@ -284,7 +284,7 @@ struct NativeTextEditor_Previews: PreviewProvider{
disableEditing: Binding.constant(false),
height: Binding.constant(100),
focused: Binding.constant(false),
- lastUnfocusedDate: Binding.constant(.now),
+ lastUnfocusedDate: Binding.constant(previewDate),
placeholder: Binding.constant("Placeholder"),
selectedRange: Binding.constant(NSRange(location: 0, length: 0)),
onImagesAdded: { _ in }
diff --git a/apps/ios/Shared/Views/Chat/ComposeMessage/SendMessageView.swift b/apps/ios/Shared/Views/Chat/ComposeMessage/SendMessageView.swift
index 1d75f38715..2cfa6b2b0a 100644
--- a/apps/ios/Shared/Views/Chat/ComposeMessage/SendMessageView.swift
+++ b/apps/ios/Shared/Views/Chat/ComposeMessage/SendMessageView.swift
@@ -446,7 +446,7 @@ struct SendMessageView_Previews: PreviewProvider {
static var previews: some View {
@State var composeStateNew = ComposeState()
@State var selectedRange = NSRange()
- let ci = ChatItem.getSample(1, .directSnd, .now, "hello")
+ let ci = ChatItem.getSample(1, .directSnd, previewDate, "hello")
@State var composeStateEditing = ComposeState(editingItem: ci)
@State var selectedRangeEditing = NSRange()
@State var sendEnabled: Bool = true
@@ -461,7 +461,7 @@ struct SendMessageView_Previews: PreviewProvider {
sendMessage: { _ in },
onMediaAdded: { _ in },
keyboardVisible: Binding.constant(true),
- keyboardHiddenDate: Binding.constant(Date.now)
+ keyboardHiddenDate: Binding.constant(previewDate)
)
}
VStack {
@@ -473,7 +473,7 @@ struct SendMessageView_Previews: PreviewProvider {
sendMessage: { _ in },
onMediaAdded: { _ in },
keyboardVisible: Binding.constant(true),
- keyboardHiddenDate: Binding.constant(Date.now)
+ keyboardHiddenDate: Binding.constant(previewDate)
)
}
}
diff --git a/apps/ios/Shared/Views/Chat/EndlessScrollView.swift b/apps/ios/Shared/Views/Chat/EndlessScrollView.swift
index cc61754b26..5ab9bef0f7 100644
--- a/apps/ios/Shared/Views/Chat/EndlessScrollView.swift
+++ b/apps/ios/Shared/Views/Chat/EndlessScrollView.swift
@@ -55,7 +55,7 @@ struct ScrollRepresentable: UIViewControllerRepresent
}
cell.isHidden = false
cell.backgroundColor = .clear
- let size = cell.systemLayoutSizeFitting(CGSizeMake(scrollView.bounds.width, CGFloat.greatestFiniteMagnitude))
+ let size = cell.systemLayoutSizeFitting(CGSizeMake(scrollView.bounds.width, CGFloat.greatestFiniteMagnitude), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
cell.frame.size.width = scrollView.bounds.width
cell.frame.size.height = size.height
return cell
@@ -74,7 +74,7 @@ struct ScrollRepresentable: UIViewControllerRepresent
fatalError("Unexpected Cell Type for: \(item)")
}
}
- let size = cell.systemLayoutSizeFitting(CGSizeMake(scrollView.bounds.width, CGFloat.greatestFiniteMagnitude))
+ let size = cell.systemLayoutSizeFitting(CGSizeMake(scrollView.bounds.width, CGFloat.greatestFiniteMagnitude), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel)
cell.frame.size.width = scrollView.bounds.width
cell.frame.size.height = size.height
cell.setNeedsLayout()
diff --git a/apps/ios/Shared/Views/Chat/Group/ChannelMembersView.swift b/apps/ios/Shared/Views/Chat/Group/ChannelMembersView.swift
index 6b7f5b65fc..f7cadc6d6f 100644
--- a/apps/ios/Shared/Views/Chat/Group/ChannelMembersView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/ChannelMembersView.swift
@@ -26,7 +26,7 @@ struct ChannelMembersView: View {
.sorted { $0.wrapped.memberRole > $1.wrapped.memberRole }
let subscriberCount = groupInfo.groupSummary.publicMemberCount ?? Int64(members.count + 1)
let s = searchText.trimmingCharacters(in: .whitespaces).localizedLowercase
- if groupInfo.isOwner {
+ if groupInfo.canModerate {
List {
Section(header: Text(subscriberCountStr(subscriberCount)).foregroundColor(theme.colors.secondary)) {
searchFieldView(text: $searchText, focussed: $searchFocussed, theme.colors.onBackground, theme.colors.secondary)
@@ -104,9 +104,11 @@ struct ChannelMembersView: View {
}
}
-#Preview {
- ChannelMembersView(
- chat: Chat.sampleData,
- groupInfo: GroupInfo.sampleData
- )
+struct ChannelMembersView_Previews: PreviewProvider {
+ static var previews: some View {
+ ChannelMembersView(
+ chat: Chat.sampleData,
+ groupInfo: GroupInfo.sampleData
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/Group/ChannelRelaysView.swift b/apps/ios/Shared/Views/Chat/Group/ChannelRelaysView.swift
index aa94f5b346..b22b2261d6 100644
--- a/apps/ios/Shared/Views/Chat/Group/ChannelRelaysView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/ChannelRelaysView.swift
@@ -170,6 +170,8 @@ func hostFromRelayLink(_ link: String) -> String {
return link
}
-#Preview {
- ChannelRelaysView(chat: Chat.sampleData, groupInfo: GroupInfo.sampleData)
+struct ChannelRelaysView_Previews: PreviewProvider {
+ static var previews: some View {
+ ChannelRelaysView(chat: Chat.sampleData, groupInfo: GroupInfo.sampleData)
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift b/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift
index 1be8070259..36300dc399 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupChatInfoView.swift
@@ -125,7 +125,7 @@ struct GroupChatInfoView: View {
Label("Share via chat", systemImage: "arrowshape.turn.up.forward")
}
}
- if groupInfo.isOwner || members.contains(where: { $0.wrapped.memberRole >= .owner }) {
+ if groupInfo.canModerate || members.contains(where: { $0.wrapped.memberRole >= .owner }) {
channelMembersButton()
}
if groupInfo.membership.memberRole >= .moderator {
@@ -154,8 +154,6 @@ struct GroupChatInfoView: View {
if showUserSupportChat {
UserSupportChatNavLink(chat: chat, groupInfo: groupInfo, scrollToItemId: $scrollToItemId)
}
- } header: {
- Text("")
}
}
@@ -314,14 +312,14 @@ struct GroupChatInfoView: View {
}
private func groupInfoHeader() -> some View {
- VStack {
+ VStack(spacing: 8) {
let cInfo = chat.chatInfo
// show actual display name, alias can be edited in this view
let displayName = (cInfo.groupInfo?.groupProfile.displayName ?? cInfo.displayName).trimmingCharacters(in: .whitespacesAndNewlines)
let fullName = cInfo.fullName.trimmingCharacters(in: .whitespacesAndNewlines)
ChatInfoImage(chat: chat, size: 192, color: Color(uiColor: .tertiarySystemFill))
- .padding(.top, 12)
- .padding()
+ .padding(.top, 20)
+ .padding(.bottom, 12)
Text(displayName)
.font(.largeTitle)
.multilineTextAlignment(.center)
@@ -734,7 +732,7 @@ struct GroupChatInfoView: View {
}
private func channelMembersButton() -> some View {
- let label: LocalizedStringKey = groupInfo.isOwner ? "Subscribers" : "Owners & contributors"
+ let label: LocalizedStringKey = groupInfo.canModerate ? "Subscribers" : "Owners & contributors"
return NavigationLink {
ChannelMembersView(chat: chat, groupInfo: groupInfo)
.navigationTitle(label)
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift b/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift
index 8a9bcaf059..a52c905307 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupLinkView.swift
@@ -241,9 +241,9 @@ struct GroupLinkView_Previews: PreviewProvider {
static var previews: some View {
@State var groupLink: GroupLink? = GroupLink(
userContactLinkId: 1,
- connLinkContact: CreatedConnLink(connFullLink: "https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2FPQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo%3D%40smp6.simplex.im%2FK1rslx-m5bpXVIdMZg9NLUZ_8JBm8xTt%23MCowBQYDK2VuAyEALDeVe-sG8mRY22LsXlPgiwTNs9dbiLrNuA7f3ZMAJ2w%3D", connShortLink: nil),
- shortLinkDataSet: false,
- shortLinkLargeDataSet: false,
+ connLinkContact: CreatedConnLink(connFullLink: "https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2FPQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo%3D%40smp6.simplex.im%2FK1rslx-m5bpXVIdMZg9NLUZ_8JBm8xTt%23MCowBQYDK2VuAyEALDeVe-sG8mRY22LsXlPgiwTNs9dbiLrNuA7f3ZMAJ2w%3D", connShortLink: "https://smp6.simplex.im/g#cL3iklYlt_Tws1B_1aGylbT_3HowPMQhuCFoBiCjZ1M"),
+ shortLinkDataSet: true,
+ shortLinkLargeDataSet: true,
groupLinkId: "abc",
acceptMemberRole: .member
)
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift b/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift
index ebbdc6b6a3..53a1ca180b 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupMemberInfoView.swift
@@ -38,6 +38,8 @@ struct GroupMemberInfoView: View {
switch groupMember.wrapped.memberRole {
case .relay: "Relay"
case .owner: "Owner"
+ case .moderator: "Moderator"
+ case .member: "Contributor"
default: "Subscriber"
}
} else {
@@ -513,10 +515,10 @@ struct GroupMemberInfoView: View {
}
private func groupMemberInfoHeader(_ mem: GroupMember) -> some View {
- VStack {
+ VStack(spacing: 8) {
MemberProfileImage(mem, size: 192, color: Color(uiColor: .tertiarySystemFill))
- .padding(.top, 12)
- .padding()
+ .padding(.top, 20)
+ .padding(.bottom, 12)
// show alias if set, alias cannot be edited in this view
let displayName = mem.displayName.trimmingCharacters(in: .whitespacesAndNewlines)
let fullName = mem.fullName.trimmingCharacters(in: .whitespacesAndNewlines)
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupPreferencesView.swift b/apps/ios/Shared/Views/Chat/Group/GroupPreferencesView.swift
index da15ab98a5..b4ba98e97f 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupPreferencesView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupPreferencesView.swift
@@ -50,8 +50,21 @@ struct GroupPreferencesView: View {
featureSection(.history, $preferences.history.enable)
featureSection(.support, $preferences.support.enable, disabled: true)
} else {
- // hidden until message signing is user-facing (recipient-only stage)
-// featureSection(.signMessages, $preferences.signMessages.enable)
+ featureSection(.signMessages, $preferences.signMessages.enable)
+ .onChange(of: preferences.signMessages.enable) { enable in
+ if enable == .on && currentPreferences.signMessages.enable != .on {
+ showAlert(
+ NSLocalizedString("Sign messages?", comment: "alert title"),
+ message: NSLocalizedString("New subscribers will see earlier messages as unsigned.", comment: "alert message"),
+ actions: {[
+ UIAlertAction(title: NSLocalizedString("Enable", comment: "alert button"), style: .default) { _ in },
+ UIAlertAction(title: NSLocalizedString("Cancel", comment: "alert button"), style: .cancel) { _ in
+ preferences.signMessages.enable = .off
+ }
+ ]}
+ )
+ }
+ }
featureSection(.timedMessages, $preferences.timedMessages.enable)
featureSection(.fullDelete, $preferences.fullDelete.enable)
featureSection(.reactions, $preferences.reactions.enable)
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupProfileView.swift b/apps/ios/Shared/Views/Chat/Group/GroupProfileView.swift
index 126fcc57b3..19478753af 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupProfileView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupProfileView.swift
@@ -37,7 +37,7 @@ struct GroupProfileView: View {
var body: some View {
List {
- EditProfileImage(profileImage: $groupProfile.image, iconName: groupInfo.chatIconName, showChooseSource: $showChooseSource)
+ EditProfileImage(profileImage: $groupProfile.image, icon: Image(systemName: groupInfo.chatIconName), showChooseSource: $showChooseSource)
.if(!focusDisplayName) { $0.padding(.top) }
Section {
diff --git a/apps/ios/Shared/Views/Chat/Group/GroupWelcomeView.swift b/apps/ios/Shared/Views/Chat/Group/GroupWelcomeView.swift
index f58f2c213d..1bef869a66 100644
--- a/apps/ios/Shared/Views/Chat/Group/GroupWelcomeView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/GroupWelcomeView.swift
@@ -59,8 +59,11 @@ struct GroupWelcomeView: View {
}
private func textPreview() -> some View {
- let r = markdownText(welcomeText, showSecrets: showSecrets, backgroundColor: theme.colors.background)
- return msgTextResultView(r, Text(AttributedString(r.string)), showSecrets: $showSecrets)
+ let parsed = parseSimpleXMarkdownText(welcomeText)
+ return MarkdownView(
+ text: welcomeText, formattedText: parsed?.formattedText, markdownBlocks: parsed?.markdownBlocks,
+ backgroundColor: theme.colors.background, cardColor: theme.appColors.receivedQuote, showSecrets: $showSecrets
+ )
.frame(minHeight: 130, alignment: .topLeading)
.frame(maxWidth: .infinity, alignment: .leading)
}
diff --git a/apps/ios/Shared/Views/Chat/Group/MemberAdmissionView.swift b/apps/ios/Shared/Views/Chat/Group/MemberAdmissionView.swift
index d80615b5d2..7213363471 100644
--- a/apps/ios/Shared/Views/Chat/Group/MemberAdmissionView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/MemberAdmissionView.swift
@@ -82,12 +82,14 @@ struct MemberAdmissionView: View {
}
}
-#Preview {
- MemberAdmissionView(
- groupInfo: Binding.constant(GroupInfo.sampleData),
- admission: Binding.constant(GroupMemberAdmission.sampleData),
- currentAdmission: GroupMemberAdmission.sampleData,
- creatingGroup: false,
- saveAdmission: {}
- )
+struct MemberAdmissionView_Previews: PreviewProvider {
+ static var previews: some View {
+ MemberAdmissionView(
+ groupInfo: Binding.constant(GroupInfo.sampleData),
+ admission: Binding.constant(GroupMemberAdmission.sampleData),
+ currentAdmission: GroupMemberAdmission.sampleData,
+ creatingGroup: false,
+ saveAdmission: {}
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/Group/MemberSupportChatToolbar.swift b/apps/ios/Shared/Views/Chat/Group/MemberSupportChatToolbar.swift
index 74cb702d21..63bc83eb1d 100644
--- a/apps/ios/Shared/Views/Chat/Group/MemberSupportChatToolbar.swift
+++ b/apps/ios/Shared/Views/Chat/Group/MemberSupportChatToolbar.swift
@@ -36,9 +36,11 @@ struct MemberSupportChatToolbar: View {
}
}
-#Preview {
- MemberSupportChatToolbar(
- groupMember: GroupMember.sampleData
- )
- .environmentObject(CurrentColors.toAppTheme())
+struct MemberSupportChatToolbar_Previews: PreviewProvider {
+ static var previews: some View {
+ MemberSupportChatToolbar(
+ groupMember: GroupMember.sampleData
+ )
+ .environmentObject(CurrentColors.toAppTheme())
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/Group/MemberSupportView.swift b/apps/ios/Shared/Views/Chat/Group/MemberSupportView.swift
index da9d56a699..721f9b08a3 100644
--- a/apps/ios/Shared/Views/Chat/Group/MemberSupportView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/MemberSupportView.swift
@@ -291,9 +291,11 @@ func deleteMemberSupportChat(_ groupInfo: GroupInfo, _ member: GroupMember) {
}
}
-#Preview {
- MemberSupportView(
- groupInfo: GroupInfo.sampleData,
- scrollToItemId: Binding.constant(nil)
- )
+struct MemberSupportView_Previews: PreviewProvider {
+ static var previews: some View {
+ MemberSupportView(
+ groupInfo: GroupInfo.sampleData,
+ scrollToItemId: Binding.constant(nil)
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/Chat/Group/SecondaryChatView.swift b/apps/ios/Shared/Views/Chat/Group/SecondaryChatView.swift
index e2092f7a24..7fade11db0 100644
--- a/apps/ios/Shared/Views/Chat/Group/SecondaryChatView.swift
+++ b/apps/ios/Shared/Views/Chat/Group/SecondaryChatView.swift
@@ -32,13 +32,18 @@ struct SecondaryChatView: View {
}
}
-#Preview {
- SecondaryChatView(
- chat: Chat(
- chatInfo: .group(groupInfo: GroupInfo.sampleData, groupChatScope: .memberSupport(groupMember_: GroupMember.sampleData)),
- chatItems: [],
- chatStats: ChatStats()
- ),
- scrollToItemId: Binding.constant(nil)
- )
+struct SecondaryChatView_Previews: PreviewProvider {
+ static var previews: some View {
+ let chatModel = ChatModel()
+ chatModel.secondaryIM = ItemsModel(secondaryIMFilter: .groupChatScopeContext(groupScopeInfo: .memberSupport(groupMember_: GroupMember.sampleData)))
+ return SecondaryChatView(
+ chat: Chat(
+ chatInfo: .group(groupInfo: GroupInfo.sampleData, groupChatScope: .memberSupport(groupMember_: GroupMember.sampleData)),
+ chatItems: [],
+ chatStats: ChatStats()
+ ),
+ scrollToItemId: Binding.constant(nil)
+ )
+ .environmentObject(chatModel)
+ }
}
diff --git a/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift b/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift
index 0ed78401b0..fb46fd83ed 100644
--- a/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift
+++ b/apps/ios/Shared/Views/ChatList/ChatListNavLink.swift
@@ -781,17 +781,19 @@ func showErrorAlert(_ error: Error, _ title: String) {
struct ChatListNavLink_Previews: PreviewProvider {
static var previews: some View {
@State var chatId: String? = "@1"
+ var contactRequest = UserContactRequest.sampleData
+ contactRequest.updatedAt = previewDate
return Group {
ChatListNavLink(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello")]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello")]
), parentSheet: .constant(nil))
ChatListNavLink(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello")]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello")]
), parentSheet: .constant(nil))
ChatListNavLink(chat: Chat(
- chatInfo: ChatInfo.sampleData.contactRequest,
+ chatInfo: .contactRequest(contactRequest: contactRequest),
chatItems: []
), parentSheet: .constant(nil))
}
diff --git a/apps/ios/Shared/Views/ChatList/ChatListView.swift b/apps/ios/Shared/Views/ChatList/ChatListView.swift
index b05e0696e3..b6c8fad9f6 100644
--- a/apps/ios/Shared/Views/ChatList/ChatListView.swift
+++ b/apps/ios/Shared/Views/ChatList/ChatListView.swift
@@ -154,9 +154,11 @@ struct UserPickerSheetView: View {
struct ChatListView: View {
@EnvironmentObject var chatModel: ChatModel
@StateObject private var connectProgressManager = ConnectProgressManager.shared
+ @ObservedObject private var badgeModel = BadgeModel.shared
@EnvironmentObject var theme: AppTheme
@Binding var activeUserPickerSheet: UserPickerSheet?
@State private var showNewChatSheet = false
+ @State private var showGetStakeSheet = false
@State private var searchMode = false
@FocusState private var searchFocussed
@State private var searchText = ""
@@ -174,7 +176,12 @@ struct ChatListView: View {
@AppStorage(GROUP_DEFAULT_ONE_HAND_UI, store: groupDefaults) private var oneHandUI = true
@AppStorage(DEFAULT_ONE_HAND_UI_CARD_SHOWN) private var oneHandUICardShown = false
@AppStorage(DEFAULT_ADDRESS_CREATION_CARD_SHOWN) private var addressCreationCardShown = false
+ @AppStorage(DEFAULT_SUPPORTER_BANNER_SHOWN) private var supporterBannerShown = false
+ @AppStorage(DEFAULT_SUPPORTER_BANNER_TAPPED) private var supporterBannerTapped = false
+ @AppStorage(DEFAULT_GET_STAKE_BANNER_TAPPED) private var getStakeBannerTapped = false
+ @AppStorage(DEFAULT_GET_STAKE_BANNER_DISMISSED) private var getStakeBannerDismissed = false
@AppStorage(DEFAULT_TOOLBAR_MATERIAL) private var toolbarMaterial = ToolbarMaterial.defaultMaterial
+ @State private var showBadgesSheet = false
// Spec: spec/client/chat-list.md#body
var body: some View {
@@ -211,6 +218,15 @@ struct ChatListView: View {
NewChatSheet()
.environment(\EnvironmentValues.refresh as! WritableKeyPath, nil)
}
+ .appSheet(isPresented: $showBadgesSheet) {
+ NavigationView {
+ BadgesView(showsAsSheet: true)
+ .modifier(ThemedBackground())
+ }
+ }
+ .appSheet(isPresented: $showGetStakeSheet) {
+ GetStakeView(fromSettings: false, showFirstImage: true)
+ }
.onChange(of: activeUserPickerSheet) {
if $0 != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
@@ -363,8 +379,63 @@ struct ChatListView: View {
}
}
+ // the onboarding cards replace the whole chat list, and the badge alert banner lives in the
+ // list - a supporter is not a newcomer, and must be told even with no conversations yet
private var shouldShowOnboarding: Bool {
- !addressCreationCardShown && !chatModel.chats.isEmpty && !hasConversations
+ !addressCreationCardShown && !chatModel.chats.isEmpty && !hasConversations && bannerBadgeAlert == nil
+ }
+
+ // the current profile's badge alert, if it is a kind the chat list has a banner for
+ private var bannerBadgeAlert: BadgeAlert? {
+ guard let alert = badgeModel.alert, badgeModel.userId == chatModel.currentUser?.userId else { return nil }
+ switch alert.kind {
+ case .supportEnded, .issueFailed, .subscriptionEnded, .paymentIssue, .subscriptionCancelled, .renewalApproaching: return alert
+ case .prepaidEnding, .unknown: return nil
+ }
+ }
+
+ private var renewalPrice: String? {
+ guard let badgeState = badgeModel.badgeState, let subscription = badgeState.subscription else { return nil }
+ return BadgeStore.shared.subscriptionPrice(badgeState.badgeType, planMonths: subscription.planMonths)
+ }
+
+ private var renewalFailure: LocalizedStringKey {
+ guard let issueError = badgeModel.badgeState?.issueError else { return "Your badge could not be renewed." }
+ return "\(issueError.reason.text)"
+ }
+
+ private func badgeAlertBanner(_ title: LocalizedStringKey, _ subtitle: LocalizedStringKey, warning: Bool = false, dismissTitle: String) -> some View {
+ SupportSimpleXBanner(
+ title: title,
+ subtitle: subtitle,
+ warning: warning,
+ onTap: { showBadgesSheet = true },
+ onDismiss: { showBadgeAlertDismissAlert(dismissTitle) }
+ )
+ }
+
+ private func showBadgeAlertDismissAlert(_ title: String) {
+ showAlert(title) {
+ [
+ UIAlertAction(title: NSLocalizedString("Remind me later", comment: "alert button"), style: .default) { _ in
+ Task { await ackBadgeAlert(snooze: true) }
+ },
+ UIAlertAction(title: NSLocalizedString("Dismiss", comment: "alert button"), style: .default) { _ in
+ Task { await ackBadgeAlert(snooze: false) }
+ },
+ cancelAlertAction
+ ]
+ }
+ }
+
+ private func showSupportSimpleXDismissAlert() {
+ showAlert(
+ title: NSLocalizedString("Support SimpleX", comment: "alert title"),
+ message: NSLocalizedString("You can support SimpleX later in Settings.", comment: "alert message"),
+ buttonTitle: NSLocalizedString("Ok", comment: "alert button"),
+ buttonAction: { withAnimation { supporterBannerShown = true } },
+ cancelButton: false
+ )
}
private var hasConversations: Bool {
@@ -382,14 +453,27 @@ struct ChatListView: View {
@ViewBuilder private var chatList: some View {
if shouldShowOnboarding {
- ConnectOnboardingView()
- .scaleEffect(x: 1, y: oneHandUI ? -1 : 1, anchor: .center)
- .modifier(ThemedBackground())
+ VStack(spacing: 0) {
+ ConnectOnboardingView()
+ if chatModel.bannerSlotFree(for: .getStake) && isInUS && !getStakeBannerDismissed {
+ GetStakeBanner(showDismiss: false, onTap: openGetStake, onDismiss: {})
+ .padding(.horizontal, 20)
+ .padding(.bottom, 8)
+ .onAppear { chatModel.chatListBanner = .getStake }
+ }
+ }
+ .scaleEffect(x: 1, y: oneHandUI ? -1 : 1, anchor: .center)
+ .modifier(ThemedBackground())
} else {
chatListContent
}
}
+ private func openGetStake() {
+ getStakeBannerTapped = true
+ showGetStakeSheet = true
+ }
+
private var chatListContent: some View {
let cs = filteredChats()
return ZStack {
@@ -418,6 +502,66 @@ struct ChatListView: View {
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
+ // one slot: an alert about a badge the user paid for outranks the pitch to get one
+ if let alert = bannerBadgeAlert {
+ Group {
+ switch alert.kind {
+ case .supportEnded:
+ badgeAlertBanner("Your badge expired", "Your badge expired on \(alert.dateText).", dismissTitle: NSLocalizedString("Your badge expired", comment: "alert title"))
+ case .issueFailed:
+ badgeAlertBanner("Badge renewal failed", renewalFailure, warning: true, dismissTitle: NSLocalizedString("Badge renewal failed", comment: "alert title"))
+ case .subscriptionEnded:
+ badgeAlertBanner("Your subscription ended", "Your badge subscription ended on \(alert.dateText).", dismissTitle: NSLocalizedString("Your subscription ended", comment: "alert title"))
+ case .paymentIssue:
+ badgeAlertBanner("Badge payment problem", "The store could not charge your payment method.", warning: true, dismissTitle: NSLocalizedString("Badge payment problem", comment: "alert title"))
+ case .subscriptionCancelled:
+ badgeAlertBanner("Subscription cancelled", "Your badge stays until \(alert.dateText).", dismissTitle: NSLocalizedString("Subscription cancelled", comment: "alert title"))
+ case .renewalApproaching:
+ if let price = renewalPrice {
+ badgeAlertBanner("Your badge renews soon", "Renews on \(alert.dateText) for \(price).", dismissTitle: NSLocalizedString("Your badge renews soon", comment: "alert title"))
+ } else {
+ badgeAlertBanner("Your badge renews soon", "Renews on \(alert.dateText).", dismissTitle: NSLocalizedString("Your badge renews soon", comment: "alert title"))
+ }
+ case .prepaidEnding, .unknown:
+ EmptyView()
+ }
+ }
+ .padding(.vertical, 3)
+ .scaleEffect(x: 1, y: oneHandUI ? -1 : 1, anchor: .center)
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .zIndex(1)
+ .onAppear { chatModel.chatListBanner = .badgeAlert }
+ // noShownBadge is false until the badge state loads: the pitch must not lock the slot and then
+ // be hidden by a supporter's badge arriving a moment later, leaving the slot empty for the session
+ } else if chatModel.bannerSlotFree(for: .badgePitch) && !supporterBannerShown && noShownBadge() && chatModel.chats.count > 3 {
+ SupportSimpleXBanner(
+ showDismiss: supporterBannerTapped,
+ onTap: {
+ supporterBannerTapped = true
+ showBadgesSheet = true
+ },
+ onDismiss: showSupportSimpleXDismissAlert
+ )
+ .padding(.vertical, 3)
+ .scaleEffect(x: 1, y: oneHandUI ? -1 : 1, anchor: .center)
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .zIndex(1)
+ .onAppear { chatModel.chatListBanner = .badgePitch }
+ } else if chatModel.bannerSlotFree(for: .getStake) && isInUS && !getStakeBannerDismissed {
+ GetStakeBanner(
+ showDismiss: getStakeBannerTapped && !chatModel.chats.isEmpty,
+ onTap: openGetStake,
+ onDismiss: { withAnimation { getStakeBannerDismissed = true } }
+ )
+ .padding(.vertical, 3)
+ .scaleEffect(x: 1, y: oneHandUI ? -1 : 1, anchor: .center)
+ .listRowSeparator(.hidden)
+ .listRowBackground(Color.clear)
+ .zIndex(1)
+ .onAppear { chatModel.chatListBanner = .getStake }
+ }
if #available(iOS 16.0, *) {
ForEach(cs, id: \.viewId) { chat in
ChatListNavLink(chat: chat, parentSheet: $sheet)
@@ -518,7 +662,7 @@ struct ChatListView: View {
VoiceItemState.smallView.values.forEach { $0.audioPlayer?.stop() }
VoiceItemState.smallView = [:]
}
-
+
// Spec: spec/client/chat-list.md#filteredChats
private func filteredChats() -> [Chat] {
if !searchChatFilteredBySimplexLink.isEmpty {
@@ -1138,17 +1282,19 @@ struct ChatListView_Previews: PreviewProvider {
static var previews: some View {
let chatModel = ChatModel()
+ var contactRequest = UserContactRequest.sampleData
+ contactRequest.updatedAt = previewDate
chatModel.updateChats([
ChatData(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello")]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello")]
),
ChatData(
chatInfo: ChatInfo.sampleData.group,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")]
),
ChatData(
- chatInfo: ChatInfo.sampleData.contactRequest,
+ chatInfo: .contactRequest(contactRequest: contactRequest),
chatItems: []
)
diff --git a/apps/ios/Shared/Views/ChatList/ChatPreviewView.swift b/apps/ios/Shared/Views/ChatList/ChatPreviewView.swift
index 5ee991a466..70cacf5bc3 100644
--- a/apps/ios/Shared/Views/ChatList/ChatPreviewView.swift
+++ b/apps/ios/Shared/Views/ChatList/ChatPreviewView.swift
@@ -299,7 +299,7 @@ struct ChatPreviewView: View {
func chatItemPreview(_ cItem: ChatItem) -> (Text, Bool) {
let (itemText, itemFormattedText) = chatItemPreviewText(cItem)
- let r = messageText(itemText, itemFormattedText, sender: cItem.meta.showGroupAsSender ? nil : cItem.memberDisplayName, preview: true, mentions: cItem.mentions, userMemberId: chat.chatInfo.groupInfo?.membership.memberId, showSecrets: nil, backgroundColor: UIColor(theme.colors.background), prefix: prefix())
+ let r = messageText(itemText, itemFormattedText, markdownBlocks: itemFormattedText == nil ? nil : cItem.markdownBlocks, sender: cItem.meta.showGroupAsSender ? nil : cItem.memberDisplayName, preview: true, mentions: cItem.mentions, userMemberId: chat.chatInfo.groupInfo?.membership.memberId, showSecrets: nil, backgroundColor: UIColor(theme.colors.background), prefix: prefix())
return (Text(AttributedString(r.string)), r.hasSecrets)
func chatItemPreviewText(_ ci: ChatItem) -> (String, [FormattedText]?) {
@@ -444,7 +444,7 @@ struct ChatPreviewView: View {
smallContentPreview(size: dynamicMediaSize, borderColor: chatLink.image != nil ? .secondary : .clear) {
ProfileImage(
imageStr: chatLink.image,
- iconName: chatLink.iconName,
+ icon: Image(systemName: chatLink.iconName),
size: dynamicMediaSize,
color: Color(uiColor: .tertiaryLabel)
)
@@ -573,25 +573,25 @@ struct ChatPreviewView_Previews: PreviewProvider {
), progressByTimeout: Binding.constant(false))
ChatPreviewView(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete))]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete))]
), progressByTimeout: Binding.constant(false))
ChatPreviewView(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete))],
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete))],
chatStats: ChatStats(unreadCount: 11, minUnreadItemId: 0)
), progressByTimeout: Binding.constant(false))
ChatPreviewView(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: .now))]
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete), itemDeleted: .deleted(deletedTs: previewDate))]
), progressByTimeout: Binding.constant(false))
ChatPreviewView(chat: Chat(
chatInfo: ChatInfo.sampleData.direct,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "hello", .sndSent(sndProgress: .complete))],
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "hello", .sndSent(sndProgress: .complete))],
chatStats: ChatStats(unreadCount: 3, minUnreadItemId: 0)
), progressByTimeout: Binding.constant(false))
ChatPreviewView(chat: Chat(
chatInfo: ChatInfo.sampleData.group,
- chatItems: [ChatItem.getSample(1, .directSnd, .now, "Lorem ipsum dolor sit amet, d. consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")],
+ chatItems: [ChatItem.getSample(1, .directSnd, previewDate, "Lorem ipsum dolor sit amet, d. consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")],
chatStats: ChatStats(unreadCount: 11, minUnreadItemId: 0)
), progressByTimeout: Binding.constant(false))
}
diff --git a/apps/ios/Shared/Views/ChatList/ContactConnectionView.swift b/apps/ios/Shared/Views/ChatList/ContactConnectionView.swift
index f5156d86b8..06ccde1361 100644
--- a/apps/ios/Shared/Views/ChatList/ContactConnectionView.swift
+++ b/apps/ios/Shared/Views/ChatList/ContactConnectionView.swift
@@ -76,7 +76,9 @@ struct ContactConnectionView: View {
struct ContactConnectionView_Previews: PreviewProvider {
static var previews: some View {
- ContactConnectionView(chat: Chat(chatInfo: ChatInfo.sampleData.contactConnection))
+ var contactConnection = PendingContactConnection.getSampleData()
+ contactConnection.updatedAt = previewDate
+ return ContactConnectionView(chat: Chat(chatInfo: .contactConnection(contactConnection: contactConnection)))
.previewLayout(.fixed(width: 360, height: 80))
}
}
diff --git a/apps/ios/Shared/Views/ChatList/ContactRequestView.swift b/apps/ios/Shared/Views/ChatList/ContactRequestView.swift
index 341bc10655..5a27271b16 100644
--- a/apps/ios/Shared/Views/ChatList/ContactRequestView.swift
+++ b/apps/ios/Shared/Views/ChatList/ContactRequestView.swift
@@ -55,7 +55,9 @@ struct ContactRequestView: View {
struct ContactRequestView_Previews: PreviewProvider {
static var previews: some View {
- ContactRequestView(contactRequest: UserContactRequest.sampleData, chat: Chat(chatInfo: ChatInfo.sampleData.contactRequest , chatItems: []))
+ var contactRequest = UserContactRequest.sampleData
+ contactRequest.updatedAt = previewDate
+ return ContactRequestView(contactRequest: contactRequest, chat: Chat(chatInfo: ChatInfo.sampleData.contactRequest , chatItems: []))
.previewLayout(.fixed(width: 360, height: 80))
}
}
diff --git a/apps/ios/Shared/Views/ChatList/GetStakeBanner.swift b/apps/ios/Shared/Views/ChatList/GetStakeBanner.swift
new file mode 100644
index 0000000000..99e8c90cc9
--- /dev/null
+++ b/apps/ios/Shared/Views/ChatList/GetStakeBanner.swift
@@ -0,0 +1,113 @@
+//
+// GetStakeBanner.swift
+// SimpleX (iOS)
+//
+// Created by spaced4ndy on 21.09.2026.
+// Copyright © 2026 SimpleX Chat. All rights reserved.
+//
+
+import SwiftUI
+import SimpleXChat
+
+// Spec: spec/client/chat-list.md#GetStakeBanner
+struct GetStakeBanner: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+ var showDismiss: Bool
+ let onTap: () -> Void
+ let onDismiss: () -> Void
+
+ var body: some View {
+ ZStack(alignment: .topTrailing) {
+ Button(action: onTap) {
+ HStack(spacing: 0) {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Invest in SimpleX Chat!")
+ .font(.headline)
+ .foregroundColor(theme.colors.primary)
+ .lineLimit(2)
+ Text("Crowdfunding on Wefunder")
+ .font(.subheadline)
+ .foregroundColor(theme.colors.onBackground)
+ .lineLimit(2)
+ }
+ Spacer(minLength: 6)
+ Image(colorScheme == .light ? "decentralized" : "decentralized-light")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 37, height: 37)
+ .padding(.trailing, showDismiss ? 32 : 10)
+ }
+ .modifier(BannerCard())
+ }
+ .buttonStyle(.plain)
+
+ if showDismiss {
+ BannerDismissButton(onDismiss: onDismiss)
+ }
+ }
+ }
+}
+
+struct BannerCard: ViewModifier {
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+
+ // grows with Dynamic Type but never shrinks below the default, so small-font users see the same card
+ @ScaledMetric(relativeTo: .body) private var scaledCardHeight: CGFloat = 72
+ private var cardHeight: CGFloat { max(72, scaledCardHeight) }
+
+ func body(content: Content) -> some View {
+ content
+ // the leading padding matches OneHandUICard's segment icon, so the text aligns with it in the list
+ .padding(.leading, 16)
+ .padding(.trailing, 8)
+ .padding(.vertical, 12)
+ .frame(minHeight: cardHeight)
+ .background(gradientBackground())
+ .clipShape(RoundedRectangle(cornerRadius: 16))
+ }
+
+ private func gradientBackground() -> some View {
+ // Asymmetric scale: start (dark end) pushed further below the card than the end (warm) is
+ // above, so the card's middle lands at the bright/mid-transition stop instead of the dark
+ // navy region. Keeps the small warm accent at top-right.
+ GeometryReader { geo in
+ let aspect = max(geo.size.height, 1) / max(geo.size.width, 1)
+ let startScale: CGFloat = colorScheme == .light ? 2.5 : 3.0
+ let endScale: CGFloat = colorScheme == .light ? 1.7 : 2.1
+ let gp = OnboardingCardView.gradientPoints(aspectRatio: aspect, scale: 1.0)
+ let start = UnitPoint(x: 0.5 + (gp.start.x - 0.5) * startScale, y: 0.5 + (gp.start.y - 0.5) * startScale)
+ let end = UnitPoint(x: 0.5 + (gp.end.x - 0.5) * endScale, y: 0.5 + (gp.end.y - 0.5) * endScale)
+ return LinearGradient(
+ stops: colorScheme == .light ? OnboardingCardView.lightStops : OnboardingCardView.darkStops,
+ startPoint: start,
+ endPoint: end
+ )
+ }
+ }
+}
+
+struct BannerDismissButton: View {
+ @EnvironmentObject var theme: AppTheme
+ @Environment(\.colorScheme) var colorScheme: ColorScheme
+ let onDismiss: () -> Void
+
+ var body: some View {
+ Image(systemName: "multiply")
+ .foregroundColor(colorScheme == .dark ? theme.colors.onBackground : theme.colors.secondary)
+ .frame(width: 12, height: 12)
+ .padding(.top, 12)
+ .padding(.bottom, 4)
+ .padding(.trailing, 16)
+ .padding(.leading, 4)
+ .contentShape(Rectangle())
+ .onTapGesture(perform: onDismiss)
+ }
+}
+
+struct GetStakeBanner_Previews: PreviewProvider {
+ static var previews: some View {
+ GetStakeBanner(showDismiss: true, onTap: {}, onDismiss: {})
+ .padding()
+ }
+}
diff --git a/apps/ios/Shared/Views/ChatList/OneHandUICard.swift b/apps/ios/Shared/Views/ChatList/OneHandUICard.swift
index 132a19d7e7..4e1b367c96 100644
--- a/apps/ios/Shared/Views/ChatList/OneHandUICard.swift
+++ b/apps/ios/Shared/Views/ChatList/OneHandUICard.swift
@@ -81,6 +81,8 @@ struct OneHandUICard: View {
}
}
-#Preview {
- OneHandUICard()
+struct OneHandUICard_Previews: PreviewProvider {
+ static var previews: some View {
+ OneHandUICard()
+ }
}
diff --git a/apps/ios/Shared/Views/ChatList/ServersSummaryView.swift b/apps/ios/Shared/Views/ChatList/ServersSummaryView.swift
index ee7605dbd2..6842a33cb0 100644
--- a/apps/ios/Shared/Views/ChatList/ServersSummaryView.swift
+++ b/apps/ios/Shared/Views/ChatList/ServersSummaryView.swift
@@ -737,6 +737,8 @@ struct DetailedXFTPStatsView: View {
}
}
-#Preview {
- ServersSummaryView()
+struct ServersSummaryView_Previews: PreviewProvider {
+ static var previews: some View {
+ ServersSummaryView()
+ }
}
diff --git a/apps/ios/Shared/Views/ChatList/UserPicker.swift b/apps/ios/Shared/Views/ChatList/UserPicker.swift
index 8c230dc56a..a25ebf3419 100644
--- a/apps/ios/Shared/Views/ChatList/UserPicker.swift
+++ b/apps/ios/Shared/Views/ChatList/UserPicker.swift
@@ -42,7 +42,8 @@ struct UserPicker: View {
HStack {
ProfileImage(imageStr: user.image, size: imageSize, color: Color(uiColor: .tertiarySystemGroupedBackground))
.padding(.trailing, 6)
- profileName(user).lineLimit(1)
+ NameWithBadge(profileName(user), user.profile.localBadge, .title2)
+ .lineLimit(1)
}
.padding(rowPadding)
.frame(width: otherUsers.isEmpty ? sectionWidth : currentUserWidth, alignment: .leading)
diff --git a/apps/ios/Shared/Views/Database/DatabaseEncryptionView.swift b/apps/ios/Shared/Views/Database/DatabaseEncryptionView.swift
index dbc25e536f..a52fdfd189 100644
--- a/apps/ios/Shared/Views/Database/DatabaseEncryptionView.swift
+++ b/apps/ios/Shared/Views/Database/DatabaseEncryptionView.swift
@@ -153,6 +153,9 @@ struct DatabaseEncryptionView: View {
try apiSaveAppSettings(settings: AppSettings.current.prepareForExport())
}
try await apiStorageEncryption(currentKey: currentKey, newKey: newKey)
+ if currentKey != newKey {
+ shouldDeleteDatabaseBackupsDefault.set(true)
+ }
encryptionStartedDefault.set(false)
initialRandomDBPassphraseGroupDefault.set(false)
if migration {
diff --git a/apps/ios/Shared/Views/Database/DatabaseErrorView.swift b/apps/ios/Shared/Views/Database/DatabaseErrorView.swift
index f7f253a617..4c4df931cb 100644
--- a/apps/ios/Shared/Views/Database/DatabaseErrorView.swift
+++ b/apps/ios/Shared/Views/Database/DatabaseErrorView.swift
@@ -118,6 +118,9 @@ struct DatabaseErrorView: View {
case .errorKeychain:
titleText("Keychain error")
errorView(Text("Cannot access keychain to save database password"))
+ case .errorKeyGeneration:
+ titleText("Database error")
+ errorView(Text("Cannot generate random database passphrase"))
case .invalidConfirmation:
// this can only happen if incorrect parameter is passed
titleText("Invalid migration confirmation")
@@ -217,6 +220,8 @@ struct DatabaseErrorView: View {
)
case .errorKeychain:
am.showAlertMsg(title: "Keychain error")
+ case .errorKeyGeneration:
+ am.showAlertMsg(title: "Database error", message: "Cannot generate random database passphrase")
case let .errorSQL(_, error):
am.showAlert(Alert(
title: Text("Database error"),
diff --git a/apps/ios/Shared/Views/Database/DatabaseView.swift b/apps/ios/Shared/Views/Database/DatabaseView.swift
index 051ed9f037..047a87cf71 100644
--- a/apps/ios/Shared/Views/Database/DatabaseView.swift
+++ b/apps/ios/Shared/Views/Database/DatabaseView.swift
@@ -453,6 +453,10 @@ struct DatabaseView: View {
ChatReceiver.shared.start()
chatLastStartGroupDefault.set(Date.now)
AppChatState.shared.set(.active)
+ if shouldDeleteDatabaseBackupsDefault.get() {
+ deleteDatabaseBackups()
+ shouldDeleteDatabaseBackupsDefault.set(false)
+ }
} catch let error {
runChat.wrappedValue = false
showAlert(NSLocalizedString("Error starting chat", comment: ""), message: responseError(error))
diff --git a/apps/ios/Shared/Views/Helpers/AppSheet.swift b/apps/ios/Shared/Views/Helpers/AppSheet.swift
index 17fe95a058..d505cdead7 100644
--- a/apps/ios/Shared/Views/Helpers/AppSheet.swift
+++ b/apps/ios/Shared/Views/Helpers/AppSheet.swift
@@ -29,6 +29,22 @@ private struct PrivacySensitive: ViewModifier {
}
}
+// Presented from the top view controller instead of a .sheet on a parent view, so an alert button or
+// a view that is itself in a sheet can open it.
+@discardableResult
+func showAppSheet(@ViewBuilder content: () -> Content) -> UIViewController? {
+ if let topController = getTopViewController() {
+ let v = content()
+ .modifier(PrivacySensitive())
+ .environmentObject(ChatModel.shared)
+ .environmentObject(AppTheme.shared)
+ let sheet = UIHostingController(rootView: v)
+ topController.present(sheet, animated: true)
+ return sheet
+ }
+ return nil
+}
+
extension View {
func appSheet(
isPresented: Binding,
diff --git a/apps/ios/Shared/Views/Helpers/ChatInfoImage.swift b/apps/ios/Shared/Views/Helpers/ChatInfoImage.swift
index 40d62e009b..a0f21aef9b 100644
--- a/apps/ios/Shared/Views/Helpers/ChatInfoImage.swift
+++ b/apps/ios/Shared/Views/Helpers/ChatInfoImage.swift
@@ -19,7 +19,7 @@ struct ChatInfoImage: View {
let iconColor = if case .local = chat.chatInfo { theme.appColors.primaryVariant2 } else { color }
return ProfileImage(
imageStr: chat.chatInfo.image,
- iconName: chatIconName(chat.chatInfo),
+ icon: chatIcon(chat.chatInfo),
size: size,
color: iconColor
)
diff --git a/apps/ios/Shared/Views/Helpers/ChatItemClipShape.swift b/apps/ios/Shared/Views/Helpers/ChatItemClipShape.swift
index 0491b38575..61a70832a9 100644
--- a/apps/ios/Shared/Views/Helpers/ChatItemClipShape.swift
+++ b/apps/ios/Shared/Views/Helpers/ChatItemClipShape.swift
@@ -16,6 +16,7 @@ import SimpleXChat
struct ChatItemClipped: ViewModifier {
@AppStorage(DEFAULT_CHAT_ITEM_ROUNDNESS) private var roundness = defaultChatItemRoundness
@AppStorage(DEFAULT_CHAT_ITEM_TAIL) private var tailEnabled = true
+ @Environment(\.terminalLayout) private var terminal
private let chatItem: (content: CIContent, chatDir: CIDirection)?
private let tailVisible: Bool
@@ -44,12 +45,18 @@ struct ChatItemClipped: ViewModifier {
} else {
tailVisible
}
- return tailEnabled
+ return tailEnabled && !terminal
? .bubble(
padding: ci.chatDir.sent ? .trailing : .leading,
tailVisible: tail
)
: .roundRect(radius: msgRectMaxRadius)
+ case .sndDeleted, .rcvDeleted, .sndModerated, .rcvModerated, .rcvBlocked:
+ return terminal
+ ? .roundRect(radius: 8)
+ : tailEnabled
+ ? .bubble(padding: ci.chatDir.sent ? .trailing : .leading, tailVisible: false)
+ : .roundRect(radius: msgRectMaxRadius)
case .rcvGroupInvitation, .sndGroupInvitation:
return .roundRect(radius: msgRectMaxRadius)
default: return .roundRect(radius: 8)
diff --git a/apps/ios/Shared/Views/Helpers/ImagePicker.swift b/apps/ios/Shared/Views/Helpers/ImagePicker.swift
index d7525027e0..8250229c87 100644
--- a/apps/ios/Shared/Views/Helpers/ImagePicker.swift
+++ b/apps/ios/Shared/Views/Helpers/ImagePicker.swift
@@ -78,9 +78,9 @@ struct LibraryMediaListPicker: UIViewControllerRepresentable {
private func loadImageData(_ p: NSItemProvider) async -> UploadContent? {
await withCheckedContinuation { cont in
- loadFileURL(p, type: UTType.data) { url in
+ loadFileURL(p, type: imageFileType(p)) { url in
if let url = url {
- let img = UploadContent.loadFromURL(url: url)
+ let img = UploadContent.loadImageFileFromURL(url: url)
cont.resume(returning: img)
} else {
cont.resume(returning: nil)
@@ -89,6 +89,11 @@ struct LibraryMediaListPicker: UIViewControllerRepresentable {
}
}
+ private func imageFileType(_ p: NSItemProvider) -> UTType {
+ let original = p.hasItemConformingToTypeIdentifier(UTType.png.identifier) || p.hasItemConformingToTypeIdentifier(UTType.gif.identifier)
+ return original || !p.hasItemConformingToTypeIdentifier(UTType.jpeg.identifier) ? UTType.data : UTType.jpeg
+ }
+
private func loadImage(_ p: NSItemProvider) async -> UIImage? {
await withCheckedContinuation { cont in
p.loadObject(ofClass: UIImage.self) { obj, err in
diff --git a/apps/ios/Shared/Views/Helpers/NameBadge.swift b/apps/ios/Shared/Views/Helpers/NameBadge.swift
index 5a48e495a2..085d9be0be 100644
--- a/apps/ios/Shared/Views/Helpers/NameBadge.swift
+++ b/apps/ios/Shared/Views/Helpers/NameBadge.swift
@@ -95,7 +95,7 @@ struct NameBadge: View {
}
}
-private func badgeImageName(_ t: BadgeType) -> String {
+func badgeImageName(_ t: BadgeType) -> String {
switch t {
case .legend: "badge-legend"
case .investor: "badge-investor"
@@ -147,8 +147,7 @@ func showBadgeInfoAlert(_ name: String, _ badge: LocalBadge) {
)
default:
// a verified badge's type is signed and can't be faked, so the real (possibly unknown) type name is the title
- let t = badge.badge.badgeType.text
- let title = t.prefix(1).uppercased() + t.dropFirst()
+ let title = badgeTypeName(badge.badge.badgeType)
if case .investor = badge.badge.badgeType {
let message = String.localizedStringWithFormat(NSLocalizedString("%@ invested in SimpleX Chat crowdfunding.", comment: "badge alert"), name)
showAlert(title, message: message) {
@@ -167,8 +166,23 @@ func showBadgeInfoAlert(_ name: String, _ badge: LocalBadge) {
} else {
String.localizedStringWithFormat(NSLocalizedString("%@ supports SimpleX Chat.", comment: "badge alert"), name)
}
- let v7 = NSLocalizedString("You can support SimpleX starting from v7 of the app.", comment: "badge alert")
- showAlert(title, message: supports + "\n\n" + v7)
+ if noShownBadge() {
+ showAlert(title, message: supports) {
+ [ supportSimpleXAlertAction, okAlertAction ]
+ }
+ } else {
+ showAlert(title, message: supports)
+ }
}
}
}
+
+// verbatim for an unknown type: it is the service's string, and must not be looked up as a localised key
+func badgeTypeName(_ t: BadgeType) -> String {
+ switch t {
+ case .supporter: NSLocalizedString("Supporter", comment: "badge type")
+ case .legend: NSLocalizedString("Legend", comment: "badge type")
+ case .investor: NSLocalizedString("Investor", comment: "badge type")
+ case let .unknown(s): s
+ }
+}
diff --git a/apps/ios/Shared/Views/Helpers/ProfileImage.swift b/apps/ios/Shared/Views/Helpers/ProfileImage.swift
index 9c2916880c..05b4a06967 100644
--- a/apps/ios/Shared/Views/Helpers/ProfileImage.swift
+++ b/apps/ios/Shared/Views/Helpers/ProfileImage.swift
@@ -12,7 +12,7 @@ import SimpleXChat
struct ProfileImage: View {
@EnvironmentObject var theme: AppTheme
var imageStr: String? = nil
- var iconName: String = "person.crop.circle.fill"
+ var icon: Image = Image(systemName: "person.crop.circle.fill")
var size: CGFloat
var color = Color(uiColor: .tertiarySystemGroupedBackground)
var backgroundColor: Color? = nil
@@ -24,7 +24,7 @@ struct ProfileImage: View {
clipProfileImage(Image(uiImage: uiImage), size: size, radius: radius, blurred: blurred)
} else {
let c = color.asAnotherColorFromSecondaryVariant(theme)
- Image(systemName: iconName)
+ icon
.resizable()
.foregroundColor(c)
.scaledToFit()
diff --git a/apps/ios/Shared/Views/Helpers/ShareSheet.swift b/apps/ios/Shared/Views/Helpers/ShareSheet.swift
index 56e437e5c8..ebe74b2a50 100644
--- a/apps/ios/Shared/Views/Helpers/ShareSheet.swift
+++ b/apps/ios/Shared/Views/Helpers/ShareSheet.swift
@@ -98,7 +98,7 @@ func openExternalLink(_ url: URL) {
} else {
showAlert(
title: NSLocalizedString("Open external link?", comment: "alert title"),
- message: s,
+ message: displayedUri(s),
buttonTitle: NSLocalizedString("Open", comment: "alert button"),
buttonAction: { UIApplication.shared.open(url) },
cancelButton: true
diff --git a/apps/ios/Shared/Views/Helpers/ThemeModeEditor.swift b/apps/ios/Shared/Views/Helpers/ThemeModeEditor.swift
index 9d5ae2e289..93027c21db 100644
--- a/apps/ios/Shared/Views/Helpers/ThemeModeEditor.swift
+++ b/apps/ios/Shared/Views/Helpers/ThemeModeEditor.swift
@@ -222,22 +222,26 @@ struct ChatWallpaperEditor: View {
@State var showMore: Bool = false
@State var showFileImporter: Bool = false
@Binding var globalThemeUsed: Bool
+ var layoutSection: AnyView
var save: (DefaultThemeMode?, ThemeModeOverride?) async -> Void
@State private var showImageImporter: Bool = false
- init(initialTheme: ThemeModeOverride, themeModeOverride: ThemeModeOverride, applyToMode: DefaultThemeMode? = nil, globalThemeUsed: Binding, save: @escaping (DefaultThemeMode?, ThemeModeOverride?) async -> Void) {
+ init(initialTheme: ThemeModeOverride, themeModeOverride: ThemeModeOverride, applyToMode: DefaultThemeMode? = nil, globalThemeUsed: Binding, layoutSection: AnyView, save: @escaping (DefaultThemeMode?, ThemeModeOverride?) async -> Void) {
let cur = ThemeManager.currentColors(nil, globalThemeUsed.wrappedValue ? nil : themeModeOverride, ChatModel.shared.currentUser?.uiThemes, themeOverridesDefault.get())
self.currentTheme = cur
self.initialTheme = initialTheme
self.themeModeOverride = themeModeOverride
self.applyToMode = applyToMode
self._globalThemeUsed = globalThemeUsed
+ self.layoutSection = layoutSection
self.save = save
}
var body: some View {
List {
+ layoutSection
+
WallpaperPresetSelector(
selectedWallpaper: currentTheme.wallpaper.type,
activeBackgroundColor: currentTheme.wallpaper.background,
@@ -451,3 +455,28 @@ private func AdvancedSettingsButton(_ primaryColor: Color, _ onClick: @escaping
}.foregroundColor(primaryColor)
}
}
+
+struct ChatLayoutSection: View {
+ var chatInfo: ChatInfo
+ var setChatLayout: (ChatLayout?) -> Void
+
+ var body: some View {
+ let defaultChatLayout = chatInfo.defaultChatLayout(profileChatLayout(ChatModel.shared.currentUser))
+ let otherLayout = otherChatLayout(defaultChatLayout)
+ let suffix = chatInfo.chatLayout == defaultChatLayout ? NSLocalizedString("(chat)", comment: "chat layout") : NSLocalizedString("(default)", comment: "chat layout")
+ Section {
+ Picker("Chat layout", selection: Binding(
+ get: { chatInfo.uiThemes?.chatLayout == otherLayout ? otherLayout : nil },
+ set: setChatLayout
+ )) {
+ Text(defaultChatLayout.displayName + " " + suffix).tag(nil as ChatLayout?)
+ Text(otherLayout.displayName).tag(otherLayout as ChatLayout?)
+ }
+ .frame(height: 36)
+ }
+ }
+}
+
+func otherChatLayout(_ layout: ChatLayout) -> ChatLayout {
+ layout == .terminal ? .classic : .terminal
+}
diff --git a/apps/ios/Shared/Views/Migration/MigrateFromDevice.swift b/apps/ios/Shared/Views/Migration/MigrateFromDevice.swift
index 2ff376701c..c262d1165a 100644
--- a/apps/ios/Shared/Views/Migration/MigrateFromDevice.swift
+++ b/apps/ios/Shared/Views/Migration/MigrateFromDevice.swift
@@ -709,6 +709,8 @@ private func showErrorOnMigrationIfNeeded(_ status: DBMigrationResult, _ alert:
alert.wrappedValue = .wrongPassphrase()
case .errorKeychain:
alert.wrappedValue = .keychainError()
+ case .errorKeyGeneration:
+ alert.wrappedValue = .databaseError(message: NSLocalizedString("Cannot generate random database passphrase", comment: "alert message"))
case let .errorSQL(_, error):
alert.wrappedValue = .databaseError(message: error)
case let .unknown(error):
diff --git a/apps/ios/Shared/Views/Migration/MigrateToDevice.swift b/apps/ios/Shared/Views/Migration/MigrateToDevice.swift
index cb3832b727..4181f6e73f 100644
--- a/apps/ios/Shared/Views/Migration/MigrateToDevice.swift
+++ b/apps/ios/Shared/Views/Migration/MigrateToDevice.swift
@@ -539,7 +539,7 @@ struct MigrateToDevice: View {
Task {
do {
if !hasChatCtrl() {
- chatInitControllerRemovingDatabases()
+ try chatInitControllerRemovingDatabases()
} else if ChatModel.shared.chatRunning == true {
// cannot delete storage if chat is running
try await stopChatAsync()
@@ -735,6 +735,8 @@ private func showErrorOnMigrationIfNeeded(_ status: DBMigrationResult, _ alert:
alert.wrappedValue = .wrongPassphrase()
case .errorKeychain:
alert.wrappedValue = .keychainError()
+ case .errorKeyGeneration:
+ alert.wrappedValue = .databaseError(message: NSLocalizedString("Cannot generate random database passphrase", comment: "alert message"))
case let .errorSQL(_, error):
alert.wrappedValue = .databaseError(message: error)
case let .unknown(error):
diff --git a/apps/ios/Shared/Views/NewChat/AddChannelView.swift b/apps/ios/Shared/Views/NewChat/AddChannelView.swift
index 7d1e5ce827..bd8c93b146 100644
--- a/apps/ios/Shared/Views/NewChat/AddChannelView.swift
+++ b/apps/ios/Shared/Views/NewChat/AddChannelView.swift
@@ -50,7 +50,7 @@ struct AddChannelView: View {
Spacer(minLength: 0)
ZStack(alignment: .center) {
ZStack(alignment: .topTrailing) {
- ProfileImage(imageStr: profile.image, iconName: "antenna.radiowaves.left.and.right.circle.fill", size: 128)
+ ProfileImage(imageStr: profile.image, icon: Image(systemName: "antenna.radiowaves.left.and.right.circle.fill"), size: 128)
if profile.image != nil {
Button {
profile.image = nil
@@ -285,7 +285,7 @@ struct AddChannelView: View {
let total = groupRelays.count
return List {
Group {
- ProfileImage(imageStr: gInfo.groupProfile.image, iconName: "antenna.radiowaves.left.and.right.circle.fill", size: 128)
+ ProfileImage(imageStr: gInfo.groupProfile.image, icon: Image(systemName: "antenna.radiowaves.left.and.right.circle.fill"), size: 128)
.frame(maxWidth: .infinity, alignment: .center)
Text(gInfo.groupProfile.displayName)
@@ -531,6 +531,8 @@ struct RelayProgressIndicator: View {
}
}
-#Preview {
- AddChannelView()
+struct AddChannelView_Previews: PreviewProvider {
+ static var previews: some View {
+ AddChannelView()
+ }
}
diff --git a/apps/ios/Shared/Views/NewChat/AddGroupView.swift b/apps/ios/Shared/Views/NewChat/AddGroupView.swift
index 47afee5f06..a4f02e51ba 100644
--- a/apps/ios/Shared/Views/NewChat/AddGroupView.swift
+++ b/apps/ios/Shared/Views/NewChat/AddGroupView.swift
@@ -71,7 +71,7 @@ struct AddGroupView: View {
Spacer(minLength: 0)
ZStack(alignment: .center) {
ZStack(alignment: .topTrailing) {
- ProfileImage(imageStr: profile.image, iconName: "person.2.circle.fill", size: 128)
+ ProfileImage(imageStr: profile.image, icon: Image(systemName: "person.2.circle.fill"), size: 128)
if profile.image != nil {
Button {
profile.image = nil
diff --git a/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift b/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift
index 416dc32308..60aca9be1f 100644
--- a/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift
+++ b/apps/ios/Shared/Views/NewChat/NewChatMenuButton.swift
@@ -497,6 +497,8 @@ struct DeletedChats: View {
}
}
-#Preview {
- NewChatMenuButton(showNewChatSheet: Binding.constant(false))
+struct NewChatMenuButton_Previews: PreviewProvider {
+ static var previews: some View {
+ NewChatMenuButton(showNewChatSheet: Binding.constant(false))
+ }
}
diff --git a/apps/ios/Shared/Views/NewChat/NewChatView.swift b/apps/ios/Shared/Views/NewChat/NewChatView.swift
index f938fb0063..b558802d36 100644
--- a/apps/ios/Shared/Views/NewChat/NewChatView.swift
+++ b/apps/ios/Shared/Views/NewChat/NewChatView.swift
@@ -739,6 +739,7 @@ struct ScannerInView: View {
let processQRCode: (_ resp: Result) -> Void
@State private var cameraAuthorizationStatus: AVAuthorizationStatus?
var scanMode: ScanMode = .continuous
+ var placeholderBackground = Color(uiColor: .secondarySystemGroupedBackground)
var body: some View {
Group {
@@ -777,7 +778,7 @@ struct ScannerInView: View {
.padding()
.background(
RoundedRectangle(cornerRadius: 12, style: .continuous)
- .fill(Color(uiColor: .secondarySystemGroupedBackground))
+ .fill(placeholderBackground)
)
.padding(.horizontal)
.listRowBackground(Color.clear)
@@ -1128,11 +1129,9 @@ private func showPrepareContactAlert(
profileImage:
ProfileImage(
imageStr: contactShortLinkData.profile.image,
- iconName: contactShortLinkData.business
- ? "briefcase.circle.fill"
- : contactShortLinkData.profile.peerType == .bot
- ? "cube.fill"
- : "person.crop.circle.fill",
+ icon: contactShortLinkData.business
+ ? Image(systemName: "briefcase.circle.fill")
+ : peerTypeIcon(contactShortLinkData.profile.peerType),
size: alertProfileImageSize
),
profileBadge: contactShortLinkData.localBadge,
@@ -1185,9 +1184,9 @@ private func showPrepareGroupAlert(
profileImage:
ProfileImage(
imageStr: groupShortLinkData.groupProfile.image,
- iconName: isChannel
+ icon: Image(systemName: isChannel
? "antenna.radiowaves.left.and.right.circle.fill"
- : "person.2.circle.fill",
+ : "person.2.circle.fill"),
size: alertProfileImageSize
),
theme: theme,
@@ -1239,7 +1238,7 @@ private func showOpenKnownContactAlert(
profileImage:
ProfileImage(
imageStr: contact.profile.image,
- iconName: contact.chatIconName,
+ icon: contact.chatIcon,
size: alertProfileImageSize
),
profileBadge: contact.active ? contact.profile.localBadge : nil,
@@ -1287,7 +1286,7 @@ private func showOpenKnownGroupAlert(
profileImage:
ProfileImage(
imageStr: groupInfo.groupProfile.image,
- iconName: groupInfo.chatIconName,
+ icon: Image(systemName: groupInfo.chatIconName),
size: alertProfileImageSize
),
theme: theme,
@@ -1604,7 +1603,7 @@ func planAndConnect(
profileImage:
ProfileImage(
imageStr: groupSLinkData.groupProfile.image,
- iconName: "antenna.radiowaves.left.and.right.circle.fill",
+ icon: Image(systemName: "antenna.radiowaves.left.and.right.circle.fill"),
size: alertProfileImageSize
),
theme: theme,
@@ -1631,7 +1630,7 @@ func planAndConnect(
profileImage:
ProfileImage(
imageStr: groupSLinkData.groupProfile.image,
- iconName: "person.2.circle.fill",
+ icon: Image(systemName: "person.2.circle.fill"),
size: alertProfileImageSize
),
theme: theme,
diff --git a/apps/ios/Shared/Views/NewChat/QRCode.swift b/apps/ios/Shared/Views/NewChat/QRCode.swift
index 2b38065bd9..6ab370a11a 100644
--- a/apps/ios/Shared/Views/NewChat/QRCode.swift
+++ b/apps/ios/Shared/Views/NewChat/QRCode.swift
@@ -46,19 +46,31 @@ struct SimpleXLinkQRCode: View {
private let smallQRRatio: CGFloat = 0.63
+extension EnvironmentValues {
+ struct FixedQRCode: EnvironmentKey {
+ static let defaultValue: UIImage? = nil
+ }
+
+ var fixedQRCode: UIImage? {
+ get { self[FixedQRCode.self] }
+ set { self[FixedQRCode.self] = newValue }
+ }
+}
+
struct QRCode: View {
let uri: String
var small: Bool = false
var withLogo: Bool = true
var tintColor = UIColor(red: 0.023, green: 0.176, blue: 0.337, alpha: 1)
var onShare: (() -> Void)? = nil
+ @Environment(\.fixedQRCode) private var fixedQRCode
@State private var image: UIImage? = nil
@State private var makeScreenshotFunc: () -> Void = {}
@State private var width: CGFloat = .infinity
var body: some View {
ZStack {
- if let image = image {
+ if let image = fixedQRCode ?? image {
qrCodeImage(image).frame(width: width, height: width)
GeometryReader { g in
let w = g.size.width * (small ? smallQRRatio : 1)
@@ -90,7 +102,7 @@ struct QRCode: View {
}
}
.onTapGesture(perform: makeScreenshotFunc)
- .task { image = await generateImage(uri, tintColor: tintColor, errorLevel: small ? "M" : "L") }
+ .task { if fixedQRCode == nil { image = await generateImage(uri, tintColor: tintColor, errorLevel: small ? "M" : "L") } }
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
@@ -103,7 +115,7 @@ private func qrCodeImage(_ image: UIImage) -> some View {
.textSelection(.enabled)
}
-private func generateImage(_ uri: String, tintColor: UIColor, errorLevel: String) async -> UIImage? {
+func generateImage(_ uri: String, tintColor: UIColor, errorLevel: String) async -> UIImage? {
let context = CIContext()
let filter = CIFilter.qrCodeGenerator()
filter.message = Data(uri.utf8)
@@ -131,6 +143,6 @@ extension View {
struct QRCode_Previews: PreviewProvider {
static var previews: some View {
- QRCode(uri: "https://simplex.chat/invitation#/?v=1&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2FFe5ICmvrm4wkrr6X1LTMii-lhBqLeB76%23MCowBQYDK2VuAyEAdhZZsHpuaAk3Hh1q0uNb_6hGTpuwBIrsp2z9U2T0oC0%3D&e2e=v%3D1%26x3dh%3DMEIwBQYDK2VvAzkAcz6jJk71InuxA0bOX7OUhddfB8Ov7xwQIlIDeXBRZaOntUU4brU5Y3rBzroZBdQJi0FKdtt_D7I%3D%2CMEIwBQYDK2VvAzkA-hDvk1duBi1hlOr08VWSI-Ou4JNNSQjseY69QyKm7Kgg1zZjbpGfyBqSZ2eqys6xtoV4ZtoQUXQ%3D")
+ QRCode(uri: "https://smp6.simplex.im/a#lrdvu2d8A1GumSmoKb2krQmtKhWXq-tyGpHuM7aMwsw", small: true)
}
}
diff --git a/apps/ios/Shared/Views/Onboarding/ChooseServerOperators.swift b/apps/ios/Shared/Views/Onboarding/ChooseServerOperators.swift
index 2c21682dba..3c4c12ae2b 100644
--- a/apps/ios/Shared/Views/Onboarding/ChooseServerOperators.swift
+++ b/apps/ios/Shared/Views/Onboarding/ChooseServerOperators.swift
@@ -398,6 +398,8 @@ struct ChooseServerOperatorsInfoView: View {
}
}
-#Preview {
- OnboardingConditionsView(selectedOperatorIds: [])
+struct OnboardingConditionsView_Previews: PreviewProvider {
+ static var previews: some View {
+ OnboardingConditionsView(selectedOperatorIds: [])
+ }
}
diff --git a/apps/ios/Shared/Views/Onboarding/HowItWorks.swift b/apps/ios/Shared/Views/Onboarding/HowItWorks.swift
index e9b9c6b970..dd01534dfb 100644
--- a/apps/ios/Shared/Views/Onboarding/HowItWorks.swift
+++ b/apps/ios/Shared/Views/Onboarding/HowItWorks.swift
@@ -65,6 +65,7 @@ struct WhySimpleX: View {
@Environment(\.dismiss) var dismiss: DismissAction
@EnvironmentObject var m: ChatModel
var onboarding: Bool
+ var titleColor: Color? = nil
@Binding var createProfileNavLinkActive: Bool
var body: some View {
@@ -74,6 +75,7 @@ struct WhySimpleX: View {
Text("You were born without an account")
.font(.title)
.bold()
+ .foregroundColor(titleColor)
.padding(.top)
Text("Nobody tracked your conversations. No one drew a map of where you'd been. Privacy was never a feature - it was the way of life.")
Text("Then we moved online, and every platform asked for a piece of you - your name, your number, your friends. We accepted that the price of talking to others is letting someone know who we talk to. Every generation, people and tech, had it this way - telephone, email, messengers, social media. It seemed the only way possible.")
diff --git a/apps/ios/Shared/Views/Onboarding/SetNotificationsMode.swift b/apps/ios/Shared/Views/Onboarding/SetNotificationsMode.swift
index 1a1f1bb68c..9c0cbe8d71 100644
--- a/apps/ios/Shared/Views/Onboarding/SetNotificationsMode.swift
+++ b/apps/ios/Shared/Views/Onboarding/SetNotificationsMode.swift
@@ -73,6 +73,7 @@ struct NtfModeSelector: View {
.resizable()
.scaledToFill()
.frame(width: mode.icon == "bolt" ? 14 : 18, height: 18)
+ .frame(width: 18)
.foregroundColor(selection == mode ? theme.colors.primary : theme.colors.secondary)
VStack(alignment: .leading, spacing: 4) {
Text(mode.label)
diff --git a/apps/ios/Shared/Views/Onboarding/WhatsNewView.swift b/apps/ios/Shared/Views/Onboarding/WhatsNewView.swift
index ba87729012..5bd57ba798 100644
--- a/apps/ios/Shared/Views/Onboarding/WhatsNewView.swift
+++ b/apps/ios/Shared/Views/Onboarding/WhatsNewView.swift
@@ -33,6 +33,7 @@ private struct Description {
let icon: String?
let title: LocalizedStringKey
let description: LocalizedStringKey?
+ var learnMore: URL? = nil
var subfeatures: [(icon: String, description: LocalizedStringKey)] = []
}
@@ -676,7 +677,7 @@ private let versionDescriptions: [VersionDescription] = [
features: (isInUS ? [
.view(FeatureView(
icon: nil,
- title: "You can now invest in SimpleX Chat",
+ title: "Own a part of SimpleX Chat",
view: { InvestInSimpleXChat() }
))
] : []) + [
@@ -698,6 +699,39 @@ private let versionDescriptions: [VersionDescription] = [
))
]
),
+ VersionDescription(
+ version: "v7.1",
+ post: nil,
+ features: (isInUS ? [
+ .view(FeatureView(
+ icon: nil,
+ title: "Own a part of SimpleX Chat",
+ view: { InvestInSimpleXChat() }
+ ))
+ ] : []) + [
+ .view(FeatureView(
+ icon: nil,
+ title: "Supporter badges",
+ view: { SupporterBadgeWhatsNew() }
+ )),
+ .feature(Description(
+ icon: "at",
+ title: "SimpleX public names",
+ description: "Sale starts on December 12.",
+ learnMore: URL(string: "https://simplex.domains/?utm_source=app_ios")
+ )),
+ .feature(Description(
+ icon: "antenna.radiowaves.left.and.right",
+ title: "Safer channels",
+ description: "Add moderators and sign every message."
+ )),
+ .feature(Description(
+ icon: "terminal",
+ title: "Flat layout and markdown",
+ description: "Enable in Appearance settings."
+ )),
+ ]
+ ),
]
private let lastVersion = versionDescriptions.last!.version
@@ -712,6 +746,35 @@ func shouldShowWhatsNew() -> Bool {
return v != lastVersion
}
+fileprivate struct SupporterBadgeWhatsNew: View {
+ @EnvironmentObject var theme: AppTheme
+ @ObservedObject private var badgeModel = BadgeModel.shared
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack(alignment: .center, spacing: 4) {
+ Image(badgeImageName(.supporter))
+ .resizable()
+ .scaledToFit()
+ .frame(width: 24, height: 24)
+ .frame(minWidth: 30, alignment: .center)
+ Text("Supporter badges").font(.title3).bold()
+ }
+ Text("Larger files available for longer.")
+ .multilineTextAlignment(.leading)
+ .lineLimit(10)
+ if currentShownBadge() != nil {
+ Text("You already have a badge!")
+ } else if noShownBadge() {
+ Text("Support SimpleX and get a badge.")
+ .foregroundColor(theme.colors.primary)
+ .onTapGesture { openBadgesView() }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+}
+
fileprivate struct NewOperatorsView: View {
var body: some View {
VStack(alignment: .leading) {
@@ -780,22 +843,23 @@ fileprivate struct InvestInSimpleXChat: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
- Text("You can now invest in SimpleX Chat! 🚀").font(.title3).bold()
- (Text("Crowdfunding on Wefunder.") + Text(verbatim: " ") + Text("Learn more").foregroundColor(theme.colors.primary))
- .multilineTextAlignment(.leading)
- .onTapGesture { showGetStakeSheet = true }
+ Text("Own a part of SimpleX Chat! 🚀").font(.title3).bold()
#if SIMPLEX_ASSETS
Image("crowdfunding_1")
.resizable()
.scaledToFit()
.cornerRadius(12)
- .padding(.vertical, 4)
+ .padding(.top, 4)
+ .padding(.bottom, 8)
.onTapGesture { showGetStakeSheet = true }
#endif
+ (Text("Crowdfunding on Wefunder.") + Text(verbatim: " ") + Text("Learn more").foregroundColor(theme.colors.primary))
+ .multilineTextAlignment(.leading)
+ .onTapGesture { showGetStakeSheet = true }
}
.frame(maxWidth: .infinity, alignment: .leading)
.sheet(isPresented: $showGetStakeSheet) {
- GetStakeView(fromSettings: false)
+ GetStakeView(fromSettings: false, showFirstImage: false)
}
}
}
@@ -821,13 +885,13 @@ fileprivate let getStakeSlides: [(image: String, heading: String, info: String?,
),
(
"crowdfunding_4",
- "Revenue plan: free for users, channels & businesses pay",
+ "Revenue plan: businesses & big channels pay",
"SimpleX Chat plans to earn from the infrastructure and services that creators, businesses and large communities need as they grow.",
"Read about how we plan to make SimpleX Chat and network profitable, and about all the investment terms on Wefunder."
),
]
-private let wefunderURL = URL(string: "https://wefunder.com/simplex.chat?utm_source=app")!
+let wefunderURL = URL(string: "https://wefunder.com/simplex.chat?utm_source=app_ios")!
private let simplexCrowdfundingURL = URL(string: "simplex:/a#JxGcOA1_QhlmVFzYYabloMbvMZk5Y9d9iS3ITDnhzYo?h=smp11.simplex.im")!
@@ -835,16 +899,17 @@ struct GetStakeView: View {
@Environment(\.dismiss) var dismiss: DismissAction
@EnvironmentObject var chatModel: ChatModel
var fromSettings: Bool
+ var showFirstImage: Bool
var body: some View {
ZoomablePageView {
VStack(alignment: .leading, spacing: 18) {
- Text(verbatim: "Get a stake in\nSimpleX Chat")
+ Text(verbatim: "Invest in\nSimpleX Chat")
.font(.largeTitle)
.bold()
.fixedSize(horizontal: false, vertical: true)
.if(!fromSettings) { $0.padding(.top) }
- if fromSettings {
+ if showFirstImage {
slideImage(getStakeSlides[0])
}
(Text(verbatim: getStakeSlides[0].text) + Text(verbatim: " Learn more and invest on Wefunder.").bold().foregroundColor(.accentColor))
@@ -1010,9 +1075,16 @@ struct WhatsNewView: View {
VStack(alignment: .leading, spacing: 4) {
featureHeader(f.icon, f.title)
if let d = f.description {
- Text(d)
- .multilineTextAlignment(.leading)
- .lineLimit(10)
+ if let url = f.learnMore {
+ (Text(d) + Text(verbatim: " ") + Text("Learn more.").foregroundColor(theme.colors.primary))
+ .multilineTextAlignment(.leading)
+ .lineLimit(10)
+ .onTapGesture { UIApplication.shared.open(url) }
+ } else {
+ Text(d)
+ .multilineTextAlignment(.leading)
+ .lineLimit(10)
+ }
}
if f.subfeatures.count > 0 {
ForEach(f.subfeatures, id: \.icon) { s in
diff --git a/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift b/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift
index 24ae5cffca..e7393ecc1c 100644
--- a/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift
+++ b/apps/ios/Shared/Views/RemoteAccess/ConnectDesktopView.swift
@@ -539,6 +539,8 @@ struct ConnectDesktopView: View {
}
}
-#Preview {
- ConnectDesktopView()
+struct ConnectDesktopView_Previews: PreviewProvider {
+ static var previews: some View {
+ ConnectDesktopView()
+ }
}
diff --git a/apps/ios/Shared/Views/TerminalView.swift b/apps/ios/Shared/Views/TerminalView.swift
index ac143fe044..32209e97fa 100644
--- a/apps/ios/Shared/Views/TerminalView.swift
+++ b/apps/ios/Shared/Views/TerminalView.swift
@@ -194,8 +194,8 @@ struct TerminalView_Previews: PreviewProvider {
static var previews: some View {
let chatModel = ChatModel()
chatModel.terminalItems = [
- .err(.now, APIResult.invalid(type: "contactSubscribed", json: "{}".data(using: .utf8)!).unexpected),
- .err(.now, APIResult.invalid(type: "newChatItems", json: "{}".data(using: .utf8)!).unexpected)
+ .err(previewDate, APIResult.invalid(type: "contactSubscribed", json: "{}".data(using: .utf8)!).unexpected),
+ .err(previewDate + 1, APIResult.invalid(type: "newChatItems", json: "{}".data(using: .utf8)!).unexpected)
]
return NavigationView {
TerminalView()
diff --git a/apps/ios/Shared/Views/UserSettings/AppSettings.swift b/apps/ios/Shared/Views/UserSettings/AppSettings.swift
index 3554ce720f..849abb4d62 100644
--- a/apps/ios/Shared/Views/UserSettings/AppSettings.swift
+++ b/apps/ios/Shared/Views/UserSettings/AppSettings.swift
@@ -67,6 +67,7 @@ extension AppSettings {
if let val = uiThemes { themeOverridesDefault.set(val.skipDuplicates()) }
if let val = oneHandUI { groupDefaults.setValue(val, forKey: GROUP_DEFAULT_ONE_HAND_UI) }
if let val = chatBottomBar { groupDefaults.setValue(val, forKey: GROUP_DEFAULT_CHAT_BOTTOM_BAR) }
+ if let val = uiChatLayout { chatLayoutDefault.set(val) }
}
public static var current: AppSettings {
@@ -104,6 +105,7 @@ extension AppSettings {
c.uiThemes = themeOverridesDefault.get()
c.oneHandUI = groupDefaults.bool(forKey: GROUP_DEFAULT_ONE_HAND_UI)
c.chatBottomBar = groupDefaults.bool(forKey: GROUP_DEFAULT_CHAT_BOTTOM_BAR)
+ c.uiChatLayout = chatLayoutDefault.get()
return c
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift b/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift
index 54a60eed19..477dd31093 100644
--- a/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift
+++ b/apps/ios/Shared/Views/UserSettings/AppearanceSettings.swift
@@ -39,6 +39,7 @@ struct AppearanceSettings: View {
@AppStorage(DEFAULT_CHAT_ITEM_TAIL) private var chatItemTail = true
@AppStorage(GROUP_DEFAULT_ONE_HAND_UI, store: groupDefaults) private var oneHandUI = true
@AppStorage(DEFAULT_TOOLBAR_MATERIAL) private var toolbarMaterial = ToolbarMaterial.defaultMaterial
+ @AppStorage(DEFAULT_CHAT_LAYOUT) private var appChatLayout = ChatLayout.classic
@State var themeUserDestination: (Int64, ThemeModeOverrides?)? = {
if let currentUser = ChatModel.shared.currentUser, let uiThemes = currentUser.uiThemes, uiThemes.preferredMode(!CurrentColors.colors.isLight) != nil {
@@ -81,11 +82,14 @@ struct AppearanceSettings: View {
Section {
ThemeDestinationPicker(themeUserDestination: $themeUserDestination, themeUserDest: themeUserDestination?.0, customizeThemeIsOpen: $customizeThemeIsOpen)
+ ChatLayoutPicker(themeUserDestination: $themeUserDestination, appLayout: $appChatLayout)
+
WallpaperPresetSelector(
selectedWallpaper: theme.wallpaper.type,
currentColors: currentColors,
onChooseType: onChooseType
)
+ .environment(\.terminalLayout, profileChatLayout(themeUserDestination == nil ? nil : m.currentUser, appChatLayout) == .terminal)
.padding(.bottom, 10)
.listRowInsets(.init())
.listRowBackground(Color.clear)
@@ -146,6 +150,7 @@ struct AppearanceSettings: View {
}
} else {
CustomizeThemeView(onChooseType: onChooseType)
+ .environment(\.terminalLayout, profileChatLayout(nil) == .terminal)
.navigationTitle("Customize theme")
.modifier(ThemedBackground(grouped: true))
.onAppear {
@@ -355,6 +360,7 @@ enum ToolbarMaterial: String, CaseIterable {
struct ChatThemePreview: View {
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var base: DefaultTheme
var wallpaperType: WallpaperType?
var backgroundColor: Color?
@@ -369,16 +375,34 @@ struct ChatThemePreview: View {
if withMessages {
let alice = ChatItem.getSample(1, CIDirection.directRcv, Date.now, NSLocalizedString("Good afternoon!", comment: "message preview"))
let bob = ChatItem.getSample(2, CIDirection.directSnd, Date.now, NSLocalizedString("Good morning!", comment: "message preview"), quotedItem: CIQuote.getSample(alice.id, alice.meta.itemTs, alice.content.text, chatDir: alice.chatDir))
- HStack {
- ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: alice, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- .modifier(ChatItemClipped(alice, tailVisible: true))
- Spacer()
- }
- HStack {
- Spacer()
- ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: bob, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
- .modifier(ChatItemClipped(bob, tailVisible: true))
- .frame(alignment: .trailing)
+ ZStack {
+ VStack {
+ HStack {
+ ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: alice, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ .modifier(ChatItemClipped(alice, tailVisible: true))
+ Spacer()
+ }
+ HStack {
+ Spacer()
+ ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: bob, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ .modifier(ChatItemClipped(bob, tailVisible: true))
+ .frame(alignment: .trailing)
+ }
+ }
+ .environment(\.terminalLayout, false)
+ .opacity(terminal ? 0 : 1)
+ .accessibilityHidden(terminal)
+ VStack(spacing: 0) {
+ TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "alice"), own: false), gutter: 0, topGap: terminalRowGap(alice, nil, separated: false, largeGap: true, hasSenderRow: true), contentStartsWithCard: terminalItemStartsWithCard(alice, revealed: true)) {
+ ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: alice, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ }
+ TerminalChatItemRow(sender: ChatItemSender(name: Text(verbatim: "bob"), own: true), gutter: 0, topGap: terminalRowGap(bob, alice, separated: false, largeGap: true, hasSenderRow: true), contentStartsWithCard: terminalItemStartsWithCard(bob, revealed: true)) {
+ ChatItemView(chat: Chat.sampleData, im: ItemsModel.shared, chatItem: bob, scrollToItem: { _ in }, scrollToItemId: Binding.constant(nil))
+ }
+ }
+ .environment(\.terminalLayout, true)
+ .opacity(terminal ? 1 : 0)
+ .accessibilityHidden(!terminal)
}
} else {
Rectangle().fill(.clear)
@@ -388,16 +412,17 @@ struct ChatThemePreview: View {
.padding(.horizontal, 16)
.frame(maxWidth: .infinity)
- if let wallpaperType, let wallpaperImage = wallpaperType.image, let backgroundColor, let tintColor {
+ if !terminal, let wallpaperType, let wallpaperImage = wallpaperType.image, let backgroundColor, let tintColor {
view.modifier(ChatViewBackground(image: wallpaperImage, imageType: wallpaperType, background: backgroundColor, tint: tintColor))
} else {
- view.background(themeBackgroundColor)
+ view.background(terminal ? backgroundColor ?? themeBackgroundColor : themeBackgroundColor)
}
}
}
struct WallpaperPresetSelector: View {
@EnvironmentObject var theme: AppTheme
+ @Environment(\.terminalLayout) private var terminal
var selectedWallpaper: WallpaperType?
var activeBackgroundColor: Color? = nil
var activeTintColor: Color? = nil
@@ -426,7 +451,9 @@ struct WallpaperPresetSelector: View {
ForEach(backgrounds, id: \.self) { background in
BackgroundItem(background)
}
- OwnBackgroundItem(selectedWallpaper)
+ if !terminal {
+ OwnBackgroundItem(selectedWallpaper)
+ }
}
}
}
@@ -716,6 +743,7 @@ struct UserWallpaperEditorSheet: View {
}
}
)
+ .environment(\.terminalLayout, profileChatLayout(ChatModel.shared.currentUser) == .terminal)
.navigationTitle("Profile theme")
.modifier(ThemedBackground(grouped: true))
.onAppear {
@@ -775,14 +803,14 @@ struct UserWallpaperEditorSheet: View {
let filePath = saveWallpaperFile(url: getWallpaperFilePath(imageFile))
if currentMode == DefaultThemeMode.light {
dark.wallpaper?.imageFile = filePath
- changedThemes = ThemeModeOverrides(light: changedThemes?.light, dark: dark)
+ changedThemes?.dark = dark
} else {
light.wallpaper?.imageFile = filePath
- changedThemes = ThemeModeOverrides(light: light, dark: changedThemes?.dark)
+ changedThemes?.light = light
}
}
} else {
- changedThemes = nil
+ changedThemes = changedThemes?.layoutOnly()
}
wallpaperFiles.remove(changedThemes?.light?.wallpaper?.imageFile)
wallpaperFiles.remove(changedThemes?.dark?.wallpaper?.imageFile)
@@ -847,7 +875,7 @@ struct ThemeDestinationPicker: View {
if isNil {
// Easiest way to hide per-user customization.
// Otherwise, it would be needed to make global variable and to use it everywhere for making a decision to include these overrides into active theme constructing or not
- m.currentUser?.uiThemes = nil
+ m.currentUser?.uiThemes = m.currentUser?.uiThemes?.layoutOnly()
} else {
m.updateCurrentUserUiThemes(uiThemes: m.users.first(where: { $0.user.userId == m.currentUser?.userId })?.user.uiThemes)
}
@@ -873,6 +901,36 @@ struct ThemeDestinationPicker: View {
}
}
+struct ChatLayoutPicker: View {
+ @Binding var themeUserDestination: (Int64, ThemeModeOverrides?)?
+ @Binding var appLayout: ChatLayout
+
+ var body: some View {
+ if let dest = themeUserDestination {
+ let defaultLayout = profileChatLayout(nil)
+ let otherLayout = otherChatLayout(defaultLayout)
+ Picker("Chat layout", selection: Binding(
+ get: { dest.1?.chatLayout == otherLayout ? otherLayout : nil },
+ set: { layout in
+ themeUserDestination = (dest.0, (dest.1 ?? ThemeModeOverrides()).withChatLayout(layout))
+ saveThemeToDatabase(themeUserDestination)
+ }
+ )) {
+ Text(defaultLayout.displayName + " " + NSLocalizedString("(default)", comment: "chat layout")).tag(nil as ChatLayout?)
+ Text(otherLayout.displayName).tag(otherLayout as ChatLayout?)
+ }
+ .frame(height: 36)
+ } else {
+ Picker("Chat layout", selection: $appLayout) {
+ ForEach([ChatLayout.classic, ChatLayout.terminal], id: \.self) { layout in
+ Text(layout.displayName).tag(layout)
+ }
+ }
+ .frame(height: 36)
+ }
+ }
+}
+
struct CustomizeThemeColorsSection: View {
@EnvironmentObject var theme: AppTheme
var editColor: (ThemeColor) -> Binding
@@ -919,6 +977,7 @@ func editColorBinding(name: ThemeColor, wallpaperType: WallpaperType?, wallpaper
}
struct WallpaperSetupView: View {
+ @Environment(\.terminalLayout) private var terminal
var wallpaperType: WallpaperType?
var base: DefaultTheme
var initialWallpaper: AppWallpaper?
@@ -926,7 +985,7 @@ struct WallpaperSetupView: View {
var onTypeChange: (WallpaperType?) -> Void
var body: some View {
- if let wallpaperType, case let WallpaperType.image(_, _, scaleType) = wallpaperType {
+ if !terminal, let wallpaperType, case let WallpaperType.image(_, _, scaleType) = wallpaperType {
let wallpaperScaleType = if let scaleType {
scaleType
} else if let initialWallpaper, case let WallpaperType.image(_, _, scaleType) = initialWallpaper.type, let scaleType {
@@ -938,15 +997,17 @@ struct WallpaperSetupView: View {
}
- if let wallpaperType, wallpaperType.isPreset {
+ if !terminal, let wallpaperType, wallpaperType.isPreset {
WallpaperScaleChooser(wallpaperScale: Binding.constant(initialWallpaper?.type.scale ?? 1), wallpaperType: wallpaperType, onTypeChange: onTypeChange)
- } else if let wallpaperType, case let WallpaperType.image(_, _, scaleType) = wallpaperType, scaleType == WallpaperScaleType.repeat {
+ } else if !terminal, let wallpaperType, case let WallpaperType.image(_, _, scaleType) = wallpaperType, scaleType == WallpaperScaleType.repeat {
WallpaperScaleChooser(wallpaperScale: Binding.constant(initialWallpaper?.type.scale ?? 1), wallpaperType: wallpaperType, onTypeChange: onTypeChange)
}
if wallpaperType?.isPreset == true || wallpaperType?.isImage == true {
picker(.wallpaperBackground, editColor)
- picker(.wallpaperTint, editColor)
+ if !terminal {
+ picker(.wallpaperTint, editColor)
+ }
}
picker(.sentMessage, editColor)
@@ -1135,7 +1196,7 @@ private func saveThemeToDatabase(_ themeUserDestination: (Int64, ThemeModeOverri
private func removeUserThemeModeOverrides(_ themeUserDestination: Binding<(Int64, ThemeModeOverrides?)?>, _ perUserTheme: Binding) {
guard let dest = themeUserDestination.wrappedValue else { return }
perUserTheme.wrappedValue = ThemeModeOverride(mode: CurrentColors.base.mode)
- themeUserDestination.wrappedValue = (dest.0, nil)
+ themeUserDestination.wrappedValue = (dest.0, dest.1?.layoutOnly())
var wallpaperFilesToDelete: [String] = []
if let type = ChatModel.shared.currentUser?.uiThemes?.light?.type, case let WallpaperType.image(filename, _, _) = type {
wallpaperFilesToDelete.append(filename)
diff --git a/apps/ios/Shared/Views/UserSettings/MarkdownHelp.swift b/apps/ios/Shared/Views/UserSettings/MarkdownHelp.swift
index 71c284e9ab..805b5a0c80 100644
--- a/apps/ios/Shared/Views/UserSettings/MarkdownHelp.swift
+++ b/apps/ios/Shared/Views/UserSettings/MarkdownHelp.swift
@@ -15,7 +15,7 @@ struct MarkdownHelp: View {
VStack(alignment: .leading, spacing: 8) {
Text("You can use markdown to format messages:")
.padding(.bottom)
- mdFormat("*bold*", Text("bold").bold())
+ mdFormat(Text(verbatim: "**") + Text("bold") + Text(verbatim: "**"), Text("bold").bold())
mdFormat("_italic_", Text("italic").italic())
mdFormat("~strike~", Text("strike").strikethrough())
mdFormat("`a + b`", Text("`a + b`").font(.body.monospaced()))
@@ -32,8 +32,12 @@ struct MarkdownHelp: View {
}
private func mdFormat(_ format: LocalizedStringKey, _ example: Text) -> some View {
+ mdFormat(Text(format), example)
+}
+
+private func mdFormat(_ format: Text, _ example: Text) -> some View {
HStack {
- Text(format).frame(width: 120, alignment: .leading)
+ format.frame(width: 120, alignment: .leading)
example
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ConditionsWebView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ConditionsWebView.swift
index 5abbbf8d2e..6a05851c63 100644
--- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ConditionsWebView.swift
+++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ConditionsWebView.swift
@@ -12,11 +12,15 @@ import WebKit
struct ConditionsWebView: UIViewRepresentable {
@State var html: String
+ var openLink: (URL) -> Void = openExternalLink
@EnvironmentObject var theme: AppTheme
@State var pageLoaded = false
func makeUIView(context: Context) -> WKWebView {
- let view = WKWebView()
+ let config = WKWebViewConfiguration()
+ config.defaultWebpagePreferences.allowsContentJavaScript = false
+ config.websiteDataStore = .nonPersistent()
+ let view = WKWebView(frame: .zero, configuration: config)
view.backgroundColor = .clear
view.isOpaque = false
view.navigationDelegate = context.coordinator
@@ -35,8 +39,9 @@ struct ConditionsWebView: UIViewRepresentable {
}
private func loadPage(_ webView: WKWebView) {
+ let nonce = UUID().uuidString
let styles = """
-
"""
- let head = " \(styles)"
+ let csp = " "
+ let head = "\(csp) \(styles)"
webView.loadHTMLString(head + html, baseURL: nil)
DispatchQueue.main.async {
pageLoaded = true
@@ -58,10 +77,16 @@ struct ConditionsWebView: UIViewRepresentable {
}
func makeCoordinator() -> Cordinator {
- Cordinator()
+ Cordinator(openLink: openLink)
}
class Cordinator: NSObject, WKNavigationDelegate {
+ let openLink: (URL) -> Void
+
+ init(openLink: @escaping (URL) -> Void) {
+ self.openLink = openLink
+ }
+
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
@@ -71,9 +96,9 @@ struct ConditionsWebView: UIViewRepresentable {
switch navigationAction.navigationType {
case .linkActivated:
decisionHandler(.cancel)
- openExternalLink(url)
+ openLink(url)
default:
- decisionHandler(.allow)
+ decisionHandler(url.scheme == "about" ? .allow : .cancel)
}
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift
index 8095c0297e..c181a19a60 100644
--- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift
+++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NetworkAndServers.swift
@@ -514,5 +514,6 @@ func updateOperatorsConditionsAcceptance(_ usvs: Binding<[UserOperatorServers]>,
struct NetworkServersView_Previews: PreviewProvider {
static var previews: some View {
NetworkAndServers()
+ .environmentObject(SaveableSettings())
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NewServerView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NewServerView.swift
index 0a3c82b4dd..8d43159f8c 100644
--- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NewServerView.swift
+++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/NewServerView.swift
@@ -151,10 +151,12 @@ func addServer(
}
}
-#Preview {
- NewServerView(
- userServers: Binding.constant([UserOperatorServers.sampleDataNilOperator]),
- serverErrors: Binding.constant([]),
- serverWarnings: Binding.constant([])
- )
+struct NewServerView_Previews: PreviewProvider {
+ static var previews: some View {
+ NewServerView(
+ userServers: Binding.constant([UserOperatorServers.sampleDataNilOperator]),
+ serverErrors: Binding.constant([]),
+ serverWarnings: Binding.constant([])
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift
index 4e2f1992d6..55ccc81850 100644
--- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift
+++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/OperatorView.swift
@@ -623,13 +623,15 @@ func conditionsLinkButton() -> some View {
}
}
-#Preview {
- OperatorView(
- currUserServers: Binding.constant([UserOperatorServers.sampleData1, UserOperatorServers.sampleDataNilOperator]),
- userServers: Binding.constant([UserOperatorServers.sampleData1, UserOperatorServers.sampleDataNilOperator]),
- serverErrors: Binding.constant([]),
- serverWarnings: Binding.constant([]),
- operatorIndex: 1,
- useOperator: ServerOperator.sampleData1.enabled
- )
+struct OperatorView_Previews: PreviewProvider {
+ static var previews: some View {
+ OperatorView(
+ currUserServers: Binding.constant([UserOperatorServers.sampleData1, UserOperatorServers.sampleDataNilOperator]),
+ userServers: Binding.constant([UserOperatorServers.sampleData1, UserOperatorServers.sampleDataNilOperator]),
+ serverErrors: Binding.constant([]),
+ serverWarnings: Binding.constant([]),
+ operatorIndex: 1,
+ useOperator: ServerOperator.sampleData1.enabled
+ )
+ }
}
diff --git a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift
index a92491edef..0e03aa4cd7 100644
--- a/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift
+++ b/apps/ios/Shared/Views/UserSettings/NetworkAndServers/ProtocolServersView.swift
@@ -451,7 +451,7 @@ struct YourServersView_Previews: PreviewProvider {
userServers: Binding.constant([UserOperatorServers.sampleDataNilOperator]),
serverErrors: Binding.constant([]),
serverWarnings: Binding.constant([]),
- operatorIndex: 1
+ operatorIndex: 0
)
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/SettingsView.swift b/apps/ios/Shared/Views/UserSettings/SettingsView.swift
index ae317cd864..68114b8047 100644
--- a/apps/ios/Shared/Views/UserSettings/SettingsView.swift
+++ b/apps/ios/Shared/Views/UserSettings/SettingsView.swift
@@ -13,6 +13,8 @@ import SimpleXChat
let simplexTeamURL = URL(string: "simplex:/a#lrdvu2d8A1GumSmoKb2krQmtKhWXq-tyGpHuM7aMwsw?h=smp6.simplex.im")!
+let simplexNewsURL = URL(string: "simplex:/c#grcfG3ulVI4Sh6ow33qBsmSk7uEy3gRSl2KkJ5ER6tA?h=smp18.simplex.im")!
+
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
let appBuild = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String
@@ -47,6 +49,7 @@ let DEFAULT_SHOULD_IMPORT_APP_SETTINGS = "shouldImportAppSettings"
let DEFAULT_DEVELOPER_TOOLS = "developerTools"
let DEFAULT_ENCRYPTION_STARTED = "encryptionStarted"
let DEFAULT_ENCRYPTION_STARTED_AT = "encryptionStartedAt"
+let DEFAULT_SHOULD_DELETE_DATABASE_BACKUPS = "shouldDeleteDatabaseBackups"
let DEFAULT_ACCENT_COLOR_RED = "accentColorRed" // deprecated, only used for migration
let DEFAULT_ACCENT_COLOR_GREEN = "accentColorGreen" // deprecated, only used for migration
let DEFAULT_ACCENT_COLOR_BLUE = "accentColorBlue" // deprecated, only used for migration
@@ -54,8 +57,13 @@ let DEFAULT_USER_INTERFACE_STYLE = "userInterfaceStyle" // deprecated, only used
let DEFAULT_PROFILE_IMAGE_CORNER_RADIUS = "profileImageCornerRadius"
let DEFAULT_CHAT_ITEM_ROUNDNESS = "chatItemRoundness"
let DEFAULT_CHAT_ITEM_TAIL = "chatItemTail"
+let DEFAULT_CHAT_LAYOUT = "chatLayout"
let DEFAULT_ONE_HAND_UI_CARD_SHOWN = "oneHandUICardShown"
let DEFAULT_ADDRESS_CREATION_CARD_SHOWN = "addressCreationCardShown"
+let DEFAULT_SUPPORTER_BANNER_SHOWN = "supporterBannerShown"
+let DEFAULT_SUPPORTER_BANNER_TAPPED = "supporterBannerTapped"
+let DEFAULT_GET_STAKE_BANNER_TAPPED = "getStakeBannerTapped"
+let DEFAULT_GET_STAKE_BANNER_DISMISSED = "getStakeBannerDismissed"
let DEFAULT_TOOLBAR_MATERIAL = "toolbarMaterial"
let DEFAULT_CONNECT_VIA_LINK_TAB = "connectViaLinkTab"
let DEFAULT_LIVE_MESSAGE_ALERT_SHOWN = "liveMessageAlertShown"
@@ -77,6 +85,7 @@ let DEFAULT_SHOW_DELETE_CONVERSATION_NOTICE = "showDeleteConversationNotice"
let DEFAULT_SHOW_DELETE_CONTACT_NOTICE = "showDeleteContactNotice"
let DEFAULT_SHOW_SENT_VIA_RPOXY = "showSentViaProxy"
let DEFAULT_SHOW_SUBSCRIPTION_PERCENTAGE = "showSubscriptionPercentage"
+let DEFAULT_MARKDOWN_FILE_TEXT_VIEW = "markdownFileTextView"
let DEFAULT_CURRENT_THEME = "currentTheme"
let DEFAULT_SYSTEM_DARK_THEME = "systemDarkTheme"
@@ -115,8 +124,13 @@ let appDefaults: [String: Any] = [
DEFAULT_PROFILE_IMAGE_CORNER_RADIUS: defaultProfileImageCorner,
DEFAULT_CHAT_ITEM_ROUNDNESS: defaultChatItemRoundness,
DEFAULT_CHAT_ITEM_TAIL: true,
+ DEFAULT_CHAT_LAYOUT: ChatLayout.classic.rawValue,
DEFAULT_ONE_HAND_UI_CARD_SHOWN: false,
DEFAULT_ADDRESS_CREATION_CARD_SHOWN: false,
+ DEFAULT_SUPPORTER_BANNER_SHOWN: false,
+ DEFAULT_SUPPORTER_BANNER_TAPPED: false,
+ DEFAULT_GET_STAKE_BANNER_TAPPED: false,
+ DEFAULT_GET_STAKE_BANNER_DISMISSED: false,
DEFAULT_TOOLBAR_MATERIAL: ToolbarMaterial.defaultMaterial,
DEFAULT_CONNECT_VIA_LINK_TAB: ConnectViaLinkTab.scan.rawValue,
DEFAULT_LIVE_MESSAGE_ALERT_SHOWN: false,
@@ -134,6 +148,7 @@ let appDefaults: [String: Any] = [
DEFAULT_SHOW_DELETE_CONTACT_NOTICE: true,
DEFAULT_SHOW_SENT_VIA_RPOXY: false,
DEFAULT_SHOW_SUBSCRIPTION_PERCENTAGE: false,
+ DEFAULT_MARKDOWN_FILE_TEXT_VIEW: false,
ANDROID_DEFAULT_CALL_ON_LOCK_SCREEN: AppSettingsLockScreenCalls.show.rawValue,
DEFAULT_THEME_OVERRIDES: "{}",
@@ -148,6 +163,10 @@ let hintDefaults = [
DEFAULT_LA_NOTICE_SHOWN,
DEFAULT_ONE_HAND_UI_CARD_SHOWN,
DEFAULT_ADDRESS_CREATION_CARD_SHOWN,
+ DEFAULT_SUPPORTER_BANNER_SHOWN,
+ DEFAULT_SUPPORTER_BANNER_TAPPED,
+ DEFAULT_GET_STAKE_BANNER_TAPPED,
+ DEFAULT_GET_STAKE_BANNER_DISMISSED,
DEFAULT_LIVE_MESSAGE_ALERT_SHOWN,
DEFAULT_SIGN_MESSAGE_ALERT_SHOWN,
DEFAULT_SHOW_HIDDEN_PROFILES_NOTICE,
@@ -193,8 +212,12 @@ let encryptionStartedDefault = BoolDefault(defaults: UserDefaults.standard, forK
let encryptionStartedAtDefault = DateDefault(defaults: UserDefaults.standard, forKey: DEFAULT_ENCRYPTION_STARTED_AT)
+let shouldDeleteDatabaseBackupsDefault = BoolDefault(defaults: UserDefaults.standard, forKey: DEFAULT_SHOULD_DELETE_DATABASE_BACKUPS)
+
let connectViaLinkTabDefault = EnumDefault(defaults: UserDefaults.standard, forKey: DEFAULT_CONNECT_VIA_LINK_TAB, withDefault: .scan)
+let chatLayoutDefault = EnumDefault(defaults: UserDefaults.standard, forKey: DEFAULT_CHAT_LAYOUT, withDefault: .classic)
+
let privacySimplexLinkModeDefault = EnumDefault(defaults: UserDefaults.standard, forKey: DEFAULT_PRIVACY_SIMPLEX_LINK_MODE, withDefault: .description)
let privacyLocalAuthModeDefault = EnumDefault(defaults: UserDefaults.standard, forKey: DEFAULT_LA_MODE, withDefault: .system)
@@ -284,7 +307,9 @@ struct SettingsView: View {
@EnvironmentObject var chatModel: ChatModel
@EnvironmentObject var sceneDelegate: SceneDelegate
@EnvironmentObject var theme: AppTheme
+ @ObservedObject private var badgeModel = BadgeModel.shared
@State private var showProgress: Bool = false
+ var versionText: String? = appVersion
var body: some View {
ZStack {
@@ -341,6 +366,26 @@ struct SettingsView: View {
}
}
+ let badgeRow = badgeRowTexts()
+ Section {
+ NavigationLink {
+ BadgesView()
+ .modifier(ThemedBackground())
+ } label: {
+ let badgeType = chatModel.currentUser?.profile.localBadge?.badge.badgeType ?? .supporter
+ ZStack(alignment: .leading) {
+ Image(badgeImageName(badgeType))
+ .resizable()
+ .scaledToFit()
+ .frame(width: 24, height: 24)
+ Text(badgeRow.label).padding(.leading, indent)
+ }
+ }
+ } footer: {
+ Text(badgeRow.benefits)
+ .foregroundColor(theme.colors.secondary)
+ }
+
Section(header: Text("Advanced settings").foregroundColor(theme.colors.secondary)) {
NavigationLink {
NetworkAndServers()
@@ -356,10 +401,8 @@ struct SettingsView: View {
.navigationTitle("Notifications")
.modifier(ThemedBackground(grouped: true))
} label: {
- HStack {
- notificationsIcon()
- Text("Notifications")
- }
+ let (icon, color) = notificationsIcon()
+ settingsRow(icon, color: color) { Text("Notifications") }
}
.disabled(chatModel.chatRunning != true)
@@ -375,16 +418,16 @@ struct SettingsView: View {
NavigationLink {
VersionView()
.navigationBarTitle("App version")
- .modifier(ThemedBackground())
+ .modifier(ThemedBackground(grouped: true))
} label: {
- Text(verbatim: "v\(appVersion ?? "?")")
+ Text(verbatim: "v\(versionText ?? "?")")
}
}
if isInUS {
- Section(header: Text("You can now invest in SimpleX Chat").foregroundColor(theme.colors.secondary)) {
+ Section(header: Text("Own a part of SimpleX Chat").foregroundColor(theme.colors.secondary)) {
NavigationLink {
- GetStakeView(fromSettings: true)
+ GetStakeView(fromSettings: true, showFirstImage: true)
.navigationBarTitle("", displayMode: .inline)
} label: {
settingsRow("dollarsign.circle", color: theme.colors.secondary) { Text("Crowdfunding on Wefunder") }
@@ -400,6 +443,14 @@ struct SettingsView: View {
}
}
+ private func badgeRowTexts() -> (label: LocalizedStringKey, benefits: LocalizedStringKey) {
+ switch currentShownBadge()?.badgeType {
+ case nil: return ("Support SimpleX", "Larger files available for longer.")
+ case .legend?: return ("Your legend badge", "Files up to 5 GB, stored for 21 days.")
+ default: return ("Your badge", "Files up to 2 GB, stored for 7 days.")
+ }
+ }
+
@ViewBuilder
private var helpAndSupportView: some View {
List {
@@ -434,6 +485,15 @@ struct SettingsView: View {
}
Section(header: Text("Contact").foregroundColor(theme.colors.secondary)) {
+ settingsRow("antenna.radiowaves.left.and.right", color: theme.colors.secondary) {
+ Button("Follow SimpleX Network News") {
+ dismiss()
+ DispatchQueue.main.async {
+ ChatModel.shared.appOpenUrl = simplexNewsURL
+ }
+ }
+ }
+ .disabled(chatModel.chatRunning != true)
settingsRow("number", color: theme.colors.secondary) {
Button("Send questions and ideas") {
dismiss()
@@ -507,7 +567,7 @@ struct SettingsView: View {
case error(LocalizedStringKey, String)
}
- private func notificationsIcon() -> some View {
+ private func notificationsIcon() -> (String, Color) {
let icon: String
let color: Color
switch (chatModel.tokenStatus) {
@@ -537,9 +597,7 @@ struct SettingsView: View {
icon = "bolt"
color = theme.colors.secondary
}
- return Image(systemName: icon)
- .padding(.trailing, 9)
- .foregroundColor(color)
+ return (icon, color)
}
}
@@ -580,7 +638,7 @@ struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
let chatModel = ChatModel()
chatModel.currentUser = User.sampleData
- return SettingsView()
+ return SettingsView(versionText: "7.1")
.environmentObject(chatModel)
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/StorageView.swift b/apps/ios/Shared/Views/UserSettings/StorageView.swift
index 094c1cb3d6..9d88e02be2 100644
--- a/apps/ios/Shared/Views/UserSettings/StorageView.swift
+++ b/apps/ios/Shared/Views/UserSettings/StorageView.swift
@@ -10,33 +10,66 @@ import SwiftUI
import SimpleXChat
struct StorageView: View {
+ @EnvironmentObject var m: ChatModel
+ @EnvironmentObject var theme: AppTheme
@State var appGroupFiles: [String: Int64] = [:]
@State var documentsFiles: [String: Int64] = [:]
var body: some View {
ScrollView {
VStack(alignment: .leading) {
- directoryView("App group:", appGroupFiles)
+ directoryView("App group:", getGroupContainerDirectory(), appGroupFiles)
if !documentsFiles.isEmpty {
- directoryView("Documents:", documentsFiles)
+ directoryView("Documents:", getDocumentsDirectory(), documentsFiles)
}
}
}
.padding()
- .onAppear {
- appGroupFiles = traverseFiles(in: getGroupContainerDirectory())
- documentsFiles = traverseFiles(in: getDocumentsDirectory())
- }
+ .onAppear(perform: loadFiles)
+ }
+
+ private func loadFiles() {
+ appGroupFiles = traverseFiles(in: getGroupContainerDirectory())
+ documentsFiles = traverseFiles(in: getDocumentsDirectory())
}
@ViewBuilder
- private func directoryView(_ name: LocalizedStringKey, _ contents: [String: Int64]) -> some View {
+ private func directoryView(_ name: LocalizedStringKey, _ dir: URL, _ contents: [String: Int64]) -> some View {
Text(name).font(.headline)
ForEach(Array(contents), id: \.key) { (key, value) in
- Text(key).bold() + Text(verbatim: " ") + Text((ByteCountFormatter.string(fromByteCount: value, countStyle: .binary)))
+ let sizeText = Text(key).bold() + Text(verbatim: " ") + Text((ByteCountFormatter.string(fromByteCount: value, countStyle: .binary)))
+ if dir.appendingPathComponent(key).path == getTempFilesDirectory().path {
+ let stopped = m.chatRunning == false
+ HStack {
+ sizeText
+ Button("Delete temp data", role: .destructive, action: confirmDeleteTempFiles)
+ .disabled(!stopped)
+ }
+ if !stopped {
+ Text("Stop chat in Settings → Chat data → Database passphrase & export to delete temp data.")
+ .font(.footnote)
+ .foregroundColor(theme.colors.secondary)
+ }
+ } else {
+ sizeText
+ }
}
}
+ private func confirmDeleteTempFiles() {
+ showAlert(
+ NSLocalizedString("Delete temp data?", comment: "alert title"),
+ message: NSLocalizedString("Files being sent or received will never complete. Videos in unsent drafts will be sent without the file.", comment: "alert message"),
+ actions: {[
+ UIAlertAction(title: NSLocalizedString("Delete", comment: "alert action"), style: .destructive) { _ in
+ deleteTempFiles()
+ loadFiles()
+ },
+ cancelAlertAction
+ ]}
+ )
+ }
+
private func traverseFiles(in dir: URL) -> [String: Int64] {
var res: [String: Int64] = [:]
let fm = FileManager.default
diff --git a/apps/ios/Shared/Views/UserSettings/UserAddressView.swift b/apps/ios/Shared/Views/UserSettings/UserAddressView.swift
index 9711f3d6f8..d6c59711a9 100644
--- a/apps/ios/Shared/Views/UserSettings/UserAddressView.swift
+++ b/apps/ios/Shared/Views/UserSettings/UserAddressView.swift
@@ -139,7 +139,7 @@ struct UserAddressView: View {
title: Text("Share address with SimpleX contacts?"),
message: Text("Add address to your profile, so that your SimpleX contacts can share it with other people. Profile update will be sent to your SimpleX contacts."),
primaryButton: .default(Text("Share")) {
- setProfileAddress($progressIndicator, true)
+ setProfileAddress($progressIndicator, true) { shareViaProfile = false }
shareViaProfile = true
}, secondaryButton: .cancel()
)
@@ -318,7 +318,7 @@ struct UserAddressView: View {
alert = .shareOnCreate
progressIndicator = false
} else {
- setProfileAddress($progressIndicator, true)
+ setProfileAddress($progressIndicator, true) { shareViaProfile = false }
shareViaProfile = true
}
} else {
@@ -582,6 +582,7 @@ struct AddressSettingsState: Equatable {
var autoAccept = false
var autoAcceptIncognito = false
var autoReply = ""
+ var chatLayout: ChatLayout?
init() {}
@@ -590,18 +591,20 @@ struct AddressSettingsState: Equatable {
self.autoAccept = settings.autoAccept != nil
self.autoAcceptIncognito = settings.autoAccept?.acceptIncognito == true
self.autoReply = settings.autoReply?.text ?? ""
+ self.chatLayout = settings.chatLayout
}
var addressSettings: AddressSettings {
AddressSettings(
businessAddress: self.businessAddress,
autoAccept: self.autoAccept ? AutoAccept(acceptIncognito: self.autoAcceptIncognito) : nil,
- autoReply: self.autoReply.isEmpty ? nil : MsgContent.text(self.autoReply)
+ autoReply: self.autoReply.isEmpty ? nil : MsgContent.text(self.autoReply),
+ chatLayout: self.chatLayout
)
}
}
-private func setProfileAddress(_ progressIndicator: Binding, _ on: Bool) {
+private func setProfileAddress(_ progressIndicator: Binding, _ on: Bool, revert: @escaping () -> Void) {
progressIndicator.wrappedValue = true
Task {
do {
@@ -613,7 +616,11 @@ private func setProfileAddress(_ progressIndicator: Binding, _ on: Bool) {
await MainActor.run { progressIndicator.wrappedValue = false }
} catch let error {
logger.error("apiSetProfileAddress: \(responseError(error))")
- await MainActor.run { progressIndicator.wrappedValue = false }
+ await MainActor.run {
+ progressIndicator.wrappedValue = false
+ revert()
+ showErrorAlert(error, NSLocalizedString("Error saving profile", comment: "alert title"))
+ }
}
}
}
@@ -709,7 +716,10 @@ struct UserAddressSettingsView: View {
title: NSLocalizedString("Share", comment: "alert action"),
style: .default,
handler: { _ in
- setProfileAddress($progressIndicator, on)
+ setProfileAddress($progressIndicator, on) {
+ ignoreShareViaProfileChange = true
+ shareViaProfile = !on
+ }
}
)
]}
@@ -731,7 +741,10 @@ struct UserAddressSettingsView: View {
title: NSLocalizedString("Stop sharing", comment: "alert action"),
style: .default,
handler: { _ in
- setProfileAddress($progressIndicator, on)
+ setProfileAddress($progressIndicator, on) {
+ ignoreShareViaProfileChange = true
+ shareViaProfile = !on
+ }
}
)
]}
@@ -1014,7 +1027,7 @@ struct SetSimplexDomainView: View {
struct UserAddressView_Previews: PreviewProvider {
static var previews: some View {
let chatModel = ChatModel()
- chatModel.userAddress = UserContactLink(CreatedConnLink(connFullLink: "https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2FPQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo%3D%40smp6.simplex.im%2FK1rslx-m5bpXVIdMZg9NLUZ_8JBm8xTt%23MCowBQYDK2VuAyEALDeVe-sG8mRY22LsXlPgiwTNs9dbiLrNuA7f3ZMAJ2w%3D", connShortLink: nil))
+ chatModel.userAddress = UserContactLink(CreatedConnLink(connFullLink: "https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2FPQUV2eL0t7OStZOoAsPEV2QYWt4-xilbakvGUGOItUo%3D%40smp6.simplex.im%2FK1rslx-m5bpXVIdMZg9NLUZ_8JBm8xTt%23MCowBQYDK2VuAyEALDeVe-sG8mRY22LsXlPgiwTNs9dbiLrNuA7f3ZMAJ2w%3D", connShortLink: "https://smp6.simplex.im/a#lrdvu2d8A1GumSmoKb2krQmtKhWXq-tyGpHuM7aMwsw"))
return Group {
UserAddressView()
diff --git a/apps/ios/Shared/Views/UserSettings/UserProfile.swift b/apps/ios/Shared/Views/UserSettings/UserProfile.swift
index a2a62b557c..64c877f9cd 100644
--- a/apps/ios/Shared/Views/UserSettings/UserProfile.swift
+++ b/apps/ios/Shared/Views/UserSettings/UserProfile.swift
@@ -29,14 +29,14 @@ struct UserProfile: View {
var body: some View {
List {
- EditProfileImage(profileImage: $profile.image, iconName: "person.crop.circle.fill", showChooseSource: $showChooseSource)
+ EditProfileImage(profileImage: $profile.image, icon: Image(systemName: "person.crop.circle.fill"), showChooseSource: $showChooseSource)
.padding(.top)
Section {
HStack {
TextField("Enter your name…", text: $profile.displayName)
.focused($focusDisplayName)
- if !validDisplayName(profile.displayName) {
+ if !validNewProfileName {
Button {
alert = .invalidNameError(validName: mkValidName(profile.displayName))
} label: {
@@ -147,10 +147,15 @@ struct UserProfile: View {
(chatModel.currentUser?.profile.description ?? "") != description.trimmingCharacters(in: .whitespacesAndNewlines)
) &&
profile.displayName.trimmingCharacters(in: .whitespaces) != "" &&
- validDisplayName(profile.displayName) &&
+ validNewProfileName &&
bioFitsLimit()
}
+ private var validNewProfileName: Bool {
+ profile.displayName == chatModel.currentUser?.profile.displayName
+ || validDisplayName(profile.displayName)
+ }
+
private func saveProfile() {
focusDisplayName = false
Task {
@@ -216,7 +221,7 @@ struct EditProfileImage: View {
@EnvironmentObject var theme: AppTheme
@AppStorage(DEFAULT_PROFILE_IMAGE_CORNER_RADIUS) private var radius = defaultProfileImageCorner
@Binding var profileImage: String?
- var iconName: String
+ var icon: Image
@Binding var showChooseSource: Bool
var body: some View {
@@ -232,7 +237,7 @@ struct EditProfileImage: View {
}
} else {
ZStack(alignment: .center) {
- ProfileImage(imageStr: profileImage, iconName: iconName, size: 160)
+ ProfileImage(imageStr: profileImage, icon: icon, size: 160)
editImageButton { showChooseSource = true }
}
}
diff --git a/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift b/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift
index 3f3adbcb2d..890c672bcd 100644
--- a/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift
+++ b/apps/ios/Shared/Views/UserSettings/UserProfilesView.swift
@@ -346,7 +346,7 @@ struct UserProfilesView: View {
HStack {
ProfileImage(imageStr: user.image, size: 38)
.padding(.trailing, 12)
- Text(user.chatViewName)
+ NameWithBadge(Text(user.chatViewName), user.profile.localBadge)
Spacer()
if user.activeUser {
Image(systemName: "checkmark").foregroundColor(theme.colors.onBackground)
diff --git a/apps/ios/Shared/Views/UserSettings/VersionView.swift b/apps/ios/Shared/Views/UserSettings/VersionView.swift
index e30c11699e..c894694cf3 100644
--- a/apps/ios/Shared/Views/UserSettings/VersionView.swift
+++ b/apps/ios/Shared/Views/UserSettings/VersionView.swift
@@ -10,9 +10,26 @@ import SwiftUI
import SimpleXChat
struct VersionView: View {
- @EnvironmentObject var theme: AppTheme
@State var versionInfo: CoreVersionInfo?
+ var body: some View {
+ VersionLayout(appVersion: appVersion, appBuild: appBuild, versionInfo: versionInfo)
+ .onAppear {
+ do {
+ versionInfo = try apiGetVersion()
+ } catch let error {
+ logger.error("apiGetVersion error: \(responseError(error))")
+ }
+ }
+ }
+}
+
+struct VersionLayout: View {
+ @EnvironmentObject var theme: AppTheme
+ let appVersion: String?
+ let appBuild: String?
+ let versionInfo: CoreVersionInfo?
+
var body: some View {
List {
Section {
@@ -37,18 +54,11 @@ struct VersionView: View {
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
- .onAppear {
- do {
- versionInfo = try apiGetVersion()
- } catch let error {
- logger.error("apiGetVersion error: \(responseError(error))")
- }
- }
}
}
struct VersionView_Previews: PreviewProvider {
static var previews: some View {
- VersionView()
+ VersionLayout(appVersion: "7.1", appBuild: "363", versionInfo: CoreVersionInfo(version: "7.1.0.14", simplexmqVersion: "7.1.0.14", simplexmqCommit: "c0c416daf052eb0215ae432ae665522a7c96c0a6"))
}
}
diff --git a/apps/ios/SimpleX Localizations/ar.xcloc/Localized Contents/ar.xliff b/apps/ios/SimpleX Localizations/ar.xcloc/Localized Contents/ar.xliff
index cddb17337c..85a953cee7 100644
--- a/apps/ios/SimpleX Localizations/ar.xcloc/Localized Contents/ar.xliff
+++ b/apps/ios/SimpleX Localizations/ar.xcloc/Localized Contents/ar.xliff
@@ -350,10 +350,6 @@
قبول التخفي
No comment provided by engineer.
-
- Accept requests
- No comment provided by engineer.
-
Add preset servers
إضافة خوادم محددة مسبقا
@@ -404,10 +400,6 @@
سيتم حذف جميع الرسائل - لا يمكن التراجع عن هذا! سيتم حذف الرسائل فقط من أجلك.
No comment provided by engineer.
-
- All your contacts will remain connected
- No comment provided by engineer.
-
Allow
سماح
@@ -418,10 +410,6 @@
السماح بالرسائل المختفية فقط إذا سمحت لك جهة الاتصال بذلك.
No comment provided by engineer.
-
- Allow irreversible message deletion only if your contact allows it to you.
- No comment provided by engineer.
-
Allow sending direct messages to members.
السماح بإرسال رسائل مباشرة إلى الأعضاء.
@@ -432,10 +420,6 @@
السماح بإرسال الرسائل التي تختفي.
No comment provided by engineer.
-
- Allow to irreversibly delete sent messages.
- No comment provided by engineer.
-
Allow to send voice messages.
السماح بإرسال رسائل صوتية.
@@ -451,10 +435,6 @@
السماح بالرسائل الصوتية؟
No comment provided by engineer.
-
- Allow your contacts to irreversibly delete sent messages.
- No comment provided by engineer.
-
Allow your contacts to send disappearing messages.
السماح لجهات اتصالك بإرسال رسائل تختفي.
@@ -530,19 +510,11 @@
قبول تلقائي للصور
No comment provided by engineer.
-
- Automatically
- No comment provided by engineer.
-
Back
رجوع
No comment provided by engineer.
-
- Both you and your contact can irreversibly delete sent messages.
- No comment provided by engineer.
-
Both you and your contact can send disappearing messages.
يمكنك أنت وجهة اتصالك إرسال رسائل تختفي.
@@ -555,7 +527,7 @@
By chat profile (default) or [by connection](https://simplex.chat/blog/20230204-simplex-chat-v4-5-user-chat-profiles.html#transport-isolation) (BETA).
- حسب ملف تعريف الدردشة (افتراضي) أو [حسب الاتصال] (https://simplex.chat/blog/20230204-simplex-chat-v4-5-user-chat-profiles.html#transport-isolation) (BETA).
+ حسب ملف تعريف الدردشة (افتراضي) أو [حسب الاتصال](https://simplex.chat/blog/20230204-simplex-chat-v4-5-user-chat-profiles.html#transport-isolation) (BETA).
No comment provided by engineer.
@@ -623,10 +595,6 @@
تغيير الدور
No comment provided by engineer.
-
- Chat archive
- No comment provided by engineer.
-
Chat console
وحدة تحكم الدردشة
@@ -702,10 +670,6 @@
امسح التحقُّق
No comment provided by engineer.
-
- Colors
- No comment provided by engineer.
-
Compare security codes with your contacts.
قارن رموز الأمان مع جهات اتصالك.
@@ -731,31 +695,11 @@
اتصل
server test step
-
- Connect via contact link?
- No comment provided by engineer.
-
-
- Connect via group link?
- No comment provided by engineer.
-
Connect via link
تواصل عبر الرابط
No comment provided by engineer.
-
- Connect via link / QR code
- No comment provided by engineer.
-
-
- Connect via one-time link?
- No comment provided by engineer.
-
-
- Connect via relay
- No comment provided by engineer.
-
Connecting to server…
جارِ الاتصال بالخادم…
@@ -781,10 +725,6 @@
خطأ في الإتصال (المصادقة)
No comment provided by engineer.
-
- Connection request
- No comment provided by engineer.
-
Connection request sent!
أرسلت طلب الاتصال!
@@ -805,10 +745,6 @@
جهة الاتصال موجودة بالفعل
No comment provided by engineer.
-
- Contact and all messages will be deleted - this cannot be undone!
- No comment provided by engineer.
-
Contact hidden:
جهة الاتصال مخفية:
@@ -819,10 +755,6 @@
تم الاتصال
notification
-
- Contact is not connected yet!
- No comment provided by engineer.
-
Contact name
اسم جهة الاتصال
@@ -833,10 +765,6 @@
تفضيلات جهة الاتصال
No comment provided by engineer.
-
- Contact requests
- No comment provided by engineer.
-
Contacts can mark messages for deletion; you will be able to view them.
يمكن لجهات الاتصال تحديد الرسائل لحذفها؛ ستتمكن من مشاهدتها.
@@ -847,10 +775,6 @@
نسخ
chat item action
-
- Core built at: %@
- No comment provided by engineer.
-
Core version: v%@
الإصدار الأساسي: v%@
@@ -861,10 +785,6 @@
إنشاء
No comment provided by engineer.
-
- Create address
- No comment provided by engineer.
-
Create group link
إنشاء رابط المجموعة
@@ -875,10 +795,6 @@
إنشاء رابط
No comment provided by engineer.
-
- Create one-time invitation link
- No comment provided by engineer.
-
Create queue
إنشاء قائمة انتظار
@@ -894,10 +810,6 @@
أنشئ ملف تعريفك
No comment provided by engineer.
-
- Created on %@
- No comment provided by engineer.
-
Current passphrase…
عبارة المرور الحالية…
@@ -1001,10 +913,6 @@
حذف
chat item action
-
- Delete Contact
- No comment provided by engineer.
-
Delete address
حذف العنوان
@@ -1025,14 +933,6 @@
حذف جميع الملفات
No comment provided by engineer.
-
- Delete archive
- No comment provided by engineer.
-
-
- Delete chat archive?
- No comment provided by engineer.
-
Delete chat profile?
حذف ملف تعريف الدردشة؟
@@ -1128,10 +1028,6 @@
حذف قاعدة البيانات القديمة؟
No comment provided by engineer.
-
- Delete pending connection
- No comment provided by engineer.
-
Delete pending connection?
حذف الاتصال قيد الانتظار؟
@@ -1217,14 +1113,6 @@
قطع الاتصال
server test step
-
- Display name
- No comment provided by engineer.
-
-
- Display name:
- No comment provided by engineer.
-
Do NOT use SimpleX for emergency calls.
لا تستخدم SimpleX لإجراء مكالمات الطوارئ.
@@ -1350,10 +1238,6 @@
خطأ في قبول طلب الاتصال
No comment provided by engineer.
-
- Error accessing database file
- No comment provided by engineer.
-
Error adding member(s)
خطأ في إضافة عضو (أعضاء)
@@ -1384,1181 +1268,11 @@
خطأ في إنشاء المجموعة
No comment provided by engineer.
-
- Error creating group link
- No comment provided by engineer.
-
-
- Error creating profile!
- No comment provided by engineer.
-
-
- Error deleting chat database
- No comment provided by engineer.
-
-
- Error deleting chat!
- No comment provided by engineer.
-
-
- Error deleting connection
- No comment provided by engineer.
-
-
- Error deleting contact
- No comment provided by engineer.
-
-
- Error deleting database
- No comment provided by engineer.
-
-
- Error deleting old database
- No comment provided by engineer.
-
-
- Error deleting token
- No comment provided by engineer.
-
-
- Error deleting user profile
- No comment provided by engineer.
-
-
- Error enabling notifications
- No comment provided by engineer.
-
-
- Error encrypting database
- No comment provided by engineer.
-
-
- Error exporting chat database
- No comment provided by engineer.
-
-
- Error importing chat database
- No comment provided by engineer.
-
-
- Error joining group
- No comment provided by engineer.
-
-
- Error receiving file
- No comment provided by engineer.
-
-
- Error removing member
- No comment provided by engineer.
-
-
- Error saving ICE servers
- No comment provided by engineer.
-
-
- Error saving SMP servers
- No comment provided by engineer.
-
-
- Error saving group profile
- No comment provided by engineer.
-
-
- Error saving passphrase to keychain
- No comment provided by engineer.
-
-
- Error sending message
- No comment provided by engineer.
-
-
- Error starting chat
- No comment provided by engineer.
-
-
- Error stopping chat
- No comment provided by engineer.
-
-
- Error switching profile!
- No comment provided by engineer.
-
-
- Error updating message
- No comment provided by engineer.
-
-
- Error updating settings
- No comment provided by engineer.
-
-
- Error: %@
- No comment provided by engineer.
-
-
- Error: URL is invalid
- No comment provided by engineer.
-
-
- Error: no database file
- No comment provided by engineer.
-
-
- Exit without saving
- No comment provided by engineer.
-
-
- Export database
- No comment provided by engineer.
-
-
- Export error:
- No comment provided by engineer.
-
-
- Exported database archive.
- No comment provided by engineer.
-
-
- Exporting database archive...
- No comment provided by engineer.
-
-
- Failed to remove passphrase
- No comment provided by engineer.
-
-
- File will be received when your contact is online, please wait or check later!
- No comment provided by engineer.
-
-
- File: %@
- No comment provided by engineer.
-
-
- Files & media
- No comment provided by engineer.
-
-
- For console
- No comment provided by engineer.
-
-
- French interface
- No comment provided by engineer.
-
-
- Full link
- No comment provided by engineer.
-
-
- Full name (optional)
- No comment provided by engineer.
-
-
- Full name:
- No comment provided by engineer.
-
-
- GIFs and stickers
- No comment provided by engineer.
-
-
- Group
- No comment provided by engineer.
-
-
- Group display name
- No comment provided by engineer.
-
-
- Group full name (optional)
- No comment provided by engineer.
-
-
- Group image
- No comment provided by engineer.
-
-
- Group invitation
- No comment provided by engineer.
-
-
- Group invitation expired
- No comment provided by engineer.
-
-
- Group invitation is no longer valid, it was removed by sender.
- No comment provided by engineer.
-
-
- Group link
- No comment provided by engineer.
-
-
- Group links
- No comment provided by engineer.
-
-
- Group members can irreversibly delete sent messages.
- No comment provided by engineer.
-
-
- Members can send direct messages.
- No comment provided by engineer.
-
-
- Members can send disappearing messages.
- No comment provided by engineer.
-
-
- Members can send voice messages.
- No comment provided by engineer.
-
-
- Group message:
- notification
-
-
- Group preferences
- No comment provided by engineer.
-
-
- Group profile
- No comment provided by engineer.
-
-
- Group profile is stored on members' devices, not on the servers.
- No comment provided by engineer.
-
-
- Group will be deleted for all members - this cannot be undone!
- No comment provided by engineer.
-
-
- Group will be deleted for you - this cannot be undone!
- No comment provided by engineer.
-
-
- Help
- No comment provided by engineer.
-
-
- Hidden
- No comment provided by engineer.
-
-
- Hide
- chat item action
-
-
- Hide app screen in the recent apps.
- No comment provided by engineer.
-
-
- How SimpleX works
- No comment provided by engineer.
-
-
- How it works
- No comment provided by engineer.
-
-
- How to
- No comment provided by engineer.
-
-
- How to use it
- No comment provided by engineer.
-
-
- How to use your servers
- No comment provided by engineer.
-
-
- ICE servers (one per line)
- No comment provided by engineer.
-
-
- If the video fails to connect, flip the camera to resolve it.
- No comment provided by engineer.
-
-
- If you can't meet in person, **show QR code in the video call**, or share the link.
- No comment provided by engineer.
-
-
- If you cannot meet in person, you can **scan QR code in the video call**, or your contact can share an invitation link.
- No comment provided by engineer.
-
-
- If you need to use the chat now tap **Do it later** below (you will be offered to migrate the database when you restart the app).
- No comment provided by engineer.
-
-
- Ignore
- No comment provided by engineer.
-
-
- Image will be received when your contact is online, please wait or check later!
- No comment provided by engineer.
-
-
- Immune to spam
- No comment provided by engineer.
-
-
- Import
- No comment provided by engineer.
-
-
- Import chat database?
- No comment provided by engineer.
-
-
- Import database
- No comment provided by engineer.
-
-
- Improved privacy and security
- No comment provided by engineer.
-
-
- Improved server configuration
- No comment provided by engineer.
-
-
- Incognito
- No comment provided by engineer.
-
-
- Incognito mode
- No comment provided by engineer.
-
-
- Incognito mode is not supported here - your main profile will be sent to group members
- No comment provided by engineer.
-
-
- Incognito mode protects the privacy of your main profile name and image — for each new contact a new random profile is created.
- No comment provided by engineer.
-
-
- Incoming audio call
- notification
-
-
- Incoming call
- notification
-
-
- Incoming video call
- notification
-
-
- Incorrect security code!
- No comment provided by engineer.
-
-
- Install [SimpleX Chat for terminal](https://github.com/simplex-chat/simplex-chat)
- No comment provided by engineer.
-
-
- Instant push notifications will be hidden!
-
- No comment provided by engineer.
-
-
- Instantly
- No comment provided by engineer.
-
-
- Invalid connection link
- No comment provided by engineer.
-
-
- Invalid server address!
- No comment provided by engineer.
-
-
- Invitation expired!
- No comment provided by engineer.
-
-
- Invite members
- No comment provided by engineer.
-
-
- Invite to group
- No comment provided by engineer.
-
-
- Irreversible message deletion
- No comment provided by engineer.
-
-
- Irreversible message deletion is prohibited in this chat.
- No comment provided by engineer.
-
-
- Irreversible message deletion is prohibited.
- No comment provided by engineer.
-
-
- It allows having many anonymous connections without any shared data between them in a single chat profile.
- No comment provided by engineer.
-
-
- It can happen when:
-1. The messages expire on the server if they were not received for 30 days,
-2. The server you use to receive the messages from this contact was updated and restarted.
-3. The connection is compromised.
-Please connect to the developers via Settings to receive the updates about the servers.
-We will be adding server redundancy to prevent lost messages.
- No comment provided by engineer.
-
-
- It seems like you are already connected via this link. If it is not the case, there was an error (%@).
- No comment provided by engineer.
-
-
- Italian interface
- No comment provided by engineer.
-
-
- Join
- No comment provided by engineer.
-
-
- Join group
- No comment provided by engineer.
-
-
- Join incognito
- No comment provided by engineer.
-
-
- Joining group
- No comment provided by engineer.
-
-
- Keychain error
- No comment provided by engineer.
-
-
- LIVE
- No comment provided by engineer.
-
-
- Large file!
- No comment provided by engineer.
-
-
- Leave
- No comment provided by engineer.
-
-
- Leave group
- No comment provided by engineer.
-
-
- Leave group?
- No comment provided by engineer.
-
-
- Light
- No comment provided by engineer.
-
-
- Limitations
- No comment provided by engineer.
-
-
- Live message!
- No comment provided by engineer.
-
-
- Live messages
- No comment provided by engineer.
-
-
- Local name
- No comment provided by engineer.
-
-
- Local profile data only
- No comment provided by engineer.
-
-
- Make a private connection
- No comment provided by engineer.
-
-
- Make sure SMP server addresses are in correct format, line separated and are not duplicated (%@).
- No comment provided by engineer.
-
-
- Make sure WebRTC ICE server addresses are in correct format, line separated and are not duplicated.
- No comment provided by engineer.
-
-
- Many people asked: *if SimpleX has no user identifiers, how can it deliver messages?*
- No comment provided by engineer.
-
-
- Mark deleted for everyone
- No comment provided by engineer.
-
-
- Mark read
- No comment provided by engineer.
-
-
- Mark verified
- No comment provided by engineer.
-
-
- Markdown in messages
- No comment provided by engineer.
-
-
- Max 30 seconds, received instantly.
- No comment provided by engineer.
-
-
- Member
- No comment provided by engineer.
-
-
- Role will be changed to "%@". All group members will be notified.
- No comment provided by engineer.
-
-
- Role will be changed to "%@". The member will receive a new invitation.
- No comment provided by engineer.
-
-
- Member will be removed from group - this cannot be undone!
- No comment provided by engineer.
-
-
- Message delivery error
- No comment provided by engineer.
-
-
- Message draft
- No comment provided by engineer.
-
-
- Message text
- No comment provided by engineer.
-
-
- Messages
- No comment provided by engineer.
-
-
- Migrating database archive...
- No comment provided by engineer.
-
-
- Migration error:
- No comment provided by engineer.
-
-
- Migration failed. Tap **Skip** below to continue using the current database. Please report the issue to the app developers via chat or email [chat@simplex.chat](mailto:chat@simplex.chat).
- No comment provided by engineer.
-
-
- Migration is completed
- No comment provided by engineer.
-
-
- More improvements are coming soon!
- No comment provided by engineer.
-
-
- Most likely this contact has deleted the connection with you.
- No comment provided by engineer.
-
-
- Multiple chat profiles
- No comment provided by engineer.
-
-
- Mute
- No comment provided by engineer.
-
-
- Name
- No comment provided by engineer.
-
-
- Network & servers
- No comment provided by engineer.
-
-
- Network settings
- No comment provided by engineer.
-
-
- Network status
- No comment provided by engineer.
-
-
- New contact request
- notification
-
-
- New contact:
- notification
-
-
- New database archive
- No comment provided by engineer.
-
-
- New in %@
- No comment provided by engineer.
-
-
- New member role
- No comment provided by engineer.
-
-
- New message
- notification
-
-
- New passphrase…
- No comment provided by engineer.
-
-
- No
- No comment provided by engineer.
-
-
- No contacts selected
- No comment provided by engineer.
-
-
- No contacts to add
- No comment provided by engineer.
-
-
- No device token!
- No comment provided by engineer.
-
-
- Group not found!
- No comment provided by engineer.
-
-
- No permission to record voice message
- No comment provided by engineer.
-
-
- No received or sent files
- No comment provided by engineer.
-
-
- Notifications
- No comment provided by engineer.
-
-
- Notifications are disabled!
- No comment provided by engineer.
-
-
- Off (Local)
- No comment provided by engineer.
-
-
- Ok
- No comment provided by engineer.
-
-
- Old database
- No comment provided by engineer.
-
-
- Old database archive
- No comment provided by engineer.
-
-
- One-time invitation link
- No comment provided by engineer.
-
-
- Onion hosts will be required for connection. Requires enabling VPN.
- No comment provided by engineer.
-
-
- Onion hosts will be used when available. Requires enabling VPN.
- No comment provided by engineer.
-
-
- Onion hosts will not be used.
- No comment provided by engineer.
-
-
- Only client devices store user profiles, contacts, groups, and messages.
- No comment provided by engineer.
-
-
- Only group owners can change group preferences.
- No comment provided by engineer.
-
-
- Only group owners can enable voice messages.
- No comment provided by engineer.
-
-
- Only you can irreversibly delete messages (your contact can mark them for deletion).
- No comment provided by engineer.
-
-
- Only you can send disappearing messages.
- No comment provided by engineer.
-
-
- Only you can send voice messages.
- No comment provided by engineer.
-
-
- Only your contact can irreversibly delete messages (you can mark them for deletion).
- No comment provided by engineer.
-
-
- Only your contact can send disappearing messages.
- No comment provided by engineer.
-
-
- Only your contact can send voice messages.
- No comment provided by engineer.
-
-
- Open Settings
- No comment provided by engineer.
-
-
- Open chat
- No comment provided by engineer.
-
-
- Open chat console
- authentication reason
-
-
- Open user profiles
- authentication reason
-
Anybody can host servers.
يمكن لأي شخص استضافة الخوادم.
No comment provided by engineer.
-
- Opening the link in the browser may reduce connection privacy and security. Untrusted SimpleX links will be red.
- No comment provided by engineer.
-
-
- PING count
- No comment provided by engineer.
-
-
- PING interval
- No comment provided by engineer.
-
-
- Paste
- No comment provided by engineer.
-
-
- Paste image
- No comment provided by engineer.
-
-
- Paste received link
- No comment provided by engineer.
-
-
- Paste the link you received into the box below to connect with your contact.
- No comment provided by engineer.
-
-
- You decide who can connect.
- No comment provided by engineer.
-
-
- Periodically
- No comment provided by engineer.
-
-
- Please ask your contact to enable sending voice messages.
- No comment provided by engineer.
-
-
- Please check that you used the correct link or ask your contact to send you another one.
- No comment provided by engineer.
-
-
- Please check your network connection with %@ and try again.
- No comment provided by engineer.
-
-
- Please check yours and your contact preferences.
- No comment provided by engineer.
-
-
- Please enter correct current passphrase.
- No comment provided by engineer.
-
-
- Please enter the previous password after restoring database backup. This action can not be undone.
- No comment provided by engineer.
-
-
- Please restart the app and migrate the database to enable push notifications.
- No comment provided by engineer.
-
-
- Please store passphrase securely, you will NOT be able to access chat if you lose it.
- No comment provided by engineer.
-
-
- Please store passphrase securely, you will NOT be able to change it if you lose it.
- No comment provided by engineer.
-
-
- Fingerprint in server address does not match certificate.
- server test error
-
-
- Preserve the last message draft, with attachments.
- No comment provided by engineer.
-
-
- Preset server
- No comment provided by engineer.
-
-
- Preset server address
- No comment provided by engineer.
-
-
- Privacy & security
- No comment provided by engineer.
-
-
- Privacy redefined
- No comment provided by engineer.
-
-
- Private filenames
- No comment provided by engineer.
-
-
- Profile and server connections
- No comment provided by engineer.
-
-
- Profile image
- No comment provided by engineer.
-
-
- Prohibit irreversible message deletion.
- No comment provided by engineer.
-
-
- Prohibit sending direct messages to members.
- No comment provided by engineer.
-
-
- Prohibit sending disappearing messages.
- No comment provided by engineer.
-
-
- Prohibit sending voice messages.
- No comment provided by engineer.
-
-
- Protect app screen
- No comment provided by engineer.
-
-
- Protocol timeout
- No comment provided by engineer.
-
-
- Push notifications
- No comment provided by engineer.
-
-
- Rate the app
- No comment provided by engineer.
-
-
- Read
- No comment provided by engineer.
-
-
- Read more in our GitHub repository.
- No comment provided by engineer.
-
-
- Read more in our [GitHub repository](https://github.com/simplex-chat/simplex-chat#readme).
- No comment provided by engineer.
-
-
- Received file event
- notification
-
-
- Receiving via
- No comment provided by engineer.
-
-
- Recipients see updates as you type them.
- No comment provided by engineer.
-
-
- Reduced battery usage
- No comment provided by engineer.
-
-
- Reject
- reject incoming call via notification
-
-
- Reject contact (sender NOT notified)
- No comment provided by engineer.
-
-
- Reject contact request
- No comment provided by engineer.
-
-
- Relay server is only used if necessary. Another party can observe your IP address.
- No comment provided by engineer.
-
-
- Relay server protects your IP address, but it can observe the duration of the call.
- No comment provided by engineer.
-
-
- Remove
- No comment provided by engineer.
-
-
- Remove member
- No comment provided by engineer.
-
-
- Remove member?
- No comment provided by engineer.
-
-
- Remove passphrase from keychain?
- No comment provided by engineer.
-
-
- Reply
- chat item action
-
-
- Required
- No comment provided by engineer.
-
-
- Reset
- No comment provided by engineer.
-
-
- Reset colors
- No comment provided by engineer.
-
-
- Reset to defaults
- No comment provided by engineer.
-
-
- Restart the app to create a new chat profile
- No comment provided by engineer.
-
-
- Restart the app to use imported chat database
- No comment provided by engineer.
-
-
- Restore
- No comment provided by engineer.
-
-
- Restore database backup
- No comment provided by engineer.
-
-
- Restore database backup?
- No comment provided by engineer.
-
-
- Restore database error
- No comment provided by engineer.
-
-
- Reveal
- chat item action
-
-
- Revert
- No comment provided by engineer.
-
-
- Role
- No comment provided by engineer.
-
-
- Run chat
- No comment provided by engineer.
-
-
- SMP servers
- No comment provided by engineer.
-
-
- Save
- chat item action
-
-
- Save (and notify contacts)
- No comment provided by engineer.
-
-
- Save and notify contact
- No comment provided by engineer.
-
-
- Save and notify group members
- No comment provided by engineer.
-
-
- Save archive
- No comment provided by engineer.
-
-
- Save group profile
- No comment provided by engineer.
-
-
- Save passphrase and open chat
- No comment provided by engineer.
-
-
- Save passphrase in Keychain
- No comment provided by engineer.
-
-
- Save preferences?
- No comment provided by engineer.
-
-
- Save servers
- No comment provided by engineer.
-
-
- Saved WebRTC ICE servers will be removed
- No comment provided by engineer.
-
-
- Scan QR code
- No comment provided by engineer.
-
-
- Scan code
- No comment provided by engineer.
-
-
- Scan security code from your contact's app.
- No comment provided by engineer.
-
-
- Scan server QR code
- No comment provided by engineer.
-
-
- Search
- No comment provided by engineer.
-
-
- Secure queue
- server test step
-
-
- Security assessment
- No comment provided by engineer.
-
-
- Security code
- No comment provided by engineer.
-
-
- Send
- No comment provided by engineer.
-
-
- Send a live message - it will update for the recipient(s) as you type it
- No comment provided by engineer.
-
-
- Send direct message
- No comment provided by engineer.
-
-
- Send link previews
- No comment provided by engineer.
-
-
- Send live message
- No comment provided by engineer.
-
-
- Send notifications
- No comment provided by engineer.
-
-
- Send notifications:
- No comment provided by engineer.
-
-
- Send questions and ideas
- No comment provided by engineer.
-
-
- Send them from gallery or custom keyboards.
- No comment provided by engineer.
-
-
- Sender cancelled file transfer.
- No comment provided by engineer.
-
-
- The sender deleted the connection request.
- No comment provided by engineer.
-
-
- Sending via
- No comment provided by engineer.
-
-
- Sent file event
- notification
-
-
- Sent messages will be deleted after set time.
- No comment provided by engineer.
-
Server requires authorization to create queues, check password.
يتطلب الخادم إذنًا لإنشاء قوائم انتظار، تحقق من كلمة المرور
@@ -2609,19 +1323,11 @@ We will be adding server redundancy to prevent lost messages.
مشاركة
chat item action
-
- Share invitation link
- No comment provided by engineer.
-
Share link
مشاركة الرابط
No comment provided by engineer.
-
- Share one-time invitation link
- No comment provided by engineer.
-
Show QR code
عرض رمز QR
@@ -2672,1063 +1378,6 @@ We will be adding server redundancy to prevent lost messages.
دعوة SimpleX لمرة واحدة
simplex link type
-
- Skip
- No comment provided by engineer.
-
-
- Skipped messages
- No comment provided by engineer.
-
-
- Somebody
- notification title
-
-
- Start a new chat
- No comment provided by engineer.
-
-
- Start chat
- No comment provided by engineer.
-
-
- Start migration
- No comment provided by engineer.
-
-
- Stop
- No comment provided by engineer.
-
-
- Stop SimpleX
- authentication reason
-
-
- Stop chat to enable database actions
- No comment provided by engineer.
-
-
- Stop chat to export, import or delete chat database. You will not be able to receive and send messages while the chat is stopped.
- No comment provided by engineer.
-
-
- Stop chat?
- No comment provided by engineer.
-
-
- Support SimpleX Chat
- No comment provided by engineer.
-
-
- System
- No comment provided by engineer.
-
-
- TCP connection timeout
- No comment provided by engineer.
-
-
- TCP_KEEPCNT
- No comment provided by engineer.
-
-
- TCP_KEEPIDLE
- No comment provided by engineer.
-
-
- TCP_KEEPINTVL
- No comment provided by engineer.
-
-
- Take picture
- No comment provided by engineer.
-
-
- Tap button
- No comment provided by engineer.
-
-
- Tap to join
- No comment provided by engineer.
-
-
- Tap to join incognito
- No comment provided by engineer.
-
-
- Tap to start a new chat
- No comment provided by engineer.
-
-
- Test failed at step %@.
- server test failure
-
-
- Test server
- No comment provided by engineer.
-
-
- Test servers
- No comment provided by engineer.
-
-
- Tests failed!
- No comment provided by engineer.
-
-
- Thank you for installing SimpleX Chat!
- No comment provided by engineer.
-
-
- Thanks to the users – [contribute via Weblate](https://github.com/simplex-chat/simplex-chat/tree/stable#help-translating-simplex-chat)!
- No comment provided by engineer.
-
-
- Thanks to the users – contribute via Weblate!
- No comment provided by engineer.
-
-
- No user identifiers.
- No comment provided by engineer.
-
-
- The app can notify you when you receive messages or contact requests - please open settings to enable.
- No comment provided by engineer.
-
-
- The attempt to change database passphrase was not completed.
- No comment provided by engineer.
-
-
- The connection you accepted will be cancelled!
- No comment provided by engineer.
-
-
- The contact you shared this link with will NOT be able to connect!
- No comment provided by engineer.
-
-
- The created archive is available via app Settings / Database / Old database archive.
- No comment provided by engineer.
-
-
- The group is fully decentralized – it is visible only to the members.
- No comment provided by engineer.
-
-
- The microphone does not work when the app is in the background.
- No comment provided by engineer.
-
-
- The future of messaging
- No comment provided by engineer.
-
-
- The old database was not removed during the migration, it can be deleted.
- No comment provided by engineer.
-
-
- Your profile is stored on your device and only shared with your contacts.
- No comment provided by engineer.
-
-
- The sender will NOT be notified
- No comment provided by engineer.
-
-
- The servers for new connections of your current chat profile **%@**.
- No comment provided by engineer.
-
-
- Theme
- No comment provided by engineer.
-
-
- This action cannot be undone - all received and sent files and media will be deleted. Low resolution pictures will remain.
- No comment provided by engineer.
-
-
- This action cannot be undone - the messages sent and received earlier than selected will be deleted. It may take several minutes.
- No comment provided by engineer.
-
-
- This action cannot be undone - your profile, contacts, messages and files will be irreversibly lost.
- No comment provided by engineer.
-
-
- This feature is experimental! It will only work if the other client has version 4.2 installed. You should see the message in the conversation once the address change is completed – please check that you can still receive messages from this contact (or group member).
- No comment provided by engineer.
-
-
- This group no longer exists.
- No comment provided by engineer.
-
-
- This setting applies to messages in your current chat profile **%@**.
- No comment provided by engineer.
-
-
- To ask any questions and to receive updates:
- No comment provided by engineer.
-
-
- To find the profile used for an incognito connection, tap the contact or group name on top of the chat.
- No comment provided by engineer.
-
-
- To make a new connection
- No comment provided by engineer.
-
-
- To prevent the call interruption, enable Do Not Disturb mode.
- No comment provided by engineer.
-
-
- To protect your privacy, SimpleX uses separate IDs for each of your contacts.
- No comment provided by engineer.
-
-
- To protect timezone, image/voice files use UTC.
- No comment provided by engineer.
-
-
- To protect your information, turn on SimpleX Lock.
-You will be prompted to complete authentication before this feature is enabled.
- No comment provided by engineer.
-
-
- To record voice message please grant permission to use Microphone.
- No comment provided by engineer.
-
-
- To support instant push notifications the chat database has to be migrated.
- No comment provided by engineer.
-
-
- To verify end-to-end encryption with your contact compare (or scan) the code on your devices.
- No comment provided by engineer.
-
-
- Transport isolation
- No comment provided by engineer.
-
-
- Trying to connect to the server used to receive messages from this contact (error: %@).
- No comment provided by engineer.
-
-
- Trying to connect to the server used to receive messages from this contact.
- No comment provided by engineer.
-
-
- Turn off
- No comment provided by engineer.
-
-
- Turn off notifications?
- No comment provided by engineer.
-
-
- Turn on
- No comment provided by engineer.
-
-
- Unable to record voice message
- No comment provided by engineer.
-
-
- Unexpected error: %@
- No comment provided by engineer.
-
-
- Unexpected migration state
- No comment provided by engineer.
-
-
- Unknown database error: %@
- No comment provided by engineer.
-
-
- Unknown error
- No comment provided by engineer.
-
-
- Unless your contact deleted the connection or this link was already used, it might be a bug - please report it.
-To connect, please ask your contact to create another connection link and check that you have a stable network connection.
- No comment provided by engineer.
-
-
- Unlock
- authentication reason
-
-
- Unmute
- No comment provided by engineer.
-
-
- Unread
- No comment provided by engineer.
-
-
- Update
- No comment provided by engineer.
-
-
- Update .onion hosts setting?
- No comment provided by engineer.
-
-
- Update database passphrase
- No comment provided by engineer.
-
-
- Update network settings?
- No comment provided by engineer.
-
-
- Update transport isolation mode?
- No comment provided by engineer.
-
-
- Updating settings will re-connect the client to all servers.
- No comment provided by engineer.
-
-
- Updating this setting will re-connect the client to all servers.
- No comment provided by engineer.
-
-
- Use .onion hosts
- No comment provided by engineer.
-
-
- Use SimpleX Chat servers?
- No comment provided by engineer.
-
-
- Use chat
- No comment provided by engineer.
-
-
- Use for new connections
- No comment provided by engineer.
-
-
- Use server
- No comment provided by engineer.
-
-
- User profile
- No comment provided by engineer.
-
-
- Using .onion hosts requires compatible VPN provider.
- No comment provided by engineer.
-
-
- Using SimpleX Chat servers.
- No comment provided by engineer.
-
-
- Verify connection security
- No comment provided by engineer.
-
-
- Verify security code
- No comment provided by engineer.
-
-
- Via browser
- No comment provided by engineer.
-
-
- Video call
- No comment provided by engineer.
-
-
- View security code
- No comment provided by engineer.
-
-
- Voice messages
- chat feature
-
-
- Voice messages are prohibited in this chat.
- No comment provided by engineer.
-
-
- Voice messages are prohibited.
- No comment provided by engineer.
-
-
- Voice messages prohibited!
- No comment provided by engineer.
-
-
- Voice message…
- No comment provided by engineer.
-
-
- Waiting for file
- No comment provided by engineer.
-
-
- Waiting for image
- No comment provided by engineer.
-
-
- WebRTC ICE servers
- No comment provided by engineer.
-
-
- Welcome %@!
- No comment provided by engineer.
-
-
- Welcome message
- No comment provided by engineer.
-
-
- What's new
- No comment provided by engineer.
-
-
- When available
- No comment provided by engineer.
-
-
- When you share an incognito profile with somebody, this profile will be used for the groups they invite you to.
- No comment provided by engineer.
-
-
- With optional welcome message.
- No comment provided by engineer.
-
-
- Wrong database passphrase
- No comment provided by engineer.
-
-
- Wrong passphrase!
- No comment provided by engineer.
-
-
- You
- No comment provided by engineer.
-
-
- You accepted connection
- No comment provided by engineer.
-
-
- You allow
- No comment provided by engineer.
-
-
- You already have a chat profile with the same display name. Please choose another name.
- No comment provided by engineer.
-
-
- You are already connected to %@.
- No comment provided by engineer.
-
-
- You are connected to the server used to receive messages from this contact.
- No comment provided by engineer.
-
-
- You are invited to group
- No comment provided by engineer.
-
-
- You can also connect by clicking the link. If it opens in the browser, click **Open in mobile app** button.
- No comment provided by engineer.
-
-
- You can now send messages to %@
- notification body
-
-
- You can set lock screen notification preview via settings.
- No comment provided by engineer.
-
-
- You can share a link or a QR code - anybody will be able to join the group. You won't lose members of the group if you later delete it.
- No comment provided by engineer.
-
-
- You can share your address as a link or as a QR code - anybody will be able to connect to you. You won't lose your contacts if you later delete it.
- No comment provided by engineer.
-
-
- You can start chat via app Settings / Database or by restarting the app
- No comment provided by engineer.
-
-
- You can use markdown to format messages:
- No comment provided by engineer.
-
-
- You could not be verified; please try again.
- No comment provided by engineer.
-
-
- You have no chats
- No comment provided by engineer.
-
-
- You have to enter passphrase every time the app starts - it is not stored on the device.
- No comment provided by engineer.
-
-
- You invited your contact
- No comment provided by engineer.
-
-
- You joined this group
- No comment provided by engineer.
-
-
- You joined this group. Connecting to inviting group member.
- No comment provided by engineer.
-
-
- You must use the most recent version of your chat database on one device ONLY, otherwise you may stop receiving the messages from some contacts.
- No comment provided by engineer.
-
-
- You need to allow your contact to send voice messages to be able to send them.
- No comment provided by engineer.
-
-
- You rejected group invitation
- No comment provided by engineer.
-
-
- You sent group invitation
- No comment provided by engineer.
-
-
- You will be connected to group when the group host's device is online, please wait or check later!
- No comment provided by engineer.
-
-
- You will be connected when your connection request is accepted, please wait or check later!
- No comment provided by engineer.
-
-
- You will be connected when your contact's device is online, please wait or check later!
- No comment provided by engineer.
-
-
- You will be required to authenticate when you start or resume the app after 30 seconds in background.
- No comment provided by engineer.
-
-
- You will join a group this link refers to and connect to its group members.
- No comment provided by engineer.
-
-
- You will stop receiving messages from this group. Chat history will be preserved.
- No comment provided by engineer.
-
-
- You're trying to invite contact with whom you've shared an incognito profile to the group in which you're using your main profile
- No comment provided by engineer.
-
-
- You're using an incognito profile for this group - to prevent sharing your main profile inviting contacts is not allowed
- No comment provided by engineer.
-
-
- Your ICE servers
- No comment provided by engineer.
-
-
- Your SMP servers
- No comment provided by engineer.
-
-
- Your SimpleX contact address
- No comment provided by engineer.
-
-
- Your calls
- No comment provided by engineer.
-
-
- Your chat database
- No comment provided by engineer.
-
-
- Your chat database is not encrypted - set passphrase to encrypt it.
- No comment provided by engineer.
-
-
- Your chat profile will be sent to group members
- No comment provided by engineer.
-
-
- Your chat profile will be sent to your contact
- No comment provided by engineer.
-
-
- Your chat profiles
- No comment provided by engineer.
-
-
- Your chat profiles are stored locally, only on your device.
- No comment provided by engineer.
-
-
- Your chats
- No comment provided by engineer.
-
-
- Your contact address
- No comment provided by engineer.
-
-
- Your contact can scan it from the app.
- No comment provided by engineer.
-
-
- Your contact needs to be online for the connection to complete.
-You can cancel this connection and remove the contact (and try later with a new link).
- No comment provided by engineer.
-
-
- Your contact sent a file that is larger than currently supported maximum size (%@).
- No comment provided by engineer.
-
-
- Your contacts can allow full message deletion.
- No comment provided by engineer.
-
-
- Your current chat database will be DELETED and REPLACED with the imported one.
- No comment provided by engineer.
-
-
- Your current profile
- No comment provided by engineer.
-
-
- Your preferences
- No comment provided by engineer.
-
-
- Your privacy
- No comment provided by engineer.
-
-
- Your profile is stored on your device and shared only with your contacts.
-SimpleX servers cannot see your profile.
- No comment provided by engineer.
-
-
- Your profile will be sent to the contact that you received this link from
- No comment provided by engineer.
-
-
- Your profile, contacts and delivered messages are stored on your device.
- No comment provided by engineer.
-
-
- Your random profile
- No comment provided by engineer.
-
-
- Your server
- No comment provided by engineer.
-
-
- Your server address
- No comment provided by engineer.
-
-
- Your settings
- No comment provided by engineer.
-
-
- [Contribute](https://github.com/simplex-chat/simplex-chat#contribute)
- No comment provided by engineer.
-
-
- [Send us email](mailto:chat@simplex.chat)
- No comment provided by engineer.
-
-
- [Star on GitHub](https://github.com/simplex-chat/simplex-chat)
- No comment provided by engineer.
-
-
- \_italic_
- No comment provided by engineer.
-
-
- \`a + b`
- No comment provided by engineer.
-
-
- above, then choose:
- No comment provided by engineer.
-
-
- accepted call
- call status
-
-
- admin
- member role
-
-
- always
- pref value
-
-
- audio call (not e2e encrypted)
- No comment provided by engineer.
-
-
- bad message ID
- integrity error chat item
-
-
- bad message hash
- integrity error chat item
-
-
- bold
- No comment provided by engineer.
-
-
- call error
- call status
-
-
- call in progress
- call status
-
-
- calling…
- call status
-
-
- cancelled %@
- feature offered item
-
-
- changed address for you
- chat item text
-
-
- changed role of %1$@ to %2$@
- rcv group event chat item
-
-
- changed your role to %@
- rcv group event chat item
-
-
- changing address for %@...
- chat item text
-
-
- changing address...
- chat item text
-
-
- colored
- No comment provided by engineer.
-
-
- complete
- No comment provided by engineer.
-
-
- connect to SimpleX Chat developers.
- No comment provided by engineer.
-
-
- connected
- No comment provided by engineer.
-
-
- connecting
- No comment provided by engineer.
-
-
- connecting (accepted)
- No comment provided by engineer.
-
-
- connecting (announced)
- No comment provided by engineer.
-
-
- connecting (introduced)
- No comment provided by engineer.
-
-
- connecting (introduction invitation)
- No comment provided by engineer.
-
-
- connecting call…
- call status
-
-
- connecting…
- chat list item title
-
-
- connection established
- chat list item title (it should not be shown
-
-
- connection:%@
- connection information
-
-
- contact has e2e encryption
- No comment provided by engineer.
-
-
- contact has no e2e encryption
- No comment provided by engineer.
-
-
- creator
- No comment provided by engineer.
-
-
- default (%@)
- pref value
-
-
- deleted
- deleted chat item
-
-
- deleted group
- rcv group event chat item
-
-
- direct
- connection level description
-
-
- duplicate message
- integrity error chat item
-
-
- e2e encrypted
- No comment provided by engineer.
-
-
- enabled
- enabled status
-
-
- enabled for contact
- enabled status
-
-
- enabled for you
- enabled status
-
-
- ended
- No comment provided by engineer.
-
-
- ended call %@
- call status
-
-
- error
- No comment provided by engineer.
-
-
- group deleted
- No comment provided by engineer.
-
-
- group profile updated
- snd group event chat item
-
-
- iOS Keychain is used to securely store passphrase - it allows receiving push notifications.
- No comment provided by engineer.
-
-
- iOS Keychain will be used to securely store passphrase after you restart the app or change passphrase - it will allow receiving push notifications.
- No comment provided by engineer.
-
-
- incognito via contact address link
- chat list item description
-
-
- incognito via group link
- chat list item description
-
-
- incognito via one-time link
- chat list item description
-
-
- indirect (%d)
- connection level description
-
-
- invalid chat
- invalid chat data
-
-
- invalid chat data
- No comment provided by engineer.
-
-
- invalid data
- invalid chat item
-
-
- invitation to group %@
- group name
-
-
- invited
- No comment provided by engineer.
-
-
- invited %@
- rcv group event chat item
-
-
- invited to connect
- chat list item title
-
-
- invited via your group link
- rcv group event chat item
-
-
- italic
- No comment provided by engineer.
-
-
- join as %@
- No comment provided by engineer.
-
-
- left
- rcv group event chat item
-
-
- marked deleted
- marked deleted chat item preview text
-
-
- member
- member role
-
-
- connected
- rcv group event chat item
-
-
- message received
- notification
-
-
- missed call
- call status
-
-
- moderated
- moderated chat item
-
-
- never
- No comment provided by engineer.
-
-
- new message
- notification
-
-
- no
- pref value
-
-
- no e2e encryption
- No comment provided by engineer.
-
-
- off
- enabled status
- group pref value
-
-
- offered %@
- feature offered item
-
-
- offered %1$@: %2$@
- feature offered item
-
-
- on
- group pref value
-
-
- or chat with the developers
- No comment provided by engineer.
-
-
- owner
- member role
-
-
- peer-to-peer
- No comment provided by engineer.
-
-
- received answer…
- No comment provided by engineer.
-
-
- received confirmation…
- No comment provided by engineer.
-
-
- rejected call
- call status
-
-
- removed
- No comment provided by engineer.
-
-
- removed %@
- rcv group event chat item
-
-
- removed you
- rcv group event chat item
-
-
- sec
- network option
-
-
- secret
- No comment provided by engineer.
-
starting…
يبدأ…
@@ -3739,10 +1388,6 @@ SimpleX servers cannot see your profile.
شطب
No comment provided by engineer.
-
- this contact
- notification title
-
unknown
غير معروف
@@ -3753,10 +1398,6 @@ SimpleX servers cannot see your profile.
حدثت ملف تعريف المجموعة
rcv group event chat item
-
- v%@ (%@)
- No comment provided by engineer.
-
via contact address link
عبر رابط عنوان الاتصال
@@ -3812,44 +1453,16 @@ SimpleX servers cannot see your profile.
غيّرتَ العنوان
chat item text
-
- you changed address for %@
- chat item text
-
-
- you changed role for yourself to %@
- snd group event chat item
-
-
- you changed role of %1$@ to %2$@
- snd group event chat item
-
you left
غادرت
snd group event chat item
-
- you removed %@
- snd group event chat item
-
you shared one-time link
لقد شاركت رابط لمرة واحدة
chat list item description
-
- you shared one-time link incognito
- chat list item description
-
-
- you:
- No comment provided by engineer.
-
-
- \~strike~
- No comment provided by engineer.
-
%@ servers
%@ الخوادم
@@ -5455,7 +3068,7 @@ This is your own one-time link!
Bulgarian, Finnish, Thai and Ukrainian - thanks to the users and [Weblate](https://github.com/simplex-chat/simplex-chat/tree/stable#help-translating-simplex-chat)!
- البلغارية والفنلندية والتايلاندية والأوكرانية - شكرًا للمستخدمين و[Weblate] (https://github.com/simplex-chat/simplex-chat/tree/stable#help-translating-simplex-chat)!
+ البلغارية والفنلندية والتايلاندية والأوكرانية - شكرًا للمستخدمين و[Weblate](https://github.com/simplex-chat/simplex-chat/tree/stable#help-translating-simplex-chat)!
Choose _Migrate from another device_ on the new device and scan QR code.
@@ -5853,7 +3466,7 @@ This is your own one-time link!
Error connecting to forwarding server %@. Please try later.
- خطأ في الإتصال بخادم التحويل @%. حاول مجددا بعد حين.
+ خطأ في الإتصال بخادم التحويل %@. حاول مجددا بعد حين.
-
- SimpleX
- Bundle name
-
-
- SimpleX needs camera access to scan QR codes to connect to other users and for video calls.
- Privacy - Camera Usage Description
-
-
- SimpleX uses Face ID for local authentication
- Privacy - Face ID Usage Description
-
-
- SimpleX needs microphone access for audio and video calls, and to record voice messages.
- Privacy - Microphone Usage Description
-
-
- SimpleX needs access to Photo Library for saving captured and received media
- Privacy - Photo Library Additions Usage Description
-