commit 0e8a88584d619ec8da3c6ac1411eb10a2ed72bee Author: xiaoxue Date: Mon May 25 00:25:42 2026 +0800 同步完整源码 - 2026-05-25 diff --git a/.actrc b/.actrc new file mode 100644 index 0000000..614c1bf --- /dev/null +++ b/.actrc @@ -0,0 +1,15 @@ +# act 配置文件 - 用于本地测试 GitHub Actions + +# 指定平台映射,使用更小的容器 +-P ubuntu-latest=catthehacker/ubuntu:act-latest +-P macos-latest=catthehacker/ubuntu:act-latest +-P windows-latest=catthehacker/ubuntu:act-latest + +# 容器架构 +--container-architecture linux/amd64 + +# 启用详细输出 +--verbose + +# 重用容器以提高性能 +--reuse \ No newline at end of file diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..719dc33 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "[pre-commit] Running Dart formatting..." + +# Resolve Dart binary robustly (works even if PATH is minimal in GUI/IDE) +DART_BIN="" + +if command -v dart >/dev/null 2>&1; then + DART_BIN="$(command -v dart)" +else + if command -v flutter >/dev/null 2>&1; then + FLUTTER_BIN="$(command -v flutter)" + FLUTTER_DIR="$(dirname "$FLUTTER_BIN")" + # Common locations when using Flutter-bundled Dart (Linux/macOS/Windows) + CANDIDATES=( + "$FLUTTER_DIR/dart" + "$FLUTTER_DIR/dart.bat" + "$FLUTTER_DIR/dart.exe" + "$FLUTTER_DIR/cache/dart-sdk/bin/dart" + "$FLUTTER_DIR/cache/dart-sdk/bin/dart.exe" + ) + for c in "${CANDIDATES[@]}"; do + if [ -x "$c" ]; then + DART_BIN="$c" + break + fi + done + fi + # FVM-managed Flutter SDK (project-local) + if [ -z "$DART_BIN" ]; then + if [ -x ".fvm/flutter_sdk/bin/dart" ]; then + DART_BIN=".fvm/flutter_sdk/bin/dart" + elif [ -x ".fvm/flutter_sdk/bin/dart.exe" ]; then + DART_BIN=".fvm/flutter_sdk/bin/dart.exe" + elif [ -x ".fvm/flutter_sdk/bin/cache/dart-sdk/bin/dart" ]; then + DART_BIN=".fvm/flutter_sdk/bin/cache/dart-sdk/bin/dart" + elif [ -x ".fvm/flutter_sdk/bin/cache/dart-sdk/bin/dart.exe" ]; then + DART_BIN=".fvm/flutter_sdk/bin/cache/dart-sdk/bin/dart.exe" + fi + fi +fi + +if [ -z "$DART_BIN" ] || ! "$DART_BIN" --version >/dev/null 2>&1; then + echo "[pre-commit] ERROR: Dart SDK not found. Please ensure either: " >&2 + echo " - 'dart' is on PATH, or" >&2 + echo " - 'flutter' is on PATH (it bundles Dart), e.g.:" >&2 + echo " export PATH=\$PATH:\$HOME/flutter/bin" >&2 + exit 127 +fi + +# Format the entire repository (as requested) +"$DART_BIN" format . + +# Re-add files in case formatter changed them +git add -A + +echo "[pre-commit] Formatting done." + +# Enforce Dart formatting before commit (no changes needed) +echo "[pre-commit] Checking Dart formatting..." +if ! "$DART_BIN" format --output=none --set-exit-if-changed .; then + echo "\n[pre-commit] Formatting issues detected. Please run:" + echo " $DART_BIN format ." + echo "and re-commit." + exit 1 +fi + +echo "[pre-commit] Formatting OK." +exit 0 + diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml new file mode 100644 index 0000000..6ed93ac --- /dev/null +++ b/.github/workflows/build-web.yml @@ -0,0 +1,52 @@ +name: Build & deploy + +on: + push: + branches: + - main + +jobs: + build: + name: Build + runs-on: ubuntu-latest + + steps: + - name: Clone repository + uses: actions/checkout@v4 + + - name: Set up Flutter + uses: subosito/flutter-action@v2 + with: + channel: 'stable' + flutter-version: '3.32.5' + + - name: Get dependencies + run: flutter pub get + + - name: Build release project + run: flutter build web --base-href /chatmcp/ + + - name: Upload production-ready build files + uses: actions/upload-artifact@v4 + with: + name: production-files + path: build/web + + deploy: + name: Deploy + needs: build + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' + + steps: + - name: Download artifact + uses: actions/download-artifact@v4 + with: + name: production-files + path: build/web + + - name: Deploy to gh-pages + uses: peaceiris/actions-gh-pages@v4 + with: + github_token: ${{ secrets.MY_GITHUB_TOKEN }} + publish_dir: build/web \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..80bf123 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,145 @@ +name: Build and Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +jobs: + build: + strategy: + matrix: + os: [ubuntu-22.04, macos-latest, windows-latest] + include: + - os: ubuntu-22.04 + apk_build: true + - os: macos-latest + apk_build: false + - os: windows-latest + apk_build: false + runs-on: ${{ matrix.os }} + + steps: + - uses: actions/checkout@v3 + + - name: Setup Java + if: matrix.apk_build + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: '17' + + - name: Setup Android SDK + if: matrix.apk_build + uses: android-actions/setup-android@v3 + + - name: Setup Flutter + uses: subosito/flutter-action@v2 + with: + channel: 'stable' + flutter-version: '3.32.5' + + - name: Create empty .env file + run: touch .env + + - name: Install dependencies + run: flutter pub get + + - name: Setup Android Signing + if: matrix.apk_build && github.event_name != 'pull_request' + env: + SIGNING_KEYSTORE: ${{ secrets.SIGNING_KEYSTORE }} + SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }} + SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }} + SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }} + run: | + mkdir -p android/app/keystore + + if [ -n "$SIGNING_KEYSTORE" ]; then + echo "$SIGNING_KEYSTORE" | base64 -d > android/app/keystore/release.jks + echo "SIGNING_STORE_PATH=keystore/release.jks" >> $GITHUB_ENV + echo "SIGNING_KEY_ALIAS=$SIGNING_KEY_ALIAS" >> $GITHUB_ENV + echo "SIGNING_STORE_PASSWORD=$SIGNING_STORE_PASSWORD" >> $GITHUB_ENV + echo "SIGNING_KEY_PASSWORD=$SIGNING_KEY_PASSWORD" >> $GITHUB_ENV + echo "✅ Android Signature Config Set" + else + echo "⚠️ No signature config found, using debug signing" + fi + + - name: Activate FastForge + run: dart pub global activate fastforge + + - name: Build linux/android package + if: matrix.os == 'ubuntu-22.04' + run: | + sudo apt-get update + sudo apt-get install -y ninja-build libgtk-3-dev locate libsqlite3-dev fuse libfuse2 libstdc++-12-dev patchelf + sudo updatedb + wget -O appimagetool "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage" + chmod +x appimagetool + sudo mv appimagetool /usr/local/bin/ + fastforge release --name=linux + fastforge release --name=android + + - name: Verify AppImage GLIBC compatibility (Pop!_OS 22.04) + if: matrix.os == 'ubuntu-22.04' + run: | + set -e + shopt -s nullglob + found=0 + for f in dist/**/*AppImage dist/*.AppImage; do + echo "Checking $f" + chmod +x "$f" + "$f" --appimage-extract >/dev/null 2>&1 || true + if [ -d squashfs-root/usr/lib ]; then + if strings squashfs-root/usr/lib/libstdc++.so.6 | grep -E 'GLIBC_2\.(36|37|38|39)' -q; then + echo "❌ $f contains libstdc++ requiring newer GLIBC" >&2 + exit 1 + fi + fi + rm -rf squashfs-root + found=1 + done + if [ "$found" -eq 0 ]; then + echo "No AppImage files found under dist/. Skipping check." + else + echo "✅ AppImage libstdc++ is compatible with GLIBC 2.35 hosts." + fi + + - name: Setup Node.js for macOS + if: matrix.os == 'macos-latest' + uses: actions/setup-node@v3 + with: + node-version: '20' + + - name: macos npm install + if: matrix.os == 'macos-latest' + run: | + npm install -g appdmg + + - name: Build macos package + if: matrix.os == 'macos-latest' + run: | + fastforge release --name=macos + + - name: Build windows package + if: matrix.os == 'windows-latest' + run: | + fastforge release --name=windows + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: build-${{ matrix.os }} + path: | + dist/*/* + + - name: Create Release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v1 + with: + files: | + dist/*/* + env: + GITHUB_TOKEN: ${{ secrets.MY_GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml new file mode 100644 index 0000000..8c7d05d --- /dev/null +++ b/.github/workflows/format.yml @@ -0,0 +1,34 @@ +name: check-format + +on: + pull_request: + branches: [ "**" ] + push: + branches: [ main, master ] + +jobs: + dart-format: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Flutter + uses: subosito/flutter-action@v2 + with: + channel: stable + + - name: Install dependencies + run: flutter pub get + + - name: Check formatting (dry-run, excluding generated) + run: | + set -e + FILES=$(git ls-files '*.dart' ':!lib/generated/**') + if [ -z "$FILES" ]; then + echo "No Dart files to check." + exit 0 + fi + dart --version + dart format --output=none --set-exit-if-changed $FILES + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a850b32 --- /dev/null +++ b/.gitignore @@ -0,0 +1,70 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ +node_modules/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +.env + +# aider +.aider.* +devtools_options.yaml + +# package +*.deb +*.rpm +dist/* + +# FVM Version Cache +.fvm/ +.fvmrc + +# VSCode related +.vscode/ + +# Android Signature-related documents +android/app/keystore/ +android/signing.env +*.jks +*.keystore diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..6ac59d7 --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "35c388afb57ef061d06a39b537336c87e0e3d1b1" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 35c388afb57ef061d06a39b537336c87e0e3d1b1 + base_revision: 35c388afb57ef061d06a39b537336c87e0e3d1b1 + - platform: android + create_revision: 35c388afb57ef061d06a39b537336c87e0e3d1b1 + base_revision: 35c388afb57ef061d06a39b537336c87e0e3d1b1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4caf84c --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024, Nicolas Bonamy + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..90b2478 --- /dev/null +++ b/Makefile @@ -0,0 +1,51 @@ +lan: + flutter gen-l10n + +build-icon: + flutter pub run flutter_launcher_icons + +dep: + dart pub global run dependency_validator + +upgrade: + flutter pub upgrade --major-versions + +# Android 签名相关命令 +android-keystore: + ./scripts/create_keystore.sh + +android-verify: + ./scripts/verify_signing.sh + +android-apk: + flutter build apk --release + +android-apk-split: + flutter build apk --release --split-per-abi + +android-aab: + flutter build appbundle --release + +android-build: android-apk android-aab + +android-build-all: android-apk-split android-aab + +android-summary: + ./scripts/build_summary.sh + +# 清理构建文件 +clean: + flutter clean + flutter pub get + +# 完整的发布构建 +release-android: clean android-verify android-build-all android-summary + +.PHONY: lan dep upgrade android-keystore android-verify android-apk android-apk-split android-aab android-build android-build-all android-summary clean release-android + +# --- Team tooling --- +setup-git-hooks: + git config core.hooksPath .githooks + chmod +x .githooks/pre-commit + +.PHONY: setup-git-hooks \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d15371a --- /dev/null +++ b/README.md @@ -0,0 +1,345 @@ +
+logo +

chatmcp

+ +Cross-platform `Macos | Windows | Linux | iOS | Android | Web` AI Chat Client + +[English](./README.md) | [简体中文](./README_ZH.md) | [Türkçe](./README_TR.md) + +
+ +## Install + +| macOS | Windows | Linux | iOS | Android | Web | +|---------------------------------------------------------|---------------------------------------------------------|-----------------------------------------------------------|----------------------------------------------------------|---------------------------------------------------------|--------------------------------------------------------| +| [Release](https://github.com/daodao97/chatmcp/releases) | [Release](https://github.com/daodao97/chatmcp/releases) | [Release](https://github.com/daodao97/chatmcp/releases) ¹ | [TestFlight](https://testflight.apple.com/join/dCXksFJV) | [Release](https://github.com/daodao97/chatmcp/releases) | [GitHub Pages](https://daodao97.github.io/chatmcp) ² | + +¹ **Linux Notes:** +- See Linux requirements below for AppImage/DEB runtime dependencies on Ubuntu 22.04 and 24.04 +- Improved Experience: Latest versions include better dark theme support, unified data storage following [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html), and optimized UI layout for Linux desktop environments is planned +- Tested on major distributions: Ubuntu, Fedora, Arch Linux, openSUSE + +² Note: Web version runs entirely in your browser with local storage for chat history and settings. + +## Documentation + +Also, you can use DeepWiki to get more information about chatmcp. +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/daodao97/chatmcp) DeepWiki is an AI-powered platform that transforms any +public GitHub repository into a fully interactive, easy-to-understand wiki. By analysing code, documentation, and configuration files, it creates +clear explanations, interactive diagrams, and even allows for real-time Q&A with the AI. + +## Preview + +![Artifact Display](./docs/preview/artifact.gif) +![Thinking Mode](./docs/preview/think.webp) +![Generate Image](./docs/preview/gen_img.webp) +![LaTeX Support](./docs/preview/latex.webp) +![HTML Preview](./docs/preview/html-preview.webp) +![Mermaid Diagram](./docs/preview/mermaid.webp) +![MCP Workflow](./docs/preview/mcp-workerflow.webp) +![MCP InMemory](./docs/preview/mcp-inmemory.webp) +![MCP Tools](./docs/preview/mcp-tools.webp) +![LLM Provider](./docs/preview/llm-provider.webp) +![MCP Stdio](./docs/preview/mcp-stdio.webp) +![MCP SSE](./docs/preview/mcp-sse.webp) + +### Data Sync + +ChatMCP applications can sync data within the same local area network + +![Data sync](./docs/preview/data-sync.webp) + +## Usage + +Make sure you have installed `uvx` or `npx` in your system + +### MacOS + +```bash +# uvx +brew install uv + +# npx +brew install node +``` + +### Linux + +```bash +# uvx +curl -LsSf https://astral.sh/uv/install.sh | sh + +# npx (using apt) +sudo apt update +sudo apt install nodejs npm +``` + +### Linux Requirements (Ubuntu 22.04 and 24.04) + +For running ChatMCP AppImage/DEB on Ubuntu and derivatives, install the following runtime packages: + +- AppImage (FUSE): `libfuse2` +- GTK 3: `libgtk-3-0` +- Graphics/EGL: + - Ubuntu 22.04: `libegl1-mesa`, `libgles2`, `libgl1-mesa-dri`, `libglx-mesa0` + - Ubuntu 24.04: `libegl1`, `libgles2`, `libgl1-mesa-dri`, `libglx-mesa0` +- X11 utilities and SQLite: `libx11-6`, `xdg-utils`, `libsqlite3-0` + +Install commands: + +- Ubuntu 22.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1-mesa libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 libsqlite3-dev +``` + +- Ubuntu 24.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1 libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 libsqlite3-dev +``` + +Optional (recommended): `mesa-vulkan-drivers`, `mesa-utils` (for diagnostics like glxinfo) + +1. Configure Your LLM API Key and Endpoint in `Setting` Page +2. Install MCP Server from `MCP Server` Page +3. Chat with MCP Server + +- stdio mcp server + ![](./docs/mcp_stdio.png) + +- sse mcp server + ![](./docs/mcp_sse.png) + +## Data Storage + +ChatMCP follows platform-specific best practices for data storage: + +### Storage Locations + +**macOS:** +```bash +~/Library/Application Support/ChatMcp/ +``` + +**Windows:** +```bash +%APPDATA%\ChatMcp\ +``` + +**Linux:** +```bash +~/.local/share/ChatMcp/ # Honors $XDG_DATA_HOME if set +~/.local/share/run.daodao.chatmcp # Flutter dependency +``` + +**Mobile:** +- Application Documents Directory + +### File Structure + +All platforms store data in a unified directory structure: +- `logs` folder - Application logs +- `chatmcp.db` - Main database file containing chat history and messages +- `shared_preferences.json` - Application settings and preferences +- `mcp_server.json` - MCP server configurations + +### Reset Application Data + +To completely reset the application (delete all chat history, settings, and configurations): + +**macOS:** +```bash +rm -rf ~/Library/Application\ Support/ChatMcp +``` + +**Windows:** +```bash +rd /s /q "%APPDATA%\ChatMcp" +``` + +**Linux:** +```bash +rm -rf ~/.local/share/ChatMcp +rm -rf ~/.local/share/run.daodao.chatmcp +``` + +## Development + +### Install Flutter + +To develop or run ChatMCP, you need to have [Flutter](https://flutter.dev/) installed. +Follow the official [Flutter installation guide](https://docs.flutter.dev/get-started/install) for your platform. + +- [Download Flutter](https://docs.flutter.dev/get-started/install) + +After installing, verify with: +```bash +flutter --version +``` + +### Mandatory Code Formatting and Pre-commit Hook + +To keep a consistent code style across contributors, this repository enforces Dart formatting on every commit. + +- The repository ships a versioned Git hook at `.githooks/pre-commit`. +- On commit, it runs `dart format .`, re-adds changed files, and then performs a no-output check to ensure nothing remains unformatted. +- Commits that are not properly formatted will be rejected locally; in addition, CI will fail unformatted PRs. + +Quick setup (once per clone): + +```bash +make setup-git-hooks +``` + +Manual setup (alternative): + +```bash +git config core.hooksPath .githooks +chmod +x .githooks/pre-commit +``` + +Requirements (at least one must be available on PATH): + +- Dart SDK, or +- Flutter (bundles Dart) + +Examples: + +- macOS/Linux (Flutter): + ```bash + export PATH="$PATH:$HOME/flutter/bin" + which flutter && flutter --version + which dart && dart --version + ``` +- macOS/Linux (Dart SDK): + ```bash + export PATH="$PATH:$HOME/dart-sdk/bin" + which dart && dart --version + ``` +- Windows (PowerShell): Add `C:\\src\\flutter\\bin` (or your Flutter path) to the User/System PATH. Validate via: + ```powershell + where flutter + where dart + ``` + +IDE note: After changing PATH, restart your IDE so VCS operations (commit) inherit the updated environment. + +CI enforcement: + +- A GitHub Actions workflow `check-format` runs `dart format --output=none --set-exit-if-changed .` on push/PR and will fail if any file is not formatted. + +Policy: + +- Do not bypass hooks (e.g., `--no-verify`). Such changes will fail in CI and must be reformatted anyway. + +### Clone and Run Locally + +```bash +# Clone the repository +git clone https://github.com/daodao97/chatmcp.git +cd chatmcp + +# Install dependencies +flutter pub get + +# Run on macOS +flutter run -d macos + +# Run on Linux (requires Flutter desktop support enabled) +flutter run -d linux + +# Build release for Linux +flutter build linux +``` + +### Web Version + +#### Local Development +```bash +# Install dependencies +flutter pub get + +# Run Web version locally +flutter run -d chrome +# Or specify port +flutter run -d chrome --web-port 8080 +# Or run as web-serer for other browsers. +flutter run -d web-server +``` + +#### Build Web Version +```bash +# Build production version +flutter build web + +# Build with base path (for deploying to subdirectory) +flutter build web --base-href /chatmcp/ +``` + +#### Deploy to GitHub Pages +```bash +# 1. Build Web version +flutter build web --base-href /chatmcp/ + +# 2. Push build/web directory contents to gh-pages branch +# Or use GitHub Actions for automatic deployment +``` + +After building, files will be in the `build/web` directory and can be deployed to any static website hosting service. + +## Features + +- [x] Chat with MCP Server +- [X] MCP Server Market +- [ ] Auto install MCP Server +- [x] SSE MCP Transport Support +- [x] Auto Choose MCP Server +- [x] Chat History +- [x] OpenAI LLM Model +- [x] Claude LLM Model +- [x] OLLama LLM Model +- [x] DeepSeek LLM Model +- [ ] RAG +- [ ] Better UI Design +- [x] Dark/Light Theme + +All features are welcome to submit, you can submit your ideas or bugs in [Issues](https://github.com/daodao97/chatmcp/issues) + +## MCP Server Market + +You can install MCP Server from MCP Server Market, MCP Server Market is a collection of MCP Server, you can use it to chat with different data. + +* Also you can add new MCP Server to the Market : [MCP Server Market](https://github.com/chatmcpclient/mcp_server_market/blob/main/mcp_server_market.json) + +Create a fork of [mcp_server_market](https://github.com/chatmcpclient/mcp_server_market) and add your MCP Server to the `mcp_server_market.json` end of the file. + +```json +{ + "mcpServers": { + "existing-mcp-servers": {}, + "your-mcp-server": { + "command": "uvx", + "args": [ + "--from", + "git+https://github.com/username/your-mcp-server", + "your-mcp-server" + ] + } + } +} +``` +You can send a Pull Request to the [mcp_server_market](https://github.com/chatmcpclient/mcp_server_market) repository to add your MCP Server to the Market. After your PR is merged, your MCP Server will be available in the Market and other users can use it immediately. + +Your feedback helps us improve chatmcp and helps other users make informed decisions. + +## Thanks + +- [MCP](https://modelcontextprotocol.io/introduction) +- [mcp-cli](https://github.com/chrishayuk/mcp-cli) + +## License + +This project is licensed under the [Apache License 2.0](./LICENSE). + +## Star History + +![](https://api.star-history.com/svg?repos=daodao97/chatmcp&type=Date) diff --git a/README_TR.md b/README_TR.md new file mode 100644 index 0000000..55d4fa5 --- /dev/null +++ b/README_TR.md @@ -0,0 +1,307 @@ +
+logo +

chatmcp

+ +Platformlar Arası MacOS | Windows | Linux | iOS | Android | Web Yapay Zeka Sohbet İstemcisi + +[English](./README.md) | [简体中文](./README_ZH.md) | Türkçe + +
+ +## Kurulum + +| macOS | Windows | Linux | iOS | Android | Web | +|-------------------------------------------------------|-------------------------------------------------------|---------------------------------------------------------|----------------------------------------------------------|-------------------------------------------------------|--------------------------------------------------------| +| [İndir](https://github.com/daodao97/chatmcp/releases) | [İndir](https://github.com/daodao97/chatmcp/releases) | [İndir](https://github.com/daodao97/chatmcp/releases) ¹ | [TestFlight](https://testflight.apple.com/join/dCXksFJV) | [İndir](https://github.com/daodao97/chatmcp/releases) | [GitHub Pages](https://daodao97.github.io/chatmcp) ² | + +¹ Not: Linux gereksinimleri aşağıdadır (Ubuntu 22.04 ve 24.04) + +² Not: Web sürümü tamamen tarayıcınızda çalışır ve sohbet geçmişi ile ayarlar için yerel depolama kullanır. + +## Dokümantasyon + +Ayrıca, chatmcp hakkında daha fazla bilgi edinmek için DeepWiki'yi kullanabilirsiniz. +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/daodao97/chatmcp) +DeepWiki, herhangi bir herkese açık GitHub deposunu tam etkileşimli, kolay anlaşılır bir wiki'ye dönüştüren yapay zeka destekli bir platformdur. +Kodları, dokümantasyonu ve yapılandırma dosyalarını analiz ederek net açıklamalar ve etkileşimli diyagramlar oluşturur, hatta yapay zeka ile +gerçek zamanlı olarak soru-cevap yapmanıza olanak tanır. + + +## Kullanım + +Sisteminizde uvx veya npx'in kurulu olduğundan emin olun. +### MacOS + +* uvx için + +```shell +brew install uv +``` + +* npx için + +```shell +brew install node +``` + +### Linux + +* uvx için + +curl -LsSf https://astral.sh/uv/install.sh | sh + +* npx için (apt kullanarak) + +```shell +sudo apt update +sudo apt install nodejs npm +``` + +### Linux Gereksinimleri (Ubuntu 22.04 ve 24.04) + +ChatMCP AppImage/DEB çalıştırmak için aşağıdaki paketlerin kurulu olması gerekir: + +- AppImage (FUSE): `libfuse2` +- GTK 3: `libgtk-3-0` +- Grafik/EGL: + - Ubuntu 22.04: `libegl1-mesa`, `libgles2`, `libgl1-mesa-dri`, `libglx-mesa0` + - Ubuntu 24.04: `libegl1`, `libgles2`, `libgl1-mesa-dri`, `libglx-mesa0` +- X11 yardımcıları ve SQLite: `libx11-6`, `xdg-utils`, `libsqlite3-0` + +Kurulum komutları: + +- Ubuntu 22.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1-mesa libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 +``` + +- Ubuntu 24.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1 libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 +``` + +Opsiyonel (önerilir): `mesa-vulkan-drivers`, `mesa-utils` (glxinfo gibi teşhis araçları) + +1. Ayarlar sayfasında LLM API Anahtarınızı ve Uç Noktanızı (Endpoint) yapılandırın. +2. MCP Sunucusu sayfasından bir MCP sunucusu kurun. +3. MCP Sunucusu ile sohbete başlayın. + +* stdio mcp sunucusu +![alt text](./docs/mcp_stdio.png) +* sse mcp sunucusu +![alt text](./docs/mcp_sse.png) +* Hata Ayıklama Modu (Debug) +- Kayıtlar (Loglar) & Veriler + +macOS: + +```bash +~/Library/Application Support/ChatMcp +``` + +Windows: + +```bash +%APPDATA%\ChatMcp +``` + +Linux: + +```bash +~/.local/share/ChatMcp +``` + +Mobil: + +- Uygulama Belgeler Dizini +Uygulamayı sıfırlamak için bu komutları kullanabilirsiniz: + +macOS: + +```bash +rm -rf ~/Library/Application\ Support/ChatMcp +``` + +Windows: + +```bash +rd /s /q "%APPDATA%\ChatMcp" +``` + +Linux: + +```bash +rm -rf ~/.local/share/ChatMcp +rm -rf ~/.local/share/run.daodao.chatmcp +``` + +## Geliştirici Notları + +Flutter paketlerini yükleyin +```shell +flutter pub get +``` +Çalıştırmak için: +- linux: +```shell +flutter run -d linux +``` + +- macOS: +```shell +flutter run -d macos +``` + +### Zorunlu Kod Formatı ve Pre-commit Hook + +Katkı verenler arasında tutarlı bir kod stili sağlamak için, bu depoda her commit öncesi Dart formatlaması zorunludur. + +- Sürüm kontrolünde bulunan bir Git hook dosyası `.githooks/pre-commit` ile gelir. +- Commit sırasında `dart format .` çalıştırılır, değişen dosyalar yeniden `git add` edilir ve ardından hiçbir dosyanın format dışı kalmadığını doğrulayan bir kontrol yapılır. +- Yerelde format dışı commit’ler reddedilir; ayrıca CI üzerinde de format dışı PR’lar kırılır. + +Hızlı kurulum (her klon sonrası bir defa): + +```bash +make setup-git-hooks +``` + +El ile kurulum (alternatif): + +```bash +git config core.hooksPath .githooks +chmod +x .githooks/pre-commit +``` + +Gereksinimler (PATH üzerinde en az biri olmalı): + +- Dart SDK, veya +- Flutter (Dart içerir) + +Örnekler: + +- macOS/Linux (Flutter): + ```bash + export PATH="$PATH:$HOME/flutter/bin" + which flutter && flutter --version + which dart && dart --version + ``` +- macOS/Linux (Dart SDK): + ```bash + export PATH="$PATH:$HOME/dart-sdk/bin" + which dart && dart --version + ``` +- Windows (PowerShell): Kullanıcı/Sistem PATH’ine `C:\\src\\flutter\\bin` (veya Flutter kurulu yolunuz) ekleyin. Doğrulama: + ```powershell + where flutter + where dart + ``` + +IDE notu: PATH’i değiştirdikten sonra IDE’nizi yeniden başlatın; commit işlemleri güncel ortam değişkenlerini miras almalıdır. + +CI doğrulaması: + +- GitHub Actions `check-format` workflow’u push/PR’larda `dart format --output=none --set-exit-if-changed .` çalıştırır ve format dışı dosyalar varsa job kırılır. + +Politika: + +- Hook’ları atlamayın (örn. `--no-verify`). Bu durumda da CI kırılacak ve yine formatlamanız gerekecektir. + +- Windows: +```shell +flutter run -d windows +``` + +- Android(emulator or gerçek cihaz): +```shell +flutter run -d "Pixel ..." +``` + +### Web Sürümü Geliştirme ve Dağıtım + +#### Yerel Geliştirme +```bash +# Bağımlılıkları yükle +flutter pub get + +# Web sürümünü yerel olarak çalıştır +flutter run -d chrome +# veya port belirterek +flutter run -d chrome --web-port 8080 +``` + +#### Web Sürümünü Oluşturma +```bash +# Üretim sürümünü oluştur +flutter build web + +# Alt dizin için temel yol belirterek oluştur +flutter build web --base-href /chatmcp/ +``` + +#### GitHub Pages'e Dağıtım +```bash +# 1. Web sürümünü oluştur +flutter build web --base-href /chatmcp/ + +# 2. build/web dizininin içeriğini gh-pages dalına gönder +# veya GitHub Actions ile otomatik dağıtım kullan +``` + +Oluşturma tamamlandıktan sonra, dosyalar `build/web` dizininde olacak ve herhangi bir statik web site barındırma hizmetine dağıtılabilir. + +## Uygulamanın Temel Özellikleri +* MCP Sunucusu ile Sohbet +* MCP Server Market +* MCP Sunucusunu Otomatik Kurulum +* SSE MCP Aktarım Desteği +* Otomatik MCP Sunucusu Seçimi +* Sohbet Geçmişi +* OpenAI LLM Modeli +* Claude LLM Modeli +* OLLama LLM Modeli +* DeepSeek LLM Modeli +* RAG (Retrieval-Augmented Generation) +* Daha İyi Arayüz Tasarımı +* Koyu/Açık Tema + +Her türlü özellik önerisine açığız. Fikirlerinizi veya bulduğunuz hataları [Issues](https://github.com/daodao97/chatmcp/issues) sayfasından bize iletebilirsiniz. + +## MCP Server Market +MCP Server Market'ten dilediğiniz MCP sunucusunu kurabilirsiniz. MCP Server Market, farklı veri türleriyle sohbet etmek için kullanabileceğiniz MCP sunucularının bir koleksiyonudur. + +* Ayrıca yeni MCP Server ekleyebilirsiniz : [MCP Server Market](https://github.com/chatmcpclient/mcp_server_market/blob/main/mcp_server_market.json) + +[mcp_server_market](https://github.com/chatmcpclient/mcp_server_market) deposunu forklayın ve `mcp_server_market.json` dosyasının sonuna yeni MCP Server ekleyin. + +```json +{ + "mcpServers": { + "existing-mcp-servers": {}, + "your-mcp-server": { + "command": "uvx", + "args": [ + "--from", + "git+https://github.com/username/your-mcp-server", + "your-mcp-server" + ] + } + } +} +``` +Değişikliklerinizi bir Pull Request göndererek paylaşabilirsiniz. PR onaylandıktan sonra MCP Server Market'te görünecektir ve diğer kullanıcılar da aynı anda kullanmaya başlayacaktır. + + +Geri bildirimleriniz, chatmcp'yi geliştirmemize ve diğer kullanıcıların bilinçli kararlar almasına yardımcı olur. + +* Teşekkürler +* MCP +* mcp-cli + +## Lisans +Bu proje Apache License 2.0 ile lisanslanmıştır. + +## GitHub Yıldız Geçmişi + +![](https://api.star-history.com/svg?repos=daodao97/chatmcp&type=Date) + diff --git a/README_ZH.md b/README_ZH.md new file mode 100644 index 0000000..e1be228 --- /dev/null +++ b/README_ZH.md @@ -0,0 +1,309 @@ +
+logo +

chatmcp

+ +跨平台 `MacOS | Windows | Linux | iOS | Android | Web` AI 聊天客户端 + +[English](./README.md) | 简体中文 | [Türkçe](./README_TR.md) + +
+ +## 安装 + +| 平台 | 链接 | 说明 | +|-----------------------------------------------------------|---------------------------------------------------------------|---------------------------------------------------------------| +| macOS | [Release](https://github.com/daodao97/chatmcp/releases) | | +| Windows | [Release](https://github.com/daodao97/chatmcp/releases) | | +| Linux | [Release](https://github.com/daodao97/chatmcp/releases) | 请参见下方“Linux 运行环境需求” ¹ | +| iOS | [TestFlight](https://testflight.apple.com/join/dCXksFJV) | | +| Android | [Release](https://github.com/daodao97/chatmcp/releases) | | +| Web | [GitHub Pages](https://daodao97.github.io/chatmcp) | 完全在浏览器中运行,使用本地存储保存聊天记录和设置 ² | + +¹ 提示:请参见下方“Linux 运行环境需求(Ubuntu 22.04 与 24.04)”。 + +² 注意:Web 版本完全在您的浏览器中运行,使用本地存储保存聊天记录和设置。 + +## 预览 + +![Artifact Display](./docs/preview/artifact.gif) +![Thinking Mode](./docs/preview/think.webp) +![Generate Image](./docs/preview/gen_img.webp) +![LaTeX Support](./docs/preview/latex.webp) +![HTML Preview](./docs/preview/html-preview.webp) +![Mermaid Diagram](./docs/preview/mermaid.webp) +![mcp workflow](./docs/preview/mcp-workerflow.webp) +![mcp inmemory](./docs/preview/mcp-inmemory.webp) +![MCP Tools](./docs/preview/mcp-tools.webp) +![LLM Provider](./docs/preview/llm-provider.webp) +![MCP Stdio](./docs/preview/mcp-stdio.webp) +![MCP SSE](./docs/preview/mcp-sse.webp) + +### 数据同步 + +ChatMCP 应用程序可以在同一局域网内同步数据 + +![Data sync](./docs/preview/data-sync.webp) + + +## 使用方法 + +确保您的系统中已安装 `uvx` 或 `npx` + +```bash +# uvx +brew install uv + +# npx +brew install node +``` + +### Linux 运行环境需求(Ubuntu 22.04 与 24.04) + +在 Ubuntu 及其衍生发行版上运行 ChatMCP 的 AppImage/DEB,请确保安装以下运行时依赖: + +- AppImage(FUSE):`libfuse2` +- GTK 3:`libgtk-3-0` +- 图形/EGL: + - Ubuntu 22.04:`libegl1-mesa`、`libgles2`、`libgl1-mesa-dri`、`libglx-mesa0` + - Ubuntu 24.04:`libegl1`、`libgles2`、`libgl1-mesa-dri`、`libglx-mesa0` +- 其他:`libx11-6`、`xdg-utils`、`libsqlite3-0` + +安装命令示例: + +- Ubuntu 22.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1-mesa libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 +``` + +- Ubuntu 24.04: +```bash +sudo apt install -y libfuse2 libgtk-3-0 libegl1 libgles2 libgl1-mesa-dri libglx-mesa0 libx11-6 xdg-utils libsqlite3-0 +``` + +可选(推荐):`mesa-vulkan-drivers`、`mesa-utils`(如 glxinfo 等诊断工具) + +1. 在"设置"页面配置您的 LLM API 密钥和端点 +2. 从"MCP 服务器"页面安装 MCP 服务器 +3. 与 MCP 服务器开始对话 + +- stdio mcp server +![](./docs/mcp_stdio.webp) + +- sse mcp server +![](./docs//mcp_sse.webp) + + +## 调试 + +- logs & data + +macOS: +```bash +~/Library/Application Support/ChatMcp +``` + +Windows: +```bash +%APPDATA%\ChatMcp +``` + +Linux: +```bash +~/.local/share/ChatMcp +``` + +Mobile: +- Application Documents Directory + +reset app can use this command + +macOS: +```bash +rm -rf ~/Library/Application\ Support/ChatMcp +``` + +Windows: +```bash +rd /s /q "%APPDATA%\ChatMcp" +``` + +Linux: +```bash +rm -rf ~/.local/share/ChatMcp +rm -rf ~/.local/share/run.daodao.chatmcp +``` + +## 开发 + +```bash +flutter pub get +flutter run -d macos +``` + +### 必要的代码格式化与 Pre-commit Hook + +为确保团队代码风格一致,本仓库在每次提交(commit)前强制执行 Dart 格式化。 + +- 仓库内提供了版本化的 Git 钩子:`.githooks/pre-commit` +- 在提交时会运行 `dart format .`,并重新 `git add` 变更的文件,然后执行只检查不输出的步骤,确保没有未格式化的文件。 +- 如果存在未格式化的文件,提交会在本地被阻止;此外,CI 也会拒绝不符合格式的 PR。 + +快速安装(每次克隆后执行一次): + +```bash +make setup-git-hooks +``` + +手动配置(备选): + +```bash +git config core.hooksPath .githooks +chmod +x .githooks/pre-commit +``` + +环境要求(PATH 中至少存在以下其一): + +- Dart SDK,或 +- Flutter(内置 Dart) + +示例: + +- macOS/Linux(Flutter): + ```bash + export PATH="$PATH:$HOME/flutter/bin" + which flutter && flutter --version + which dart && dart --version + ``` +- macOS/Linux(Dart SDK): + ```bash + export PATH="$PATH:$HOME/dart-sdk/bin" + which dart && dart --version + ``` +- Windows(PowerShell):将 `C:\\src\\flutter\\bin`(或您的 Flutter 路径)加入用户/系统 PATH。验证: + ```powershell + where flutter + where dart + ``` + +IDE 提示:修改 PATH 后请重启 IDE,使其在提交操作时继承最新的环境变量。 + +CI 校验: + +- GitHub Actions 工作流 `check-format` 会在 push/PR 时运行 `dart format --output=none --set-exit-if-changed .`,若有未格式化文件则任务失败。 + +政策: + +- 请不要绕过 hooks(例如使用 `--no-verify`)。即使绕过,本次 PR 也会在 CI 中失败,仍需格式化后再提交。 + +### Web版本开发和部署 + +#### 本地开发 +```bash +# 安装依赖 +flutter pub get + +# 本地运行Web版本 +flutter run -d chrome +# 或者指定端口 +flutter run -d chrome --web-port 8080 +``` + +#### 构建Web版本 +```bash +# 构建生产版本 +flutter build web + +# 构建并指定基础路径(用于部署到子目录) +flutter build web --base-href /chatmcp/ +``` + +#### 部署到GitHub Pages +```bash +# 1. 构建Web版本 +flutter build web --base-href /chatmcp/ + +# 2. 将build/web目录的内容推送到gh-pages分支 +# 或者使用GitHub Actions自动部署 +``` + +构建完成后,文件将在 `build/web` 目录中,可以部署到任何静态网站托管服务。 + +### Android 签名配置 + +如果您需要构建发布版本的 Android 应用,请配置签名: + +```bash +# 生成签名密钥 +./scripts/create_keystore.sh + +# 验证签名配置 +./scripts/verify_signing.sh + +# 构建签名的 APK +flutter build apk --release + +# 构建签名的 App Bundle(推荐用于 Google Play) +flutter build appbundle --release +``` + +详细的签名配置说明请参考:[Android 签名配置指南](./docs/android-signing.md) + +## 功能特性 + +- [x] 与 MCP 服务器对话 +- [ ] MCP 服务器市场 +- [ ] 自动安装 MCP 服务器 +- [x] SSE MCP 传输支持 +- [x] 自动选择 MCP 服务器 +- [x] 聊天历史 +- [x] OpenAI LLM 模型 +- [x] Claude LLM 模型 +- [x] OLLama LLM 模型 +- [x] DeepSeek LLM 模型 +- [ ] RAG +- [ ] 更好的 UI 设计 +- [x] 深色/浅色主题 + +欢迎提交任何功能建议,您可以在 [Issues](https://github.com/daodao97/chatmcp/issues) 中提交您的想法或错误报告。 + +## MCP 服务器市场 + +您可以从 MCP 服务器市场安装 MCP 服务器。MCP 服务器市场是 MCP 服务器的集合,您可以用它来与不同的数据进行对话。 + + +您也可以在 [MCP 服务器市场](https://github.com/chatmcpclient/mcp_server_market/blob/main/mcp_server_market.json) 中添加新的 MCP 服务器。 + +创建 [mcp_server_market](https://github.com/chatmcpclient/mcp_server_market) 的 fork 并添加您的 MCP 服务器到 `mcp_server_market.json` 文件的末尾。 + +```json +{ + "mcpServers": { + "existing-mcp-servers": {}, + "your-mcp-server": { + "command": "uvx", + "args": [ + "--from", + "git+https://github.com/username/your-mcp-server", + "your-mcp-server" + ] + } + } +} +``` +您可以向 [mcp_server_market](https://github.com/chatmcpclient/mcp_server_market) 仓库发送 Pull Request 以将您的 MCP 服务器添加到市场。在您的 PR 被合并后,您的 MCP 服务器将可在市场使用,其他用户可以立即使用它。 + +您的反馈有助于我们改进 chatmcp,也能帮助其他用户做出明智的决定。 + + +## 致谢 + +- [MCP](https://modelcontextprotocol.io/introduction) +- [mcp-cli](https://github.com/chrishayuk/mcp-cli) + +## 许可证 + +本项目采用 [Apache License 2.0](./LICENSE) 许可证。 + +## Star History + +![](https://api.star-history.com/svg?repos=daodao97/chatmcp&type=Date) \ No newline at end of file diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..2c94dba --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,37 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +# add dart formatter configuration +dart_code_metrics: + rules: + - maximum-line-length: 150 # set line width to 150 characters + +# set dart formatter line width +formatter: + page_width: 150 + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..578c3e2 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,103 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +// 从环境变量读取签名配置,支持优雅降级 +fun getEnvOrProperty(name: String): String? { + return System.getenv(name) ?: project.findProperty(name) as String? +} + +android { + namespace = "run.daodao.chatmcp" + compileSdk = flutter.compileSdkVersion + // ndkVersion = flutter.ndkVersion + // ndkVersion = "27.0.12077973" + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + // 签名配置 - 只有在环境变量存在时才创建 + signingConfigs { + create("release") { + val storeFile = getEnvOrProperty("SIGNING_STORE_PATH")?.let { file(it) } + val keyAlias = getEnvOrProperty("SIGNING_KEY_ALIAS") + val storePassword = getEnvOrProperty("SIGNING_STORE_PASSWORD") + val keyPassword = getEnvOrProperty("SIGNING_KEY_PASSWORD") + + // 只有在所有必要配置都存在时才设置签名 + if (storeFile != null && storeFile.exists() && + !keyAlias.isNullOrEmpty() && + !storePassword.isNullOrEmpty() && + !keyPassword.isNullOrEmpty()) { + this.storeFile = storeFile + this.keyAlias = keyAlias + this.storePassword = storePassword + this.keyPassword = keyPassword + println("✅ Release signing config loaded successfully") + } else { + println("⚠️ Release signing config incomplete or missing, will use debug signing") + } + } + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "run.daodao.chatmcp" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + // minSdk = flutter.minSdkVersion + minSdkVersion(24) + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // 智能选择签名配置 + val releaseSigningConfig = signingConfigs.getByName("release") + val hasValidSigning = try { + releaseSigningConfig.storeFile != null && + releaseSigningConfig.storeFile!!.exists() && + !releaseSigningConfig.keyAlias.isNullOrEmpty() && + !releaseSigningConfig.storePassword.isNullOrEmpty() && + !releaseSigningConfig.keyPassword.isNullOrEmpty() + } catch (e: Exception) { + false + } + + signingConfig = if (hasValidSigning) { + println("✅ Using release signing config") + releaseSigningConfig + } else { + println("⚠️ Using debug signing config") + signingConfigs.getByName("debug") + } + + // 开启代码压缩和混淆(仅在正式签名时) + isMinifyEnabled = hasValidSigning + isShrinkResources = hasValidSigning + if (hasValidSigning) { + proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") + } + } + + debug { + signingConfig = signingConfigs.getByName("debug") + isDebuggable = true + } + } +} + +flutter { + source = "../.." +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..c4d3a0c --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,72 @@ +# Flutter相关的混淆规则 +-keep class io.flutter.app.** { *; } +-keep class io.flutter.plugin.** { *; } +-keep class io.flutter.util.** { *; } +-keep class io.flutter.view.** { *; } +-keep class io.flutter.** { *; } +-keep class io.flutter.plugins.** { *; } + +# Dart相关 +-dontwarn io.flutter.embedding.** + +# 保留注解 +-keepattributes *Annotation* + +# 保留泛型信息 +-keepattributes Signature + +# 保留源文件名和行号信息(用于调试) +-keepattributes SourceFile,LineNumberTable + +# 混淆时不使用大小写混合类名 +-dontusemixedcaseclassnames + +# 不跳过非公共的库类 +-dontskipnonpubliclibraryclasses + +# 打印混淆的详细信息 +-verbose + +# 不做预检验,preverify是proguard的四个步骤之一 +-dontpreverify + +# 保留Serializable序列化的类不被混淆 +-keepclassmembers class * implements java.io.Serializable { + static final long serialVersionUID; + private static final java.io.ObjectStreamField[] serialPersistentFields; + private void writeObject(java.io.ObjectOutputStream); + private void readObject(java.io.ObjectInputStream); + java.lang.Object writeReplace(); + java.lang.Object readResolve(); +} + +# 保留Parcelable序列化的类不被混淆 +-keep class * implements android.os.Parcelable { + public static final android.os.Parcelable$Creator *; +} + +# 保留枚举类不被混淆 +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + +# 保留原生方法不被混淆 +-keepclasseswithmembernames class * { + native ; +} + +# 保留在Activity中的方法参数是view的方法 +-keepclassmembers class * extends android.app.Activity { + public void *(android.view.View); +} + +# WebView相关 +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} + +# 保留反射使用的类和方法 +-keep class * { + public ; +} \ No newline at end of file diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..118c649 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/run/daodao/chatmcp/MainActivity.kt b/android/app/src/main/kotlin/run/daodao/chatmcp/MainActivity.kt new file mode 100644 index 0000000..56697a7 --- /dev/null +++ b/android/app/src/main/kotlin/run/daodao/chatmcp/MainActivity.kt @@ -0,0 +1,5 @@ +package run.daodao.chatmcp + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/launcher_icon.png b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png new file mode 100644 index 0000000..16ada2c Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/launcher_icon.png b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png new file mode 100644 index 0000000..9960620 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png new file mode 100644 index 0000000..dc3bd95 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png new file mode 100644 index 0000000..59abc8c Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png new file mode 100644 index 0000000..775e969 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..b6600c4 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,48 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +subprojects { + project.plugins.withId("org.jetbrains.kotlin.android") { + project.extensions.findByType()?.apply { + jvmToolchain(17) + } + } + + // 强制所有子项目使用相同的 Kotlin 编译选项 + afterEvaluate { + if (extensions.findByName("android") != null) { + extensions.configure { + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + } + } + + tasks.withType().configureEach { + kotlinOptions { + jvmTarget = "17" + } + } + } +} + +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} + +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..f3388b2 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,7 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true + +# Kotlin 编译选项 - 确保所有模块使用相同的 JVM 目标 +kotlin.jvm.target.validation.mode=warning +org.jetbrains.kotlin.gradle.tasks.KotlinCompile.jvmTarget=17 diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..afa1e8e --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..f5f071d --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + val flutterSdkPath = run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.7.0" apply false + id("org.jetbrains.kotlin.android") version "2.0.21" apply false +} + +include(":app") diff --git a/assets/js/turndown.js b/assets/js/turndown.js new file mode 100644 index 0000000..e86fb18 --- /dev/null +++ b/assets/js/turndown.js @@ -0,0 +1,974 @@ +var TurndownService = (function () { + 'use strict'; + + function extend (destination) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + for (var key in source) { + if (source.hasOwnProperty(key)) destination[key] = source[key]; + } + } + return destination + } + + function repeat (character, count) { + return Array(count + 1).join(character) + } + + function trimLeadingNewlines (string) { + return string.replace(/^\n*/, '') + } + + function trimTrailingNewlines (string) { + // avoid match-at-end regexp bottleneck, see #370 + var indexEnd = string.length; + while (indexEnd > 0 && string[indexEnd - 1] === '\n') indexEnd--; + return string.substring(0, indexEnd) + } + + var blockElements = [ + 'ADDRESS', 'ARTICLE', 'ASIDE', 'AUDIO', 'BLOCKQUOTE', 'BODY', 'CANVAS', + 'CENTER', 'DD', 'DIR', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE', + 'FOOTER', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', + 'HGROUP', 'HR', 'HTML', 'ISINDEX', 'LI', 'MAIN', 'MENU', 'NAV', 'NOFRAMES', + 'NOSCRIPT', 'OL', 'OUTPUT', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TD', + 'TFOOT', 'TH', 'THEAD', 'TR', 'UL' + ]; + + function isBlock (node) { + return is(node, blockElements) + } + + var voidElements = [ + 'AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT', + 'KEYGEN', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR' + ]; + + function isVoid (node) { + return is(node, voidElements) + } + + function hasVoid (node) { + return has(node, voidElements) + } + + var meaningfulWhenBlankElements = [ + 'A', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TH', 'TD', 'IFRAME', 'SCRIPT', + 'AUDIO', 'VIDEO' + ]; + + function isMeaningfulWhenBlank (node) { + return is(node, meaningfulWhenBlankElements) + } + + function hasMeaningfulWhenBlank (node) { + return has(node, meaningfulWhenBlankElements) + } + + function is (node, tagNames) { + return tagNames.indexOf(node.nodeName) >= 0 + } + + function has (node, tagNames) { + return ( + node.getElementsByTagName && + tagNames.some(function (tagName) { + return node.getElementsByTagName(tagName).length + }) + ) + } + + var rules = {}; + + rules.paragraph = { + filter: 'p', + + replacement: function (content) { + return '\n\n' + content + '\n\n' + } + }; + + rules.lineBreak = { + filter: 'br', + + replacement: function (content, node, options) { + return options.br + '\n' + } + }; + + rules.heading = { + filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'], + + replacement: function (content, node, options) { + var hLevel = Number(node.nodeName.charAt(1)); + + if (options.headingStyle === 'setext' && hLevel < 3) { + var underline = repeat((hLevel === 1 ? '=' : '-'), content.length); + return ( + '\n\n' + content + '\n' + underline + '\n\n' + ) + } else { + return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n' + } + } + }; + + rules.blockquote = { + filter: 'blockquote', + + replacement: function (content) { + content = content.replace(/^\n+|\n+$/g, ''); + content = content.replace(/^/gm, '> '); + return '\n\n' + content + '\n\n' + } + }; + + rules.list = { + filter: ['ul', 'ol'], + + replacement: function (content, node) { + var parent = node.parentNode; + if (parent.nodeName === 'LI' && parent.lastElementChild === node) { + return '\n' + content + } else { + return '\n\n' + content + '\n\n' + } + } + }; + + rules.listItem = { + filter: 'li', + + replacement: function (content, node, options) { + content = content + .replace(/^\n+/, '') // remove leading newlines + .replace(/\n+$/, '\n') // replace trailing newlines with just a single one + .replace(/\n/gm, '\n '); // indent + var prefix = options.bulletListMarker + ' '; + var parent = node.parentNode; + if (parent.nodeName === 'OL') { + var start = parent.getAttribute('start'); + var index = Array.prototype.indexOf.call(parent.children, node); + prefix = (start ? Number(start) + index : index + 1) + '. '; + } + return ( + prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '') + ) + } + }; + + rules.indentedCodeBlock = { + filter: function (node, options) { + return ( + options.codeBlockStyle === 'indented' && + node.nodeName === 'PRE' && + node.firstChild && + node.firstChild.nodeName === 'CODE' + ) + }, + + replacement: function (content, node, options) { + return ( + '\n\n ' + + node.firstChild.textContent.replace(/\n/g, '\n ') + + '\n\n' + ) + } + }; + + rules.fencedCodeBlock = { + filter: function (node, options) { + return ( + options.codeBlockStyle === 'fenced' && + node.nodeName === 'PRE' && + node.firstChild && + node.firstChild.nodeName === 'CODE' + ) + }, + + replacement: function (content, node, options) { + var className = node.firstChild.getAttribute('class') || ''; + var language = (className.match(/language-(\S+)/) || [null, ''])[1]; + var code = node.firstChild.textContent; + + var fenceChar = options.fence.charAt(0); + var fenceSize = 3; + var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm'); + + var match; + while ((match = fenceInCodeRegex.exec(code))) { + if (match[0].length >= fenceSize) { + fenceSize = match[0].length + 1; + } + } + + var fence = repeat(fenceChar, fenceSize); + + return ( + '\n\n' + fence + language + '\n' + + code.replace(/\n$/, '') + + '\n' + fence + '\n\n' + ) + } + }; + + rules.horizontalRule = { + filter: 'hr', + + replacement: function (content, node, options) { + return '\n\n' + options.hr + '\n\n' + } + }; + + rules.inlineLink = { + filter: function (node, options) { + return ( + options.linkStyle === 'inlined' && + node.nodeName === 'A' && + node.getAttribute('href') + ) + }, + + replacement: function (content, node) { + var href = node.getAttribute('href'); + if (href) href = href.replace(/([()])/g, '\\$1'); + var title = cleanAttribute(node.getAttribute('title')); + if (title) title = ' "' + title.replace(/"/g, '\\"') + '"'; + return '[' + content + '](' + href + title + ')' + } + }; + + rules.referenceLink = { + filter: function (node, options) { + return ( + options.linkStyle === 'referenced' && + node.nodeName === 'A' && + node.getAttribute('href') + ) + }, + + replacement: function (content, node, options) { + var href = node.getAttribute('href'); + var title = cleanAttribute(node.getAttribute('title')); + if (title) title = ' "' + title + '"'; + var replacement; + var reference; + + switch (options.linkReferenceStyle) { + case 'collapsed': + replacement = '[' + content + '][]'; + reference = '[' + content + ']: ' + href + title; + break + case 'shortcut': + replacement = '[' + content + ']'; + reference = '[' + content + ']: ' + href + title; + break + default: + var id = this.references.length + 1; + replacement = '[' + content + '][' + id + ']'; + reference = '[' + id + ']: ' + href + title; + } + + this.references.push(reference); + return replacement + }, + + references: [], + + append: function (options) { + var references = ''; + if (this.references.length) { + references = '\n\n' + this.references.join('\n') + '\n\n'; + this.references = []; // Reset references + } + return references + } + }; + + rules.emphasis = { + filter: ['em', 'i'], + + replacement: function (content, node, options) { + if (!content.trim()) return '' + return options.emDelimiter + content + options.emDelimiter + } + }; + + rules.strong = { + filter: ['strong', 'b'], + + replacement: function (content, node, options) { + if (!content.trim()) return '' + return options.strongDelimiter + content + options.strongDelimiter + } + }; + + rules.code = { + filter: function (node) { + var hasSiblings = node.previousSibling || node.nextSibling; + var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings; + + return node.nodeName === 'CODE' && !isCodeBlock + }, + + replacement: function (content) { + if (!content) return '' + content = content.replace(/\r?\n|\r/g, ' '); + + var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? ' ' : ''; + var delimiter = '`'; + var matches = content.match(/`+/gm) || []; + while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`'; + + return delimiter + extraSpace + content + extraSpace + delimiter + } + }; + + rules.image = { + filter: 'img', + + replacement: function (content, node) { + var alt = cleanAttribute(node.getAttribute('alt')); + var src = node.getAttribute('src') || ''; + var title = cleanAttribute(node.getAttribute('title')); + var titlePart = title ? ' "' + title + '"' : ''; + return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : '' + } + }; + + function cleanAttribute (attribute) { + return attribute ? attribute.replace(/(\n+\s*)+/g, '\n') : '' + } + + /** + * Manages a collection of rules used to convert HTML to Markdown + */ + + function Rules (options) { + this.options = options; + this._keep = []; + this._remove = []; + + this.blankRule = { + replacement: options.blankReplacement + }; + + this.keepReplacement = options.keepReplacement; + + this.defaultRule = { + replacement: options.defaultReplacement + }; + + this.array = []; + for (var key in options.rules) this.array.push(options.rules[key]); + } + + Rules.prototype = { + add: function (key, rule) { + this.array.unshift(rule); + }, + + keep: function (filter) { + this._keep.unshift({ + filter: filter, + replacement: this.keepReplacement + }); + }, + + remove: function (filter) { + this._remove.unshift({ + filter: filter, + replacement: function () { + return '' + } + }); + }, + + forNode: function (node) { + if (node.isBlank) return this.blankRule + var rule; + + if ((rule = findRule(this.array, node, this.options))) return rule + if ((rule = findRule(this._keep, node, this.options))) return rule + if ((rule = findRule(this._remove, node, this.options))) return rule + + return this.defaultRule + }, + + forEach: function (fn) { + for (var i = 0; i < this.array.length; i++) fn(this.array[i], i); + } + }; + + function findRule (rules, node, options) { + for (var i = 0; i < rules.length; i++) { + var rule = rules[i]; + if (filterValue(rule, node, options)) return rule + } + return void 0 + } + + function filterValue (rule, node, options) { + var filter = rule.filter; + if (typeof filter === 'string') { + if (filter === node.nodeName.toLowerCase()) return true + } else if (Array.isArray(filter)) { + if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true + } else if (typeof filter === 'function') { + if (filter.call(rule, node, options)) return true + } else { + throw new TypeError('`filter` needs to be a string, array, or function') + } + } + + /** + * The collapseWhitespace function is adapted from collapse-whitespace + * by Luc Thevenard. + * + * The MIT License (MIT) + * + * Copyright (c) 2014 Luc Thevenard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + /** + * collapseWhitespace(options) removes extraneous whitespace from an the given element. + * + * @param {Object} options + */ + function collapseWhitespace (options) { + var element = options.element; + var isBlock = options.isBlock; + var isVoid = options.isVoid; + var isPre = options.isPre || function (node) { + return node.nodeName === 'PRE' + }; + + if (!element.firstChild || isPre(element)) return + + var prevText = null; + var keepLeadingWs = false; + + var prev = null; + var node = next(prev, element, isPre); + + while (node !== element) { + if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE + var text = node.data.replace(/[ \r\n\t]+/g, ' '); + + if ((!prevText || / $/.test(prevText.data)) && + !keepLeadingWs && text[0] === ' ') { + text = text.substr(1); + } + + // `text` might be empty at this point. + if (!text) { + node = remove(node); + continue + } + + node.data = text; + + prevText = node; + } else if (node.nodeType === 1) { // Node.ELEMENT_NODE + if (isBlock(node) || node.nodeName === 'BR') { + if (prevText) { + prevText.data = prevText.data.replace(/ $/, ''); + } + + prevText = null; + keepLeadingWs = false; + } else if (isVoid(node) || isPre(node)) { + // Avoid trimming space around non-block, non-BR void elements and inline PRE. + prevText = null; + keepLeadingWs = true; + } else if (prevText) { + // Drop protection if set previously. + keepLeadingWs = false; + } + } else { + node = remove(node); + continue + } + + var nextNode = next(prev, node, isPre); + prev = node; + node = nextNode; + } + + if (prevText) { + prevText.data = prevText.data.replace(/ $/, ''); + if (!prevText.data) { + remove(prevText); + } + } + } + + /** + * remove(node) removes the given node from the DOM and returns the + * next node in the sequence. + * + * @param {Node} node + * @return {Node} node + */ + function remove (node) { + var next = node.nextSibling || node.parentNode; + + node.parentNode.removeChild(node); + + return next + } + + /** + * next(prev, current, isPre) returns the next node in the sequence, given the + * current and previous nodes. + * + * @param {Node} prev + * @param {Node} current + * @param {Function} isPre + * @return {Node} + */ + function next (prev, current, isPre) { + if ((prev && prev.parentNode === current) || isPre(current)) { + return current.nextSibling || current.parentNode + } + + return current.firstChild || current.nextSibling || current.parentNode + } + + /* + * Set up window for Node.js + */ + + var root = (typeof window !== 'undefined' ? window : {}); + + /* + * Parsing HTML strings + */ + + function canParseHTMLNatively () { + var Parser = root.DOMParser; + var canParse = false; + + // Adapted from https://gist.github.com/1129031 + // Firefox/Opera/IE throw errors on unsupported types + try { + // WebKit returns null on unsupported types + if (new Parser().parseFromString('', 'text/html')) { + canParse = true; + } + } catch (e) {} + + return canParse + } + + function createHTMLParser () { + var Parser = function () {}; + + { + if (shouldUseActiveX()) { + Parser.prototype.parseFromString = function (string) { + var doc = new window.ActiveXObject('htmlfile'); + doc.designMode = 'on'; // disable on-page scripts + doc.open(); + doc.write(string); + doc.close(); + return doc + }; + } else { + Parser.prototype.parseFromString = function (string) { + var doc = document.implementation.createHTMLDocument(''); + doc.open(); + doc.write(string); + doc.close(); + return doc + }; + } + } + return Parser + } + + function shouldUseActiveX () { + var useActiveX = false; + try { + document.implementation.createHTMLDocument('').open(); + } catch (e) { + if (root.ActiveXObject) useActiveX = true; + } + return useActiveX + } + + var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser(); + + function RootNode (input, options) { + var root; + if (typeof input === 'string') { + var doc = htmlParser().parseFromString( + // DOM parsers arrange elements in the and . + // Wrapping in a custom element ensures elements are reliably arranged in + // a single element. + '' + input + '', + 'text/html' + ); + root = doc.getElementById('turndown-root'); + } else { + root = input.cloneNode(true); + } + collapseWhitespace({ + element: root, + isBlock: isBlock, + isVoid: isVoid, + isPre: options.preformattedCode ? isPreOrCode : null + }); + + return root + } + + var _htmlParser; + function htmlParser () { + _htmlParser = _htmlParser || new HTMLParser(); + return _htmlParser + } + + function isPreOrCode (node) { + return node.nodeName === 'PRE' || node.nodeName === 'CODE' + } + + function Node (node, options) { + node.isBlock = isBlock(node); + node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode; + node.isBlank = isBlank(node); + node.flankingWhitespace = flankingWhitespace(node, options); + return node + } + + function isBlank (node) { + return ( + !isVoid(node) && + !isMeaningfulWhenBlank(node) && + /^\s*$/i.test(node.textContent) && + !hasVoid(node) && + !hasMeaningfulWhenBlank(node) + ) + } + + function flankingWhitespace (node, options) { + if (node.isBlock || (options.preformattedCode && node.isCode)) { + return { leading: '', trailing: '' } + } + + var edges = edgeWhitespace(node.textContent); + + // abandon leading ASCII WS if left-flanked by ASCII WS + if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) { + edges.leading = edges.leadingNonAscii; + } + + // abandon trailing ASCII WS if right-flanked by ASCII WS + if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) { + edges.trailing = edges.trailingNonAscii; + } + + return { leading: edges.leading, trailing: edges.trailing } + } + + function edgeWhitespace (string) { + var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/); + return { + leading: m[1], // whole string for whitespace-only strings + leadingAscii: m[2], + leadingNonAscii: m[3], + trailing: m[4], // empty for whitespace-only strings + trailingNonAscii: m[5], + trailingAscii: m[6] + } + } + + function isFlankedByWhitespace (side, node, options) { + var sibling; + var regExp; + var isFlanked; + + if (side === 'left') { + sibling = node.previousSibling; + regExp = / $/; + } else { + sibling = node.nextSibling; + regExp = /^ /; + } + + if (sibling) { + if (sibling.nodeType === 3) { + isFlanked = regExp.test(sibling.nodeValue); + } else if (options.preformattedCode && sibling.nodeName === 'CODE') { + isFlanked = false; + } else if (sibling.nodeType === 1 && !isBlock(sibling)) { + isFlanked = regExp.test(sibling.textContent); + } + } + return isFlanked + } + + var reduce = Array.prototype.reduce; + var escapes = [ + [/\\/g, '\\\\'], + [/\*/g, '\\*'], + [/^-/g, '\\-'], + [/^\+ /g, '\\+ '], + [/^(=+)/g, '\\$1'], + [/^(#{1,6}) /g, '\\$1 '], + [/`/g, '\\`'], + [/^~~~/g, '\\~~~'], + [/\[/g, '\\['], + [/\]/g, '\\]'], + [/^>/g, '\\>'], + [/_/g, '\\_'], + [/^(\d+)\. /g, '$1\\. '] + ]; + + function TurndownService (options) { + if (!(this instanceof TurndownService)) return new TurndownService(options) + + var defaults = { + rules: rules, + headingStyle: 'setext', + hr: '* * *', + bulletListMarker: '*', + codeBlockStyle: 'indented', + fence: '```', + emDelimiter: '_', + strongDelimiter: '**', + linkStyle: 'inlined', + linkReferenceStyle: 'full', + br: ' ', + preformattedCode: false, + blankReplacement: function (content, node) { + return node.isBlock ? '\n\n' : '' + }, + keepReplacement: function (content, node) { + return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML + }, + defaultReplacement: function (content, node) { + return node.isBlock ? '\n\n' + content + '\n\n' : content + } + }; + this.options = extend({}, defaults, options); + this.rules = new Rules(this.options); + } + + TurndownService.prototype = { + /** + * The entry point for converting a string or DOM node to Markdown + * @public + * @param {String|HTMLElement} input The string or DOM node to convert + * @returns A Markdown representation of the input + * @type String + */ + + turndown: function (input) { + if (!canConvert(input)) { + throw new TypeError( + input + ' is not a string, or an element/document/fragment node.' + ) + } + + if (input === '') return '' + + var output = process.call(this, new RootNode(input, this.options)); + return postProcess.call(this, output) + }, + + /** + * Add one or more plugins + * @public + * @param {Function|Array} plugin The plugin or array of plugins to add + * @returns The Turndown instance for chaining + * @type Object + */ + + use: function (plugin) { + if (Array.isArray(plugin)) { + for (var i = 0; i < plugin.length; i++) this.use(plugin[i]); + } else if (typeof plugin === 'function') { + plugin(this); + } else { + throw new TypeError('plugin must be a Function or an Array of Functions') + } + return this + }, + + /** + * Adds a rule + * @public + * @param {String} key The unique key of the rule + * @param {Object} rule The rule + * @returns The Turndown instance for chaining + * @type Object + */ + + addRule: function (key, rule) { + this.rules.add(key, rule); + return this + }, + + /** + * Keep a node (as HTML) that matches the filter + * @public + * @param {String|Array|Function} filter The unique key of the rule + * @returns The Turndown instance for chaining + * @type Object + */ + + keep: function (filter) { + this.rules.keep(filter); + return this + }, + + /** + * Remove a node that matches the filter + * @public + * @param {String|Array|Function} filter The unique key of the rule + * @returns The Turndown instance for chaining + * @type Object + */ + + remove: function (filter) { + this.rules.remove(filter); + return this + }, + + /** + * Escapes Markdown syntax + * @public + * @param {String} string The string to escape + * @returns A string with Markdown syntax escaped + * @type String + */ + + escape: function (string) { + return escapes.reduce(function (accumulator, escape) { + return accumulator.replace(escape[0], escape[1]) + }, string) + } + }; + + /** + * Reduces a DOM node down to its Markdown string equivalent + * @private + * @param {HTMLElement} parentNode The node to convert + * @returns A Markdown representation of the node + * @type String + */ + + function process (parentNode) { + var self = this; + return reduce.call(parentNode.childNodes, function (output, node) { + node = new Node(node, self.options); + + var replacement = ''; + if (node.nodeType === 3) { + replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue); + } else if (node.nodeType === 1) { + replacement = replacementForNode.call(self, node); + } + + return join(output, replacement) + }, '') + } + + /** + * Appends strings as each rule requires and trims the output + * @private + * @param {String} output The conversion output + * @returns A trimmed version of the ouput + * @type String + */ + + function postProcess (output) { + var self = this; + this.rules.forEach(function (rule) { + if (typeof rule.append === 'function') { + output = join(output, rule.append(self.options)); + } + }); + + return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '') + } + + /** + * Converts an element node to its Markdown equivalent + * @private + * @param {HTMLElement} node The node to convert + * @returns A Markdown representation of the node + * @type String + */ + + function replacementForNode (node) { + var rule = this.rules.forNode(node); + var content = process.call(this, node); + var whitespace = node.flankingWhitespace; + if (whitespace.leading || whitespace.trailing) content = content.trim(); + return ( + whitespace.leading + + rule.replacement(content, node, this.options) + + whitespace.trailing + ) + } + + /** + * Joins replacement to the current output with appropriate number of new lines + * @private + * @param {String} output The current conversion output + * @param {String} replacement The string to append to the output + * @returns Joined output + * @type String + */ + + function join (output, replacement) { + var s1 = trimTrailingNewlines(output); + var s2 = trimLeadingNewlines(replacement); + var nls = Math.max(output.length - s1.length, replacement.length - s2.length); + var separator = '\n\n'.substring(0, nls); + + return s1 + separator + s2 + } + + /** + * Determines whether an input can be converted + * @private + * @param {String|HTMLElement} input Describe this parameter + * @returns Describe what it returns + * @type String|Object|Array|Boolean|Number + */ + + function canConvert (input) { + return ( + input != null && ( + typeof input === 'string' || + (input.nodeType && ( + input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11 + )) + ) + ) + } + + return TurndownService; + +}()); diff --git a/assets/logo.png b/assets/logo.png new file mode 100644 index 0000000..18a2bc4 Binary files /dev/null and b/assets/logo.png differ diff --git a/assets/logo/302ai.svg b/assets/logo/302ai.svg new file mode 100644 index 0000000..6874166 --- /dev/null +++ b/assets/logo/302ai.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/logo/ai-chip.svg b/assets/logo/ai-chip.svg new file mode 100644 index 0000000..1775718 --- /dev/null +++ b/assets/logo/ai-chip.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/logo/claude.svg b/assets/logo/claude.svg new file mode 100644 index 0000000..d300701 --- /dev/null +++ b/assets/logo/claude.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/logo/copilot.svg b/assets/logo/copilot.svg new file mode 100644 index 0000000..7cb1538 --- /dev/null +++ b/assets/logo/copilot.svg @@ -0,0 +1,61 @@ + + + + + + + image/svg+xml + + + + + + + + + diff --git a/assets/logo/deepseek.svg b/assets/logo/deepseek.svg new file mode 100644 index 0000000..e177494 --- /dev/null +++ b/assets/logo/deepseek.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/logo/foundry.svg b/assets/logo/foundry.svg new file mode 100644 index 0000000..f73116f --- /dev/null +++ b/assets/logo/foundry.svg @@ -0,0 +1 @@ +Azure AI FoundryYour platform to build generative AI solutions and custom copilots \ No newline at end of file diff --git a/assets/logo/gemini.svg b/assets/logo/gemini.svg new file mode 100644 index 0000000..1f6cf95 --- /dev/null +++ b/assets/logo/gemini.svg @@ -0,0 +1 @@ +Gemini \ No newline at end of file diff --git a/assets/logo/github.svg b/assets/logo/github.svg new file mode 100644 index 0000000..4df6bde --- /dev/null +++ b/assets/logo/github.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/logo/grok.svg b/assets/logo/grok.svg new file mode 100644 index 0000000..1f6cf95 --- /dev/null +++ b/assets/logo/grok.svg @@ -0,0 +1 @@ +Gemini \ No newline at end of file diff --git a/assets/logo/ollama.svg b/assets/logo/ollama.svg new file mode 100644 index 0000000..d778086 --- /dev/null +++ b/assets/logo/ollama.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/logo/openai.svg b/assets/logo/openai.svg new file mode 100644 index 0000000..594a890 --- /dev/null +++ b/assets/logo/openai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/logo/openrouter.svg b/assets/logo/openrouter.svg new file mode 100644 index 0000000..c9952c1 --- /dev/null +++ b/assets/logo/openrouter.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/assets/logo_256.png b/assets/logo_256.png new file mode 100644 index 0000000..114b06c Binary files /dev/null and b/assets/logo_256.png differ diff --git a/assets/mcp_server.json b/assets/mcp_server.json new file mode 100644 index 0000000..80ef9c4 --- /dev/null +++ b/assets/mcp_server.json @@ -0,0 +1,4 @@ +{ + "mcpServers": { + } +} \ No newline at end of file diff --git a/assets/sandbox/index.html b/assets/sandbox/index.html new file mode 100644 index 0000000..a32aa2d --- /dev/null +++ b/assets/sandbox/index.html @@ -0,0 +1,112 @@ + + + + + + Sandbox Preview + + + + + + + +
+ +
+ + + + + \ No newline at end of file diff --git a/assets/test.db b/assets/test.db new file mode 100644 index 0000000..e69199c Binary files /dev/null and b/assets/test.db differ diff --git a/assets/test.png b/assets/test.png new file mode 100644 index 0000000..03e3c42 Binary files /dev/null and b/assets/test.png differ diff --git a/distribute_options.yaml b/distribute_options.yaml new file mode 100644 index 0000000..0251699 --- /dev/null +++ b/distribute_options.yaml @@ -0,0 +1,90 @@ +# Fastforge Config +# Reference: https://github.com/fastforgedev/fastforge +# Usage: fastforge release --name=dev + +output: dist/ +releases: + - name: linux + jobs: + # Linux DEB Package Build (Debian/Ubuntu) + - name: release-linux-deb + package: + platform: linux + target: deb + build_args: + dart-define: + APP_ENV: production + + # Linux RPM Package Build (Red Hat/CentOS/Fedora) + - name: release-linux-rpm + package: + platform: linux + target: rpm + build_args: + dart-define: + APP_ENV: production + + # Linux AppImage Package Build (Portable) + - name: release-linux-appimage + package: + platform: linux + target: appimage + build_args: + dart-define: + APP_ENV: production + + - name: android + jobs: + # Android APK Build + - name: release-android-apk + package: + platform: android + target: apk + build_args: + target-platform: android-arm,android-arm64 + dart-define: + APP_ENV: production + + - name: windows + jobs: + # Windows ZIP Package Build + - name: release-windows-zip + package: + platform: windows + target: zip + build_args: + dart-define: + APP_ENV: production + # Add extra file configuration + extra_files: + - source: "windows/sqlite3.dll" + destination: "sqlite3.dll" + - name: release-windows-msix + package: + platform: windows + target: msix + build_args: + dart-define: + APP_ENV: production + + - name: macos + jobs: + # macOS DMG Build + - name: release-macos-dmg + package: + platform: macos + target: dmg + build_args: + dart-define: + APP_ENV: production + + - name: web + jobs: + # Web Build + - name: release-web-tarball + package: + platform: web + target: tar.gz + build_args: + dart-define: + APP_ENV: production diff --git a/docs/android-signing.md b/docs/android-signing.md new file mode 100644 index 0000000..3bac617 --- /dev/null +++ b/docs/android-signing.md @@ -0,0 +1,176 @@ +# Android 应用签名配置指南 + +本文档介绍如何为 ChatMcp Android 应用配置签名,以便发布到 Google Play Store 或其他应用商店。 + +## 📋 目录 + +- [本地开发环境配置](#本地开发环境配置) +- [GitHub Actions 配置](#github-actions-配置) +- [签名验证](#签名验证) +- [常见问题](#常见问题) + +## 🔧 本地开发环境配置 + +### 1. 生成签名密钥 + +运行以下命令生成签名密钥: + +```bash +./scripts/create_keystore.sh +``` + +脚本会引导您完成以下步骤: +- 输入密钥库文件名(默认:`chatmcp-release-key.jks`) +- 输入密钥别名(默认:`chatmcp`) +- 设置密钥库密码和密钥密码 +- 输入证书信息(姓名、组织等) + +### 2. 配置环境变量 + +脚本会自动创建 `android/signing.env` 文件,包含以下配置: + +```bash +SIGNING_STORE_PATH=keystore/chatmcp-release-key.jks +SIGNING_KEY_ALIAS=chatmcp +SIGNING_STORE_PASSWORD=your_store_password +SIGNING_KEY_PASSWORD=your_key_password +``` + +### 3. 本地构建签名 APK + +```bash +# 构建签名的 APK +flutter build apk --release + +# 构建签名的 App Bundle(推荐用于 Google Play) +flutter build appbundle --release +``` + +## 🚀 GitHub Actions 配置 + +### 1. 设置 GitHub Secrets + +在您的 GitHub 仓库中,转到 `Settings` > `Secrets and variables` > `Actions`,添加以下 secrets: + +| Secret 名称 | 描述 | 示例值 | +|------------|------|--------| +| `SIGNING_KEYSTORE` | 密钥库文件的 base64 编码 | `MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...` | +| `SIGNING_KEY_ALIAS` | 密钥别名 | `chatmcp` | +| `SIGNING_STORE_PASSWORD` | 密钥库密码 | `your_store_password` | +| `SIGNING_KEY_PASSWORD` | 密钥密码 | `your_key_password` | + +### 2. 生成密钥库的 base64 编码 + +根据您的操作系统,使用以下命令之一: + +**macOS:** +```bash +base64 -i android/app/keystore/chatmcp-release-key.jks | pbcopy +``` + +**Linux:** +```bash +base64 -w 0 android/app/keystore/chatmcp-release-key.jks | xclip -selection clipboard +``` + +**Windows:** +```cmd +certutil -encode android/app/keystore/chatmcp-release-key.jks temp.base64 && type temp.base64 | clip && del temp.base64 +``` + +### 3. 触发构建 + +GitHub Actions 会在以下情况下自动构建签名的 Android 应用: + +- 推送带有 `v*` 标签的提交(如 `v1.0.0`) +- 手动触发工作流程 + +构建完成后,您可以在以下位置找到文件: +- **Artifacts**: 每次构建的临时文件 +- **Releases**: 标签构建的正式发布文件 + +## ✅ 签名验证 + +### 验证 APK 签名 + +使用以下命令验证 APK 是否正确签名: + +```bash +# 查看 APK 签名信息 +keytool -printcert -jarfile build/app/outputs/flutter-apk/app-release.apk + +# 验证 APK 签名 +jarsigner -verify -verbose -certs build/app/outputs/flutter-apk/app-release.apk +``` + +### 验证 App Bundle 签名 + +```bash +# 使用 bundletool 验证 AAB 文件 +java -jar bundletool.jar validate --bundle=build/app/outputs/bundle/release/app-release.aab +``` + +## 🔒 安全最佳实践 + +1. **密钥安全**: + - 将密钥库文件保存在安全的位置 + - 定期备份密钥库文件 + - 不要将密钥库文件提交到版本控制系统 + +2. **密码管理**: + - 使用强密码 + - 将密码存储在安全的密码管理器中 + - 定期更换密码 + +3. **访问控制**: + - 限制对 GitHub Secrets 的访问权限 + - 定期审查有权访问签名密钥的人员 + +## 🛠️ 常见问题 + +### Q: 构建时提示 "签名配置不完整" + +**A**: 检查以下项目: +- 确保所有 GitHub Secrets 都已正确设置 +- 验证密钥库文件的 base64 编码是否正确 +- 确认密钥别名和密码是否匹配 + +### Q: 如何更新签名密钥? + +**A**: +1. 生成新的密钥库文件 +2. 更新 GitHub Secrets 中的相关值 +3. 重新构建应用 + +**注意**: 更换签名密钥后,用户需要卸载旧版本才能安装新版本。 + +### Q: 如何为不同环境使用不同的签名? + +**A**: 可以创建多个构建变体: +- `debug`: 使用调试签名 +- `release`: 使用发布签名 +- `staging`: 使用测试签名 + +### Q: App Bundle 和 APK 有什么区别? + +**A**: +- **APK**: 传统的 Android 应用包格式,包含所有架构的代码 +- **App Bundle**: Google 推荐的格式,支持动态交付,用户只下载适合其设备的代码 + +## 📚 相关资源 + +- [Android 应用签名官方文档](https://developer.android.com/studio/publish/app-signing) +- [Flutter Android 构建文档](https://docs.flutter.dev/deployment/android) +- [Google Play 发布指南](https://developer.android.com/distribute/googleplay) + +## 🆘 获取帮助 + +如果您在配置过程中遇到问题,请: + +1. 检查本文档的常见问题部分 +2. 查看 GitHub Actions 的构建日志 +3. 在项目仓库中创建 Issue + +--- + +**重要提醒**: 请妥善保管您的签名密钥,丢失密钥将导致无法更新已发布的应用! \ No newline at end of file diff --git a/docs/mcp_oauth_servers.md b/docs/mcp_oauth_servers.md new file mode 100644 index 0000000..8c75d7a --- /dev/null +++ b/docs/mcp_oauth_servers.md @@ -0,0 +1,94 @@ +# OAuth 2.0 + PKCE Auto-Discovery for MCP Servers + +This feature adds automatic OAuth 2.0 authentication support for remote MCP servers, enabling seamless integration with OAuth-protected services like Notion MCP and Atlassian MCP. + +## Features + +- **🔍 Auto-Discovery**: Automatically detects OAuth requirements using RFC 8414 (OAuth 2.0 Authorization Server Metadata) +- **🔐 Dynamic Client Registration**: Supports RFC 7591 for automatic client registration when supported by the server +- **🛡️ PKCE Security**: Implements RFC 7636 (Proof Key for Code Exchange) for secure public client authentication +- **🌐 Public Client Support**: Works with servers that don't require client_id (like Notion MCP) +- **🔄 Token Management**: Automatic token refresh and expiry handling +- **🚫 Extension Filtering**: Filters out browser extension interference during OAuth callbacks + +## Platform Support + +**✅ Web Platform**: Full OAuth support with popup-based authentication flow +**❌ Mobile/Desktop**: OAuth authentication is **web-only** due to browser security requirements + +On non-web platforms: +- OAuth discovery still works (detects requirements) +- OAuth authentication throws `UnsupportedError` +- Fallback to manual configuration or other auth methods + +## Tested OAuth Providers + +- ✅ **Notion MCP** (`https://mcp.notion.com/mcp`) +- ✅ **Atlassian MCP** (specific URL varies) +- 🔄 **Other RFC 8414 compliant servers** (should work automatically) + +## How It Works + +1. **Discovery Phase**: When you enter an MCP server URL, the system: + - Checks `/.well-known/oauth-authorization-server` for OAuth metadata + - Attempts dynamic client registration if available + - Falls back to public client mode if no client registration + +2. **Authentication Phase**: + - Opens OAuth authorization popup + - Handles PKCE code challenge/verifier generation + - Processes OAuth callback with state validation + - Exchanges authorization code for access token + +3. **Usage Phase**: + - Automatically includes `Authorization: Bearer ` in MCP requests + - Handles token refresh when needed + - Validates token expiry + +## Architecture + +``` +┌─────────────────┐ ┌────────────────────┐ ┌─────────────────┐ +│ MCP Server │ │ OAuth Discovery │ │ OAuth Handler │ +│ │◄──►│ │◄──►│ │ +│ /.well-known/ │ │ RFC 8414 Compliant │ │ PKCE + Popup │ +│ oauth-auth... │ │ │ │ Cross-origin │ +└─────────────────┘ └────────────────────┘ └─────────────────┘ + │ + ▼ + ┌────────────────────┐ + │ MCP Client │ + │ │ + │ Bearer Token Auth │ + │ StreamableClient │ + │ SSEClient │ + └────────────────────┘ +``` + +## Usage + +1. Go to **Settings → MCP Servers** +2. Enter an OAuth-protected MCP server URL (e.g., `https://mcp.notion.com/mcp`) +3. Click **Add Server** - OAuth requirements are detected automatically +4. If OAuth is required, you'll be prompted to authenticate +5. Complete the OAuth flow in the popup window +6. The server will be ready to use with automatic token authentication + +## Security Features + +- **PKCE Protection**: Prevents authorization code interception attacks +- **State Parameter Validation**: Prevents CSRF attacks +- **Origin Validation**: Ensures callbacks come from expected sources +- **Browser Extension Filtering**: Ignores interference from development tools +- **Token Expiry Handling**: Automatic refresh before expiration + +## Future Enhancements + +- Mobile/Desktop OAuth support via external browser +- Additional OAuth flows (device code, etc.) +- OAuth provider-specific optimizations +- Enhanced error handling and user feedback + +--- + +This implementation follows OAuth 2.0 security best practices and modern web standards for a robust, user-friendly authentication experience. diff --git a/docs/mcp_sse.png b/docs/mcp_sse.png new file mode 100644 index 0000000..c9da4d8 Binary files /dev/null and b/docs/mcp_sse.png differ diff --git a/docs/mcp_stdio.png b/docs/mcp_stdio.png new file mode 100644 index 0000000..d018b46 Binary files /dev/null and b/docs/mcp_stdio.png differ diff --git a/docs/pagination_config.md b/docs/pagination_config.md new file mode 100644 index 0000000..1aace1c --- /dev/null +++ b/docs/pagination_config.md @@ -0,0 +1,116 @@ +# 分页配置统一说明 + +## 概述 + +本次更改统一了整个应用程序中的分页配置,实现了滚动到底部自动加载更多的功能,避免了硬编码并提供了集中化的配置管理。 + +## 核心功能 + +### 滚动到底部自动加载 + +- 用户滚动到距离底部 100px 时自动触发加载下一页 +- 移除了下拉刷新功能,专注于向下滚动的体验 +- 显示加载状态和"没有更多了"的提示 + +### 防重复加载机制 + +- 使用本地状态防止快速滚动时重复触发加载 +- 只有在满足所有条件时才触发加载: + - 滚动到触发距离 + - 有更多数据可加载 + - 当前没有在加载中 + - 已有聊天数据 + +## 配置文件 + +### `lib/config/pagination_config.dart` + +这个配置文件包含了所有分页相关的常量: + +```dart +class PaginationConfig { + /// 默认页面大小 - 20条记录 + static const int defaultPageSize = 20; + + /// 搜索结果页面大小 - 20条记录 + static const int searchPageSize = 20; + + /// 最大页面大小 - 100条记录 + static const int maxPageSize = 100; + + /// 最小页面大小 - 1条记录 + static const int minPageSize = 1; + + /// 滚动触发加载的距离 - 100像素 + static const double loadMoreTriggerDistance = 100.0; +} +``` + +## 用户体验流程 + +1. **初始加载**: 应用启动时自动加载第一页数据 +2. **滚动浏览**: 用户向下滚动查看聊天历史 +3. **自动加载**: 接近底部时自动加载下一页,显示加载指示器 +4. **无缝体验**: 新数据追加到列表末尾,用户可继续滚动 +5. **结束提示**: 没有更多数据时显示"—— 没有更多了 ——" + +## 技术实现 + +### 页码约定 + +- **页码从 1 开始**: 符合常规分页概念,第一页为 page=1 +- **内部转换**: 本地存储层自动转换为从 0 开始的 offset 计算 +- **API 统一**: 所有 Repository 接口使用 1-based 页码 + +```dart +// 用户调用 (1-based) +final result = await repository.getChats(page: 1); // 第一页 + +// 内部转换 (0-based offset) +final offset = (page - 1) * pageSize; // offset = 0 for first page +``` + +### ScrollController 监听 + +```dart +void _scrollListener() { + final scrollPosition = _scrollController.position; + final isNearBottom = scrollPosition.pixels >= + scrollPosition.maxScrollExtent - PaginationConfig.loadMoreTriggerDistance; + + if (isNearBottom && hasMoreData && !isLoading) { + loadMoreChats(); + } +} +``` + +### 状态管理 + +- `_currentPage`: 当前页码 (从 1 开始) +- `hasMoreChats`: 是否还有更多数据 +- `isLoadingChats`: 是否正在加载 +- `_isLoadingMore`: 本地防重复加载标志 + +### UI 状态显示 + +- **加载中**: 转圈动画 + "正在下载数据..." +- **没有更多**: "—— 没有更多了 ——" +- **有更多**: 显示足够的空白区域供滚动检测 + +## 主要优势 + +1. **自然体验**: 符合用户滚动浏览的习惯 +2. **性能优化**: 按需加载,避免一次性加载大量数据 +3. **防误触**: 精确的触发距离和防重复机制 +4. **状态清晰**: 明确的加载状态和结束提示 +5. **配置统一**: 所有分页参数集中管理 + +## 配置说明 + +- **loadMoreTriggerDistance**: 100px 是经过测试的最佳触发距离,既不会太早触发,也不会让用户等待 +- **defaultPageSize**: 20条记录平衡了网络请求效率和用户体验 +- **footer 高度**: 50px 确保有足够空间进行滚动检测 + +## 与搜索功能的配合 + +搜索时会重置分页状态,新的搜索结果同样支持滚动加载更多功能,提供一致的用户体验。 \ No newline at end of file diff --git a/docs/preview/artifact.gif b/docs/preview/artifact.gif new file mode 100644 index 0000000..66e2370 Binary files /dev/null and b/docs/preview/artifact.gif differ diff --git a/docs/preview/data-sync.webp b/docs/preview/data-sync.webp new file mode 100644 index 0000000..2f4e633 Binary files /dev/null and b/docs/preview/data-sync.webp differ diff --git a/docs/preview/gen_img.webp b/docs/preview/gen_img.webp new file mode 100644 index 0000000..8869d2f Binary files /dev/null and b/docs/preview/gen_img.webp differ diff --git a/docs/preview/html-preview.webp b/docs/preview/html-preview.webp new file mode 100644 index 0000000..db736d4 Binary files /dev/null and b/docs/preview/html-preview.webp differ diff --git a/docs/preview/latex.webp b/docs/preview/latex.webp new file mode 100644 index 0000000..6437c0b Binary files /dev/null and b/docs/preview/latex.webp differ diff --git a/docs/preview/llm-provider.webp b/docs/preview/llm-provider.webp new file mode 100644 index 0000000..4d0327d Binary files /dev/null and b/docs/preview/llm-provider.webp differ diff --git a/docs/preview/mcp-inmemory.webp b/docs/preview/mcp-inmemory.webp new file mode 100644 index 0000000..573fb01 Binary files /dev/null and b/docs/preview/mcp-inmemory.webp differ diff --git a/docs/preview/mcp-sse.webp b/docs/preview/mcp-sse.webp new file mode 100644 index 0000000..3fe1484 Binary files /dev/null and b/docs/preview/mcp-sse.webp differ diff --git a/docs/preview/mcp-stdio.webp b/docs/preview/mcp-stdio.webp new file mode 100644 index 0000000..e49adae Binary files /dev/null and b/docs/preview/mcp-stdio.webp differ diff --git a/docs/preview/mcp-tools.webp b/docs/preview/mcp-tools.webp new file mode 100644 index 0000000..cf67f1b Binary files /dev/null and b/docs/preview/mcp-tools.webp differ diff --git a/docs/preview/mcp-workerflow.webp b/docs/preview/mcp-workerflow.webp new file mode 100644 index 0000000..98f7a6c Binary files /dev/null and b/docs/preview/mcp-workerflow.webp differ diff --git a/docs/preview/mermaid.webp b/docs/preview/mermaid.webp new file mode 100644 index 0000000..fefc232 Binary files /dev/null and b/docs/preview/mermaid.webp differ diff --git a/docs/preview/think.webp b/docs/preview/think.webp new file mode 100644 index 0000000..9332774 Binary files /dev/null and b/docs/preview/think.webp differ diff --git a/docs/readme.md b/docs/readme.md new file mode 100644 index 0000000..a5bfb7d --- /dev/null +++ b/docs/readme.md @@ -0,0 +1,9 @@ +## mcp server + +### stdio mcp server + +![](./mcp_stdio.png) + +### sse mcp serever + +![](./mcp_sse.png) \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 0000000..1fab620 --- /dev/null +++ b/index.html @@ -0,0 +1,112 @@ + + + + + + Sandbox Preview + + + + + + + +
+ +
+ + + + + \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..7c56964 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 0000000..d97f17e --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,44 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '12.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100644 index 0000000..2de2420 --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,141 @@ +PODS: + - DKImagePickerController/Core (4.3.9): + - DKImagePickerController/ImageDataManager + - DKImagePickerController/Resource + - DKImagePickerController/ImageDataManager (4.3.9) + - DKImagePickerController/PhotoGallery (4.3.9): + - DKImagePickerController/Core + - DKPhotoGallery + - DKImagePickerController/Resource (4.3.9) + - DKPhotoGallery (0.0.19): + - DKPhotoGallery/Core (= 0.0.19) + - DKPhotoGallery/Model (= 0.0.19) + - DKPhotoGallery/Preview (= 0.0.19) + - DKPhotoGallery/Resource (= 0.0.19) + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Core (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Preview + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Model (0.0.19): + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Preview (0.0.19): + - DKPhotoGallery/Model + - DKPhotoGallery/Resource + - SDWebImage + - SwiftyGif + - DKPhotoGallery/Resource (0.0.19): + - SDWebImage + - SwiftyGif + - file_picker (0.0.1): + - DKImagePickerController/PhotoGallery + - Flutter + - Flutter (1.0.0) + - flutter_inappwebview_ios (0.0.1): + - Flutter + - flutter_inappwebview_ios/Core (= 0.0.1) + - OrderedSet (~> 6.0.3) + - flutter_inappwebview_ios/Core (0.0.1): + - Flutter + - OrderedSet (~> 6.0.3) + - flutter_keyboard_visibility (0.0.1): + - Flutter + - mobile_scanner (7.0.0): + - Flutter + - FlutterMacOS + - network_info_plus (0.0.1): + - Flutter + - OrderedSet (6.0.3) + - package_info_plus (0.4.5): + - Flutter + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - SDWebImage (5.20.0): + - SDWebImage/Core (= 5.20.0) + - SDWebImage/Core (5.20.0) + - share_plus (0.0.1): + - Flutter + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + - sqflite_darwin (0.0.4): + - Flutter + - FlutterMacOS + - SwiftyGif (5.4.5) + - url_launcher_ios (0.0.1): + - Flutter + +DEPENDENCIES: + - file_picker (from `.symlinks/plugins/file_picker/ios`) + - Flutter (from `Flutter`) + - flutter_inappwebview_ios (from `.symlinks/plugins/flutter_inappwebview_ios/ios`) + - flutter_keyboard_visibility (from `.symlinks/plugins/flutter_keyboard_visibility/ios`) + - mobile_scanner (from `.symlinks/plugins/mobile_scanner/darwin`) + - network_info_plus (from `.symlinks/plugins/network_info_plus/ios`) + - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) + - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + - share_plus (from `.symlinks/plugins/share_plus/ios`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + - sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`) + - url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`) + +SPEC REPOS: + trunk: + - DKImagePickerController + - DKPhotoGallery + - OrderedSet + - SDWebImage + - SwiftyGif + +EXTERNAL SOURCES: + file_picker: + :path: ".symlinks/plugins/file_picker/ios" + Flutter: + :path: Flutter + flutter_inappwebview_ios: + :path: ".symlinks/plugins/flutter_inappwebview_ios/ios" + flutter_keyboard_visibility: + :path: ".symlinks/plugins/flutter_keyboard_visibility/ios" + mobile_scanner: + :path: ".symlinks/plugins/mobile_scanner/darwin" + network_info_plus: + :path: ".symlinks/plugins/network_info_plus/ios" + package_info_plus: + :path: ".symlinks/plugins/package_info_plus/ios" + path_provider_foundation: + :path: ".symlinks/plugins/path_provider_foundation/darwin" + share_plus: + :path: ".symlinks/plugins/share_plus/ios" + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + sqflite_darwin: + :path: ".symlinks/plugins/sqflite_darwin/darwin" + url_launcher_ios: + :path: ".symlinks/plugins/url_launcher_ios/ios" + +SPEC CHECKSUMS: + DKImagePickerController: 946cec48c7873164274ecc4624d19e3da4c1ef3c + DKPhotoGallery: b3834fecb755ee09a593d7c9e389d8b5d6deed60 + file_picker: a0560bc09d61de87f12d246fc47d2119e6ef37be + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + flutter_inappwebview_ios: b89ba3482b96fb25e00c967aae065701b66e9b99 + flutter_keyboard_visibility: 4625131e43015dbbe759d9b20daaf77e0e3f6619 + mobile_scanner: 9157936403f5a0644ca3779a38ff8404c5434a93 + network_info_plus: 16d8832ab43b7bc22b168d76fffcad9da35486d2 + OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94 + package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499 + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + SDWebImage: 73c6079366fea25fa4bb9640d5fb58f0893facd8 + share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a + shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7 + sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0 + SwiftyGif: 706c60cf65fa2bc5ee0313beece843c8eb8194d4 + url_launcher_ios: 694010445543906933d732453a59da0a173ae33d + +PODFILE CHECKSUM: 819463e6a0290f5a72f145ba7cde16e8b6ef0796 + +COCOAPODS: 1.16.2 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..37ce6b5 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,738 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 72A4DF0F9CD2007EF0AAD436 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 88A7F851365B612417351C90 /* Pods_RunnerTests.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; + AE7625DE671923214E953096 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2218FF48B4BAC267064C0F06 /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 156C9F6BBB5CD899D336C5C9 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 2218FF48B4BAC267064C0F06 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 22B07061F8EABD5FE2BADA9E /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 2E4C8EA2A41FD100B21D20A2 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 4582E52D7C3FBA40AF481063 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 88A7F851365B612417351C90 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9DF45E7014F307A6EB967EBE /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + A6033F212D5D943200E9F557 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; + E55F578D33F8D514846A194A /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 94768FE6C82906BC3BA7F95A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 72A4DF0F9CD2007EF0AAD436 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + AE7625DE671923214E953096 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 07D954F63056073F794043A1 /* Pods */ = { + isa = PBXGroup; + children = ( + 22B07061F8EABD5FE2BADA9E /* Pods-Runner.debug.xcconfig */, + 9DF45E7014F307A6EB967EBE /* Pods-Runner.release.xcconfig */, + 156C9F6BBB5CD899D336C5C9 /* Pods-Runner.profile.xcconfig */, + E55F578D33F8D514846A194A /* Pods-RunnerTests.debug.xcconfig */, + 2E4C8EA2A41FD100B21D20A2 /* Pods-RunnerTests.release.xcconfig */, + 4582E52D7C3FBA40AF481063 /* Pods-RunnerTests.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 07D954F63056073F794043A1 /* Pods */, + DBE563954DF2FE07E78DA21D /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + A6033F212D5D943200E9F557 /* Runner.entitlements */, + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; + DBE563954DF2FE07E78DA21D /* Frameworks */ = { + isa = PBXGroup; + children = ( + 2218FF48B4BAC267064C0F06 /* Pods_Runner.framework */, + 88A7F851365B612417351C90 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 7EE78C74D884CBEE3157C4F7 /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 94768FE6C82906BC3BA7F95A /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 6F7FCC3395C71AA5B85637A5 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 8A77FA793F77B4AA1D3A7C48 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 6F7FCC3395C71AA5B85637A5 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 7EE78C74D884CBEE3157C4F7 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 8A77FA793F77B4AA1D3A7C48 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = XNDA84PBM3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E55F578D33F8D514846A194A /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2E4C8EA2A41FD100B21D20A2 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4582E52D7C3FBA40AF481063 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = AppIcon; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = XNDA84PBM3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = XNDA84PBM3; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d0d98aa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1 @@ +{"images":[{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"20x20","idiom":"iphone","filename":"Icon-App-20x20@3x.png","scale":"3x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"29x29","idiom":"iphone","filename":"Icon-App-29x29@3x.png","scale":"3x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"40x40","idiom":"iphone","filename":"Icon-App-40x40@3x.png","scale":"3x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@1x.png","scale":"1x"},{"size":"57x57","idiom":"iphone","filename":"Icon-App-57x57@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@2x.png","scale":"2x"},{"size":"60x60","idiom":"iphone","filename":"Icon-App-60x60@3x.png","scale":"3x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@1x.png","scale":"1x"},{"size":"20x20","idiom":"ipad","filename":"Icon-App-20x20@2x.png","scale":"2x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@1x.png","scale":"1x"},{"size":"29x29","idiom":"ipad","filename":"Icon-App-29x29@2x.png","scale":"2x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@1x.png","scale":"1x"},{"size":"40x40","idiom":"ipad","filename":"Icon-App-40x40@2x.png","scale":"2x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@1x.png","scale":"1x"},{"size":"50x50","idiom":"ipad","filename":"Icon-App-50x50@2x.png","scale":"2x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@1x.png","scale":"1x"},{"size":"72x72","idiom":"ipad","filename":"Icon-App-72x72@2x.png","scale":"2x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@1x.png","scale":"1x"},{"size":"76x76","idiom":"ipad","filename":"Icon-App-76x76@2x.png","scale":"2x"},{"size":"83.5x83.5","idiom":"ipad","filename":"Icon-App-83.5x83.5@2x.png","scale":"2x"},{"size":"1024x1024","idiom":"ios-marketing","filename":"Icon-App-1024x1024@1x.png","scale":"1x"}],"info":{"version":1,"author":"xcode"}} \ No newline at end of file diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..088468b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..33f2e1b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..bb83094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..1ef0be0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..8136c9b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..2b4d3cd Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..7ae64fb Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..bb83094 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..6b032de Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..a332e24 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..772e914 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..99f3069 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..8963203 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..8cc9cd2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..a332e24 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..75298b4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..b887da3 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..4b7e53f Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..03f3b3f Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..532efa9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..ca46ff1 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..ec215e5 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,57 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + ChatMCP + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + chatmcp + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + NSPhotoLibraryUsageDescription + Need to access the photo library to save images. + NSPhotoLibraryAddUsageDescription + Need to access the photo library to save images. + NSLocalNetworkUsageDescription + This app needs to access local networks for device-to-device communication. + NSCameraUsageDescription + This app needs camera access to scan QR codes for network synchronization. + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements new file mode 100644 index 0000000..903def2 --- /dev/null +++ b/ios/Runner/Runner.entitlements @@ -0,0 +1,8 @@ + + + + + aps-environment + development + + diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/l10n.yaml b/l10n.yaml new file mode 100644 index 0000000..fea8f17 --- /dev/null +++ b/l10n.yaml @@ -0,0 +1,5 @@ +arb-dir: lib/l10n +template-arb-file: app_en.arb +output-localization-file: app_localizations.dart +output-dir: lib/generated +synthetic-package: false \ No newline at end of file diff --git a/lib/components/widgets/base.dart b/lib/components/widgets/base.dart new file mode 100644 index 0000000..21da560 --- /dev/null +++ b/lib/components/widgets/base.dart @@ -0,0 +1,35 @@ +import 'package:chatmcp/utils/color.dart'; +import 'package:flutter/material.dart'; + +class Gap extends StatelessWidget { + const Gap({super.key, required this.size}); + + final double size; + + @override + Widget build(BuildContext context) { + return SizedBox(width: size, height: size); + } +} + +class CText extends StatelessWidget { + const CText({super.key, required this.text, this.size, this.fontWeight, this.overflow, this.color}); + + final String text; + final double? size; + final FontWeight? fontWeight; + final TextOverflow? overflow; + final Color? color; + @override + Widget build(BuildContext context) { + return Text( + text, + style: TextStyle( + fontSize: size ?? 12, + color: color ?? AppColors.getThemeTextColor(context), + fontWeight: fontWeight, + overflow: overflow ?? TextOverflow.ellipsis, + ), + ); + } +} diff --git a/lib/components/widgets/custom_popup.dart b/lib/components/widgets/custom_popup.dart new file mode 100644 index 0000000..fcfe192 --- /dev/null +++ b/lib/components/widgets/custom_popup.dart @@ -0,0 +1,373 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_popup/flutter_popup.dart'; +import 'package:chatmcp/utils/color.dart'; + +/// 自定义弹窗基础组件 +/// 提供统一的弹窗样式和行为 +class BasePopup extends StatelessWidget { + /// 弹窗内容 + final Widget content; + + /// 触发弹窗的子组件 + final Widget child; + + /// 是否显示箭头 + final bool showArrow; + + /// 箭头颜色 + final Color? arrowColor; + + /// 背景颜色 + final Color? backgroundColor; + + /// 弹窗最大宽度 + final double? maxWidth; + + /// 弹窗最大高度 + final double? maxHeight; + + /// 弹窗边距 + final EdgeInsetsGeometry? margin; + + /// 弹窗内边距 + final EdgeInsets? padding; + + /// 弹窗圆角 + final BorderRadius? borderRadius; + + /// 弹窗阴影 + final List? boxShadow; + + const BasePopup({ + super.key, + required this.content, + required this.child, + this.showArrow = true, + this.arrowColor, + this.backgroundColor, + this.maxWidth, + this.maxHeight, + this.margin, + this.padding, + this.borderRadius, + this.boxShadow, + }); + + @override + Widget build(BuildContext context) { + final effectiveArrowColor = arrowColor ?? AppColors.getSidebarBackgroundColor(context); + final effectiveBackgroundColor = backgroundColor ?? AppColors.getSidebarBackgroundColor(context); + final effectiveBorderRadius = borderRadius ?? BorderRadius.circular(8); + final effectiveBoxShadow = boxShadow ?? [BoxShadow(color: Colors.black.withValues(alpha: 0.1), blurRadius: 8, offset: const Offset(0, 2))]; + + return CustomPopup( + showArrow: showArrow, + arrowColor: effectiveArrowColor, + backgroundColor: effectiveBackgroundColor, + contentPadding: EdgeInsets.all(0), + content: Container( + constraints: BoxConstraints(maxWidth: maxWidth ?? 280, maxHeight: maxHeight ?? MediaQuery.of(context).size.height * 0.6), + margin: margin, + padding: padding ?? const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: AppColors.getSidebarBackgroundColor(context), + borderRadius: effectiveBorderRadius, + boxShadow: effectiveBoxShadow, + ), + child: content, + ), + child: child, + ); + } +} + +/// 带搜索功能的弹窗基础组件 +class SearchablePopup extends StatefulWidget { + /// 弹窗内容构建器,接收搜索文本作为参数 + final Widget Function(String searchText) contentBuilder; + + /// 触发弹窗的子组件 + final Widget child; + + /// 搜索框提示文本 + final String searchHint; + + /// 是否显示箭头 + final bool showArrow; + + /// 箭头颜色 + final Color? arrowColor; + + /// 背景颜色 + final Color? backgroundColor; + + /// 弹窗最大宽度 + final double? maxWidth; + + /// 弹窗最大高度 + final double? maxHeight; + + /// 搜索框变化回调 + final void Function(String)? onSearchChanged; + + const SearchablePopup({ + super.key, + required this.contentBuilder, + required this.child, + this.searchHint = 'Search', + this.showArrow = true, + this.arrowColor, + this.backgroundColor, + this.maxWidth, + this.maxHeight, + this.onSearchChanged, + }); + + @override + State createState() => _SearchablePopupState(); +} + +class _SearchablePopupState extends State { + final TextEditingController _searchController = TextEditingController(); + String _searchText = ''; + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return BasePopup( + showArrow: widget.showArrow, + arrowColor: widget.arrowColor, + backgroundColor: widget.backgroundColor, + maxWidth: widget.maxWidth ?? 280, + maxHeight: widget.maxHeight ?? MediaQuery.of(context).size.height * 0.6, + padding: EdgeInsets.zero, + content: StatefulBuilder( + builder: (BuildContext context, StateSetter popupSetState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + // 搜索框 + Padding( + padding: const EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 4.0), + child: TextField( + controller: _searchController, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: AppColors.getThemeTextColor(context)), + decoration: InputDecoration( + hintText: widget.searchHint, + hintStyle: Theme.of(context).textTheme.bodySmall?.copyWith(color: AppColors.getInactiveTextColor(context)), + prefixIcon: Icon(Icons.search, size: 16, color: AppColors.getInactiveTextColor(context)), + isDense: true, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none), + filled: true, + fillColor: widget.backgroundColor ?? AppColors.getSidebarBackgroundColor(context), + contentPadding: const EdgeInsets.symmetric(vertical: 6, horizontal: 8), + ), + onChanged: (value) { + popupSetState(() { + _searchText = value.toLowerCase(); + }); + widget.onSearchChanged?.call(value); + }, + ), + ), + // 内容区域 + Flexible(child: widget.contentBuilder(_searchText)), + ], + ); + }, + ), + child: widget.child, + ); + } +} + +/// 弹窗列表项组件 +class PopupListItem extends StatelessWidget { + /// 列表项内容 + final Widget child; + + /// 点击回调 + final VoidCallback? onTap; + + /// 是否选中 + final bool isSelected; + + /// 内边距 + final EdgeInsetsGeometry? padding; + + /// 选中时的颜色 + final Color? selectedColor; + + const PopupListItem({super.key, required this.child, this.onTap, this.isSelected = false, this.padding, this.selectedColor}); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + child: Container( + padding: padding ?? const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Expanded(child: child), + if (isSelected) Icon(Icons.check, size: 14, color: selectedColor ?? AppColors.getTextButtonColor(context)), + ], + ), + ), + ); + } +} + +/// 弹窗分组标题组件 +class PopupGroupHeader extends StatelessWidget { + /// 标题文本 + final String title; + + /// 图标 + final Widget? icon; + + /// 内边距 + final EdgeInsetsGeometry? padding; + + const PopupGroupHeader({super.key, required this.title, this.icon, this.padding}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: padding ?? const EdgeInsets.fromLTRB(16, 6, 16, 2), + child: Row( + children: [ + if (icon != null) ...[icon!, const SizedBox(width: 8)], + Text(title, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ); + } +} + +/// 弹窗分隔线组件 +class PopupDivider extends StatelessWidget { + /// 分隔线高度 + final double height; + + /// 左边距 + final double indent; + + /// 右边距 + final double endIndent; + + /// 分隔线颜色 + final Color? color; + + const PopupDivider({super.key, this.height = 1, this.indent = 8, this.endIndent = 8, this.color}); + + @override + Widget build(BuildContext context) { + return Divider(height: height, indent: indent, endIndent: endIndent, color: color ?? AppColors.getCodePreviewBorderColor(context)); + } +} + +/// 空状态组件 +class PopupEmptyState extends StatelessWidget { + /// 空状态文本 + final String message; + + /// 文本样式 + final TextStyle? textStyle; + + const PopupEmptyState({super.key, required this.message, this.textStyle}); + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Text(message, style: textStyle ?? Theme.of(context).textTheme.bodyMedium?.copyWith(color: AppColors.getInactiveTextColor(context))), + ), + ); + } +} + +/// 底层弹窗实现组件 +class CustomPopupWidget extends StatelessWidget { + final Widget content; + final Widget child; + final bool showArrow; + final Color arrowColor; + final Color backgroundColor; + + const CustomPopupWidget({ + super.key, + required this.content, + required this.child, + required this.showArrow, + required this.arrowColor, + required this.backgroundColor, + }); + + @override + Widget build(BuildContext context) { + return BasePopup(showArrow: showArrow, arrowColor: arrowColor, backgroundColor: backgroundColor, content: content, child: child); + } +} + +/// 自定义弹窗路由实现 +class CustomPopupRoute extends StatelessWidget { + final Widget content; + final Widget child; + final bool showArrow; + final Color arrowColor; + final Color backgroundColor; + + const CustomPopupRoute({ + super.key, + required this.content, + required this.child, + required this.showArrow, + required this.arrowColor, + required this.backgroundColor, + }); + + @override + Widget build(BuildContext context) { + // 现在使用 BasePopup 而不是直接使用 flutter_popup 包 + return BasePopup(showArrow: showArrow, arrowColor: arrowColor, backgroundColor: backgroundColor, content: content, child: child); + } +} + +/* +使用示例: + +1. 基础弹窗: +BasePopup( + content: Text('弹窗内容'), + child: ElevatedButton( + onPressed: null, + child: Text('点击显示弹窗'), + ), +) + +2. 带搜索的弹窗: +SearchablePopup( + searchHint: '搜索...', + contentBuilder: (searchText) { + return Column( + children: [ + PopupGroupHeader(title: '分组标题'), + PopupListItem( + child: Text('列表项'), + onTap: () {}, + isSelected: true, + ), + PopupDivider(), + PopupEmptyState(message: '没有找到结果'), + ], + ); + }, + child: Text('点击搜索'), +) +*/ diff --git a/lib/config/pagination_config.dart b/lib/config/pagination_config.dart new file mode 100644 index 0000000..82aedcc --- /dev/null +++ b/lib/config/pagination_config.dart @@ -0,0 +1,28 @@ +/// Configuration constants for pagination across the application +/// +/// This class centralizes all pagination-related configuration to ensure +/// consistency across different parts of the application. +class PaginationConfig { + /// Default page size for chat list pagination + /// Used in sidebar chat list, search results, and general chat loading + static const int defaultPageSize = 20; + + /// Page size for search results + /// Can be different from default if search results need different pagination + static const int searchPageSize = 20; + + /// Maximum page size allowed for any pagination request + /// Used as a safety limit and for loading all items when needed + static const int maxPageSize = 100; + + /// Minimum page size allowed for any pagination request + /// Used for validation and edge cases + static const int minPageSize = 1; + + /// Distance from bottom (in pixels) to trigger load more in scroll views + /// When user scrolls within this distance from bottom, next page loads automatically + static const double loadMoreTriggerDistance = 100.0; + + /// Private constructor to prevent instantiation + PaginationConfig._(); +} diff --git a/lib/dao/base_dao.dart b/lib/dao/base_dao.dart new file mode 100644 index 0000000..5510855 --- /dev/null +++ b/lib/dao/base_dao.dart @@ -0,0 +1,50 @@ +import 'package:sqflite/sqflite.dart'; +import './init_db.dart'; + +abstract class BaseDao { + final String tableName; + + const BaseDao(this.tableName); + + Future get database => DatabaseHelper.instance.database; + + // Methods to be implemented by subclasses for data conversion + Map toJson(T entity); + T fromJson(Map json); + + // Generic CRUD operations + Future insert(T entity) async { + final db = await database; + return db.insert(tableName, toJson(entity), conflictAlgorithm: ConflictAlgorithm.replace); + } + + Future> query({String? where, List? whereArgs, String? orderBy, int? limit, int? offset}) async { + final db = await database; + final List> maps = await db.query( + tableName, + where: where, + whereArgs: whereArgs, + orderBy: orderBy, + limit: limit, + offset: offset, + ); + return maps.map((item) => fromJson(item)).toList(); + } + + Future queryById(String id) async { + final db = await database; + final List> maps = await db.query(tableName, where: 'id = ?', whereArgs: [id]); + if (maps.isEmpty) return null; + return fromJson(maps.first); + } + + Future update(T entity, String id) async { + final db = await database; + return db.update(tableName, toJson(entity), where: 'id = ?', whereArgs: [id]); + } + + Future delete(String id) async { + final db = await database; + return db.delete(tableName, where: 'id = ?', whereArgs: [id]); + } +} diff --git a/lib/dao/chat.dart b/lib/dao/chat.dart new file mode 100644 index 0000000..a132d6c --- /dev/null +++ b/lib/dao/chat.dart @@ -0,0 +1,44 @@ +import './base_dao.dart'; +import './chat_message.dart'; +import 'package:chatmcp/llm/model.dart' as llmModel; + +class Chat { + final int? id; + final String title; + final DateTime createdAt; + final DateTime updatedAt; + + Chat({this.id, required this.title, DateTime? createdAt, DateTime? updatedAt}) + : createdAt = createdAt ?? DateTime.now(), + updatedAt = updatedAt ?? DateTime.now(); + + Map toJson() { + return {if (id != null) 'id': id, 'title': title, 'createdAt': createdAt.toIso8601String(), 'updatedAt': updatedAt.toIso8601String()}; + } + + // get chat_messages + Future> getChatMessages() async { + final chatMessages = await ChatMessageDao().query(where: 'chatId = ?', whereArgs: [id!]); + + return chatMessages.map((e) => llmModel.ChatMessage.fromDb(e)).toList(); + } +} + +class ChatDao extends BaseDao { + ChatDao() : super('chat'); + + @override + Chat fromJson(Map json) { + return Chat( + id: json['id'] ?? '', + title: json['title'] ?? '', + createdAt: json['createdAt'] != null ? DateTime.parse(json['createdAt']) : DateTime.now(), + updatedAt: json['updatedAt'] != null ? DateTime.parse(json['updatedAt']) : DateTime.now(), + ); + } + + @override + Map toJson(Chat entity) { + return entity.toJson(); + } +} diff --git a/lib/dao/chat_message.dart b/lib/dao/chat_message.dart new file mode 100644 index 0000000..4f2c3c1 --- /dev/null +++ b/lib/dao/chat_message.dart @@ -0,0 +1,63 @@ +import './base_dao.dart'; +import 'package:uuid/uuid.dart'; + +class DbChatMessage { + final int? id; + final int chatId; + final String body; + final DateTime createdAt; + final DateTime updatedAt; + final String messageId; + final String parentMessageId; + + DbChatMessage({ + this.id, + required this.chatId, + required this.body, + DateTime? createdAt, + DateTime? updatedAt, + String? messageId, + this.parentMessageId = '', + }) : createdAt = createdAt ?? DateTime.now(), + updatedAt = updatedAt ?? DateTime.now(), + messageId = messageId ?? const Uuid().v4(); + + Map toJson() { + return { + if (id != null) 'id': id, + 'chatId': chatId, + 'messageId': messageId, + 'parentMessageId': parentMessageId, + 'body': body, + 'createdAt': createdAt.toIso8601String(), + 'updatedAt': updatedAt.toIso8601String(), + }; + } +} + +class ChatMessageDao extends BaseDao { + ChatMessageDao() : super('chat_message'); + + @override + DbChatMessage fromJson(Map json) { + return DbChatMessage( + id: json['id'] ?? 0, + chatId: json['chatId'] ?? 0, + messageId: json['messageId'] ?? '', + parentMessageId: json['parentMessageId'] ?? '', + body: json['body'] ?? '', + createdAt: json['createdAt'] != null ? DateTime.parse(json['createdAt']) : DateTime.now(), + updatedAt: json['updatedAt'] != null ? DateTime.parse(json['updatedAt']) : DateTime.now(), + ); + } + + @override + Map toJson(DbChatMessage entity) { + return entity.toJson(); + } + + Future deleteMessages(int chatId) async { + final db = await database; + return db.delete(tableName, where: 'chatId = ?', whereArgs: [chatId]); + } +} diff --git a/lib/dao/init_db.dart b/lib/dao/init_db.dart new file mode 100644 index 0000000..db9f6ba --- /dev/null +++ b/lib/dao/init_db.dart @@ -0,0 +1,273 @@ +import 'dart:async'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/storage_manager.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:logging/logging.dart'; +import 'package:sqflite/sqflite.dart' as sqflite; +import 'package:sqflite_common_ffi_web/sqflite_ffi_web.dart'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; + +//TODO : need to refactor the database helper class +// desktop app can use different database for persistent storage like sqlite, postgres, etc. +// mobile app can use in memory database +// for now, currently using in memory database for both desktop and mobile +// need to add support for other databases like postgres, mysql, etc. focus on relational database for now + +class DatabaseHelper { + static final DatabaseHelper instance = DatabaseHelper._init(); + static const List requiredTables = ['chat', 'chat_message']; + static const int currentVersion = 3; + + DatabaseHelper._init(); + + /// Thread-safe database initialization mechanism using Completer + /// This implementation ensures that: + /// 1. Database is initialized only once, even if multiple threads call get database simultaneously + /// 2. All threads receive the same database instance after initialization + /// 3. If initialization fails, all waiting threads receive the error + /// 4. No race conditions occur during initialization + static Completer? _initializationCompleter; + static Database? _database; + + /// Thread-safe getter for database instance + /// Returns existing database if already initialized + /// If initialization is in progress, waits for it to complete + /// If no initialization has started, begins new initialization + Future get database async { + if (_database != null) { + return _database!; + } + + // If initialization is already in progress, wait for it + if (_initializationCompleter != null) { + Logger.root.fine('Database initialization already in progress, waiting for completion'); + return _initializationCompleter!.future; + } + + // Start new initialization + Logger.root.info('Starting new database initialization process'); + _initializationCompleter = Completer(); + + try { + Logger.root.info('Step 1: Initializing SQLite database...'); + _database = await _initializeSqlite(); + Logger.root.info('Step 2: SQLite database initialized successfully'); + _initializationCompleter!.complete(_database); + } catch (e, stackTrace) { + Logger.root.severe('Database initialization failed: $e\nStack trace:\n$stackTrace'); + _initializationCompleter!.completeError(e, stackTrace); + _initializationCompleter = null; + rethrow; + } + + return _database!; + } + + Future _initializeSqlite() async { + if (kIsDesktop) { + Logger.root.info('Step 1.1: Initializing SQLite for desktop platform'); + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + } else if (kIsMobile) { + Logger.root.info('Step 1.1: Initializing SQLite for mobile platform'); + databaseFactory = sqflite.databaseFactory; + } else if (kIsWeb) { + Logger.root.info('Step 1.1: Initializing SQLite for web platform'); + databaseFactory = databaseFactoryFfiWeb; + } + + String dbPath; + if (kIsWeb) { + dbPath = 'chatmcp.db'; + } else { + dbPath = await StorageManager.getDatabasePath(); + } + + Logger.root.info('Step 1.2: Database will be created at: $dbPath'); + if (!kIsWeb) { + Logger.root.info('Step 1.3: Operating system: ${Platform.operatingSystem}'); + } + + final DatabaseSchemaManager schemaManager = DatabaseSchemaManager(); + + try { + Logger.root.info('Step 1.4: Opening database connection and running migrations'); + final db = await databaseFactory.openDatabase( + dbPath, + options: OpenDatabaseOptions(version: currentVersion, onCreate: schemaManager.onCreate, onUpgrade: schemaManager.onUpgrade), + ); + + Logger.root.info('Step 1.5: Database connection established and migrations completed'); + return db; + } catch (e, stackTrace) { + Logger.root.severe('Database initialization failed: $e\nStack trace:\n$stackTrace'); + rethrow; + } + } +} + +// Database Migration Class Definition +class DatabaseMigration { + final int version; + final List sql; + + const DatabaseMigration({required this.version, required this.sql}); +} + +Future initDb() async { + try { + Logger.root.info('Database initialization process started'); + final db = await DatabaseHelper.instance.database; + // Verify if tables were actually created + final tables = await db.query('sqlite_master', where: "type = 'table'"); + Logger.root.info('Database initialization completed successfully. Available tables: ${tables.map((t) => t['name']).join(', ')}'); + } catch (e, stackTrace) { + Logger.root.severe('Database initialization failed: $e\nStack trace:\n$stackTrace'); + rethrow; + } +} + +/// Abstract command class that encapsulates SQL statements needed for each version upgrade +abstract class CommandScript { + /// Utilize [Batch] to execute statements in bulk, avoiding multiple database calls + Future execute(Batch batch); +} + +/// For example, table creation logic for v1 +class CommandScriptV1 extends CommandScript { + @override + Future execute(Batch batch) async { + Logger.root.info('Starting table creation...'); + // Initial table creation scripts + batch.execute(''' + CREATE TABLE IF NOT EXISTS chat( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + model TEXT, + createdAt datetime, + updatedAt datetime + ) + '''); + batch.execute(''' + CREATE TABLE IF NOT EXISTS chat_message( + id INTEGER PRIMARY KEY AUTOINCREMENT, + chatId INTEGER, + messageId TEXT, + parentMessageId TEXT, + body TEXT, + createdAt datetime, + updatedAt datetime, + FOREIGN KEY (chatId) REFERENCES chat(id) + ) + '''); + Logger.root.info('Table creation complete'); + } +} + +/// Database migration for v2 (placeholder for future changes) +class CommandScriptV2 extends CommandScript { + @override + Future execute(Batch batch) async { + Logger.root.info('Applying database migration v2 (placeholder)'); + // Placeholder for future migrations + } +} + +/// Database migration for v3 - Fix model column issue +class CommandScriptV3 extends CommandScript { + @override + Future execute(Batch batch) async { + Logger.root.info('Applying database migration v3 - fixing model column'); + + // Use a completely different approach that's safer + // Instead of trying to detect columns, we'll backup, recreate, and restore + + // Step 1: Create backup table with only columns we know exist + batch.execute(''' + CREATE TABLE IF NOT EXISTS chat_backup( + id INTEGER PRIMARY KEY, + title TEXT, + createdAt datetime, + updatedAt datetime + ) + '''); + + // Step 2: Backup existing data (only safe columns) + batch.execute(''' + INSERT OR IGNORE INTO chat_backup (id, title, createdAt, updatedAt) + SELECT id, title, createdAt, updatedAt + FROM chat + WHERE id IS NOT NULL + '''); + + // Step 3: Drop the existing table + batch.execute('DROP TABLE IF EXISTS chat'); + + // Step 4: Create new table with correct schema + batch.execute(''' + CREATE TABLE chat( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT, + model TEXT, + createdAt datetime, + updatedAt datetime + ) + '''); + + // Step 5: Restore data from backup (model will be NULL) + batch.execute(''' + INSERT INTO chat (id, title, model, createdAt, updatedAt) + SELECT id, title, NULL as model, createdAt, updatedAt + FROM chat_backup + '''); + + // Step 6: Clean up backup table + batch.execute('DROP TABLE IF EXISTS chat_backup'); + + Logger.root.info('Database migration v3 completed successfully'); + } +} + +/// Management class to organize multiple version migration scripts +class DatabaseSchemaManager { + /// Map versions to corresponding CommandScript + final Map _commands = {}; + + DatabaseSchemaManager() { + Logger.root.info('Initializing database schema manager'); + _commands[1] = CommandScriptV1(); + _commands[2] = CommandScriptV2(); + _commands[3] = CommandScriptV3(); + } + + /// On database creation: create tables (version=1) + Future onCreate(Database db, int version) async { + Logger.root.info('Creating new database schema (version: $version)'); + final batch = db.batch(); + for (int v = 1; v <= version; v++) { + final script = _commands[v]; + if (script != null) { + Logger.root.info('Executing schema creation script for version $v'); + await script.execute(batch); + } + } + await batch.commit(); + Logger.root.info('Database schema creation completed'); + } + + /// On database upgrade: execute scripts from oldVersion+1 to newVersion + Future onUpgrade(Database db, int oldVersion, int newVersion) async { + Logger.root.info('Upgrading database from version $oldVersion to $newVersion'); + final batch = db.batch(); + for (int v = oldVersion + 1; v <= newVersion; v++) { + final script = _commands[v]; + if (script != null) { + Logger.root.info('Executing upgrade script for version $v'); + await script.execute(batch); + } + } + await batch.commit(); + Logger.root.info('Database upgrade completed successfully'); + } +} diff --git a/lib/file_logger.dart b/lib/file_logger.dart new file mode 100644 index 0000000..22cadd0 --- /dev/null +++ b/lib/file_logger.dart @@ -0,0 +1 @@ +export 'file_logger_stub.dart' if (dart.library.io) 'file_logger_io.dart'; diff --git a/lib/file_logger_io.dart b/lib/file_logger_io.dart new file mode 100644 index 0000000..c715da9 --- /dev/null +++ b/lib/file_logger_io.dart @@ -0,0 +1,87 @@ +import 'dart:io'; + +import 'package:flutter/widgets.dart'; +import 'package:path/path.dart' as path; +import 'package:chatmcp/utils/storage_manager.dart'; + +class FileLogger { + static File? _logFile; + static IOSink? _logSink; + + static Future initLogFile() async { + try { + final String appDirPath = await StorageManager.getAppDataDirectory(); + final logDir = Directory(path.join(appDirPath, 'logs')); + + // Ensure log directory exists + if (!await logDir.exists()) { + await logDir.create(recursive: true); + } + + // Clean up old log files (3 days ago) + await cleanupOldLogs(); + + // Use date as log filename + final now = DateTime.now(); + final fileName = 'app_${now.year}-${now.month}-${now.day}.log'; + _logFile = File(path.join(logDir.path, fileName)); + + // Open file in append mode + _logSink = _logFile?.openWrite(mode: FileMode.append); + } catch (e) { + debugPrint('Failed to initialize log file: $e'); + } + } + + /// Clean up old log files (3 days ago) + static Future cleanupOldLogs({int days = 3}) async { + try { + final String appDirPath = await StorageManager.getAppDataDirectory(); + final logDir = Directory(path.join(appDirPath, 'logs')); + + if (!await logDir.exists()) { + return; + } + + final now = DateTime.now(); + final threeDaysAgo = now.subtract(Duration(days: days)); + + await for (final FileSystemEntity entity in logDir.list()) { + if (entity is File && entity.path.endsWith('.log')) { + final fileName = path.basename(entity.path); + + // 解析文件名中的日期 (app_YYYY-M-D.log) + final dateMatch = RegExp(r'app_(\d{4})-(\d{1,2})-(\d{1,2})\.log$').firstMatch(fileName); + + if (dateMatch != null) { + try { + final year = int.parse(dateMatch.group(1)!); + final month = int.parse(dateMatch.group(2)!); + final day = int.parse(dateMatch.group(3)!); + final logDate = DateTime(year, month, day); + + // 如果日志文件日期早于3天前,则删除 + if (logDate.isBefore(threeDaysAgo)) { + await entity.delete(); + debugPrint('Deleted old log file: ${entity.path}'); + } + } catch (e) { + debugPrint('Failed to parse date from log file $fileName: $e'); + } + } + } + } + } catch (e) { + debugPrint('Failed to cleanup old logs: $e'); + } + } + + static void closeLogFile() { + _logSink?.flush(); + _logSink?.close(); + } + + static void writeToFile(String message) { + _logSink?.writeln('${DateTime.now()} $message'); + } +} diff --git a/lib/file_logger_stub.dart b/lib/file_logger_stub.dart new file mode 100644 index 0000000..df3cf25 --- /dev/null +++ b/lib/file_logger_stub.dart @@ -0,0 +1,17 @@ +class FileLogger { + static Future initLogFile() async { + // Do nothing on the web. + } + + static void closeLogFile() { + // Do nothing on the web. + } + + static void writeToFile(String message) { + // Do nothing on the web. + } + + static Future cleanupOldLogs({int days = 3}) async { + // Do nothing on the web. + } +} diff --git a/lib/generated/app_localizations.dart b/lib/generated/app_localizations.dart new file mode 100644 index 0000000..4cfb360 --- /dev/null +++ b/lib/generated/app_localizations.dart @@ -0,0 +1,1782 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:intl/intl.dart' as intl; + +import 'app_localizations_de.dart'; +import 'app_localizations_en.dart'; +import 'app_localizations_tr.dart'; +import 'app_localizations_zh.dart'; + +// ignore_for_file: type=lint + +/// Callers can lookup localized strings with an instance of AppLocalizations +/// returned by `AppLocalizations.of(context)`. +/// +/// Applications need to include `AppLocalizations.delegate()` in their app's +/// `localizationDelegates` list, and the locales they support in the app's +/// `supportedLocales` list. For example: +/// +/// ```dart +/// import 'generated/app_localizations.dart'; +/// +/// return MaterialApp( +/// localizationsDelegates: AppLocalizations.localizationsDelegates, +/// supportedLocales: AppLocalizations.supportedLocales, +/// home: MyApplicationHome(), +/// ); +/// ``` +/// +/// ## Update pubspec.yaml +/// +/// Please make sure to update your pubspec.yaml to include the following +/// packages: +/// +/// ```yaml +/// dependencies: +/// # Internationalization support. +/// flutter_localizations: +/// sdk: flutter +/// intl: any # Use the pinned version from flutter_localizations +/// +/// # Rest of dependencies +/// ``` +/// +/// ## iOS Applications +/// +/// iOS applications define key application metadata, including supported +/// locales, in an Info.plist file that is built into the application bundle. +/// To configure the locales supported by your app, you’ll need to edit this +/// file. +/// +/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file. +/// Then, in the Project Navigator, open the Info.plist file under the Runner +/// project’s Runner folder. +/// +/// Next, select the Information Property List item, select Add Item from the +/// Editor menu, then select Localizations from the pop-up menu. +/// +/// Select and expand the newly-created Localizations item then, for each +/// locale your application supports, add a new item and select the locale +/// you wish to add from the pop-up menu in the Value field. This list should +/// be consistent with the languages listed in the AppLocalizations.supportedLocales +/// property. +abstract class AppLocalizations { + AppLocalizations(String locale) : localeName = intl.Intl.canonicalizedLocale(locale.toString()); + + final String localeName; + + static AppLocalizations? of(BuildContext context) { + return Localizations.of(context, AppLocalizations); + } + + static const LocalizationsDelegate delegate = _AppLocalizationsDelegate(); + + /// A list of this localizations delegate along with the default localizations + /// delegates. + /// + /// Returns a list of localizations delegates containing this delegate along with + /// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, + /// and GlobalWidgetsLocalizations.delegate. + /// + /// Additional delegates can be added by appending to this list in + /// MaterialApp. This list does not have to be used at all if a custom list + /// of delegates is preferred or required. + static const List> localizationsDelegates = >[ + delegate, + GlobalMaterialLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ]; + + /// A list of this localizations delegate's supported locales. + static const List supportedLocales = [Locale('de'), Locale('en'), Locale('tr'), Locale('zh')]; + + /// No description provided for @settings. + /// + /// In en, this message translates to: + /// **'Settings'** + String get settings; + + /// No description provided for @general. + /// + /// In en, this message translates to: + /// **'General'** + String get general; + + /// No description provided for @providers. + /// + /// In en, this message translates to: + /// **'Providers'** + String get providers; + + /// No description provided for @mcpServer. + /// + /// In en, this message translates to: + /// **'MCP Server'** + String get mcpServer; + + /// No description provided for @language. + /// + /// In en, this message translates to: + /// **'Language'** + String get language; + + /// No description provided for @theme. + /// + /// In en, this message translates to: + /// **'Theme'** + String get theme; + + /// No description provided for @dark. + /// + /// In en, this message translates to: + /// **'Dark'** + String get dark; + + /// No description provided for @light. + /// + /// In en, this message translates to: + /// **'Light'** + String get light; + + /// No description provided for @system. + /// + /// In en, this message translates to: + /// **'System'** + String get system; + + /// No description provided for @languageSettings. + /// + /// In en, this message translates to: + /// **'Language Settings'** + String get languageSettings; + + /// No description provided for @featureSettings. + /// + /// In en, this message translates to: + /// **'Feature Settings'** + String get featureSettings; + + /// No description provided for @enableArtifacts. + /// + /// In en, this message translates to: + /// **'Enable Artifacts'** + String get enableArtifacts; + + /// No description provided for @enableArtifactsDescription. + /// + /// In en, this message translates to: + /// **'Enable the artifacts of the AI assistant in the conversation, will use more tokens'** + String get enableArtifactsDescription; + + /// No description provided for @enableToolUsage. + /// + /// In en, this message translates to: + /// **'Enable Tool Usage'** + String get enableToolUsage; + + /// No description provided for @enableToolUsageDescription. + /// + /// In en, this message translates to: + /// **'Enable the usage of tools in the conversation, will use more tokens'** + String get enableToolUsageDescription; + + /// No description provided for @themeSettings. + /// + /// In en, this message translates to: + /// **'Theme Settings'** + String get themeSettings; + + /// No description provided for @lightTheme. + /// + /// In en, this message translates to: + /// **'Light Theme'** + String get lightTheme; + + /// No description provided for @darkTheme. + /// + /// In en, this message translates to: + /// **'Dark Theme'** + String get darkTheme; + + /// No description provided for @followSystem. + /// + /// In en, this message translates to: + /// **'Follow System'** + String get followSystem; + + /// No description provided for @showAvatar. + /// + /// In en, this message translates to: + /// **'Show Avatar'** + String get showAvatar; + + /// No description provided for @showAssistantAvatar. + /// + /// In en, this message translates to: + /// **'Show Assistant Avatar'** + String get showAssistantAvatar; + + /// No description provided for @showAssistantAvatarDescription. + /// + /// In en, this message translates to: + /// **'Show the avatar of the AI assistant in the conversation'** + String get showAssistantAvatarDescription; + + /// No description provided for @showUserAvatar. + /// + /// In en, this message translates to: + /// **'Show User Avatar'** + String get showUserAvatar; + + /// No description provided for @showUserAvatarDescription. + /// + /// In en, this message translates to: + /// **'Show the avatar of the user in the conversation'** + String get showUserAvatarDescription; + + /// No description provided for @systemPrompt. + /// + /// In en, this message translates to: + /// **'System Prompt'** + String get systemPrompt; + + /// No description provided for @systemPromptDescription. + /// + /// In en, this message translates to: + /// **'This is the system prompt for the conversation with the AI assistant, used to set the behavior and style of the assistant'** + String get systemPromptDescription; + + /// No description provided for @llmKey. + /// + /// In en, this message translates to: + /// **'LLM Key'** + String get llmKey; + + /// No description provided for @toolKey. + /// + /// In en, this message translates to: + /// **'Tool Key'** + String get toolKey; + + /// No description provided for @saveSettings. + /// + /// In en, this message translates to: + /// **'Save Settings'** + String get saveSettings; + + /// No description provided for @apiKey. + /// + /// In en, this message translates to: + /// **'API Key'** + String get apiKey; + + /// No description provided for @enterApiKey. + /// + /// In en, this message translates to: + /// **'Enter your {provider} API Key'** + String enterApiKey(Object provider); + + /// No description provided for @apiKeyValidation. + /// + /// In en, this message translates to: + /// **'API Key must be at least 10 characters'** + String get apiKeyValidation; + + /// No description provided for @apiEndpoint. + /// + /// In en, this message translates to: + /// **'API Endpoint'** + String get apiEndpoint; + + /// No description provided for @enterApiEndpoint. + /// + /// In en, this message translates to: + /// **'Enter API endpoint URL'** + String get enterApiEndpoint; + + /// No description provided for @apiVersion. + /// + /// In en, this message translates to: + /// **'API Version'** + String get apiVersion; + + /// No description provided for @enterApiVersion. + /// + /// In en, this message translates to: + /// **'Enter API Version'** + String get enterApiVersion; + + /// No description provided for @platformNotSupported. + /// + /// In en, this message translates to: + /// **'Current platform does not support MCP Server'** + String get platformNotSupported; + + /// No description provided for @mcpServerDesktopOnly. + /// + /// In en, this message translates to: + /// **'MCP Server only supports desktop platforms (Windows, macOS, Linux)'** + String get mcpServerDesktopOnly; + + /// No description provided for @searchServer. + /// + /// In en, this message translates to: + /// **'Search server...'** + String get searchServer; + + /// No description provided for @noServerConfigs. + /// + /// In en, this message translates to: + /// **'No server configurations found'** + String get noServerConfigs; + + /// No description provided for @addProvider. + /// + /// In en, this message translates to: + /// **'Add Provider'** + String get addProvider; + + /// No description provided for @refresh. + /// + /// In en, this message translates to: + /// **'Refresh'** + String get refresh; + + /// No description provided for @install. + /// + /// In en, this message translates to: + /// **'Install'** + String get install; + + /// No description provided for @edit. + /// + /// In en, this message translates to: + /// **'Edit'** + String get edit; + + /// No description provided for @delete. + /// + /// In en, this message translates to: + /// **'Delete'** + String get delete; + + /// No description provided for @command. + /// + /// In en, this message translates to: + /// **'Command Or Sever Url'** + String get command; + + /// No description provided for @arguments. + /// + /// In en, this message translates to: + /// **'Arguments'** + String get arguments; + + /// No description provided for @environmentVariables. + /// + /// In en, this message translates to: + /// **'Environment Variables'** + String get environmentVariables; + + /// No description provided for @serverName. + /// + /// In en, this message translates to: + /// **'Server Name'** + String get serverName; + + /// No description provided for @commandExample. + /// + /// In en, this message translates to: + /// **'For example: npx, uvx, https://mcpserver.com'** + String get commandExample; + + /// No description provided for @argumentsExample. + /// + /// In en, this message translates to: + /// **'Separate arguments with spaces, use quotes for arguments with spaces, for example: -y obsidian-mcp \'/Users/username/Documents/Obsidian Vault\''** + String get argumentsExample; + + /// No description provided for @envVarsFormat. + /// + /// In en, this message translates to: + /// **'One per line, format: KEY=VALUE'** + String get envVarsFormat; + + /// No description provided for @cancel. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get cancel; + + /// No description provided for @save. + /// + /// In en, this message translates to: + /// **'Save'** + String get save; + + /// No description provided for @confirmDelete. + /// + /// In en, this message translates to: + /// **'Confirm Delete'** + String get confirmDelete; + + /// No description provided for @confirmDeleteServer. + /// + /// In en, this message translates to: + /// **'Are you sure you want to delete server \"{name}\" ?'** + String confirmDeleteServer(Object name); + + /// No description provided for @error. + /// + /// In en, this message translates to: + /// **'Error'** + String get error; + + /// No description provided for @commandNotExist. + /// + /// In en, this message translates to: + /// **'Command \"{command}\" does not exist, please install it first\n\nCurrent PATH:\n{path}'** + String commandNotExist(Object command, Object path); + + /// No description provided for @all. + /// + /// In en, this message translates to: + /// **'All'** + String get all; + + /// No description provided for @installed. + /// + /// In en, this message translates to: + /// **'Installed'** + String get installed; + + /// No description provided for @modelSettings. + /// + /// In en, this message translates to: + /// **'Model Settings'** + String get modelSettings; + + /// No description provided for @temperature. + /// + /// In en, this message translates to: + /// **'Temperature: {value}'** + String temperature(Object value); + + /// No description provided for @temperatureTooltip. + /// + /// In en, this message translates to: + /// **'Sampling temperature controls the randomness of output:\n• 0.0: Suitable for code generation and math problems\n• 1.0: Suitable for data extraction and analysis\n• 1.3: Suitable for general conversation and translation\n• 1.5: Suitable for creative writing and poetry'** + String get temperatureTooltip; + + /// No description provided for @topP. + /// + /// In en, this message translates to: + /// **'Top P: {value}'** + String topP(Object value); + + /// No description provided for @topPTooltip. + /// + /// In en, this message translates to: + /// **'Top P (nucleus sampling) is an alternative to temperature. The model only considers tokens whose cumulative probability exceeds P. It is recommended not to modify both temperature and top_p at the same time.'** + String get topPTooltip; + + /// No description provided for @maxTokens. + /// + /// In en, this message translates to: + /// **'Max Tokens'** + String get maxTokens; + + /// No description provided for @maxTokensTooltip. + /// + /// In en, this message translates to: + /// **'Maximum number of tokens to generate. One token is approximately equal to 4 characters. Longer conversations require more tokens.'** + String get maxTokensTooltip; + + /// No description provided for @frequencyPenalty. + /// + /// In en, this message translates to: + /// **'Frequency Penalty: {value}'** + String frequencyPenalty(Object value); + + /// No description provided for @frequencyPenaltyTooltip. + /// + /// In en, this message translates to: + /// **'Frequency penalty parameter. Positive values penalize new tokens based on their existing frequency in the text, decreasing the model\'s likelihood of repeating the same content verbatim.'** + String get frequencyPenaltyTooltip; + + /// No description provided for @presencePenalty. + /// + /// In en, this message translates to: + /// **'Presence Penalty: {value}'** + String presencePenalty(Object value); + + /// No description provided for @presencePenaltyTooltip. + /// + /// In en, this message translates to: + /// **'Presence penalty parameter. Positive values penalize new tokens based on whether they appear in the text, increasing the model\'s likelihood of talking about new topics.'** + String get presencePenaltyTooltip; + + /// No description provided for @enterMaxTokens. + /// + /// In en, this message translates to: + /// **'Enter max tokens'** + String get enterMaxTokens; + + /// No description provided for @share. + /// + /// In en, this message translates to: + /// **'Share'** + String get share; + + /// No description provided for @modelConfig. + /// + /// In en, this message translates to: + /// **'Model Config'** + String get modelConfig; + + /// No description provided for @debug. + /// + /// In en, this message translates to: + /// **'Debug'** + String get debug; + + /// No description provided for @webSearchTest. + /// + /// In en, this message translates to: + /// **'Web Search Test'** + String get webSearchTest; + + /// No description provided for @today. + /// + /// In en, this message translates to: + /// **'Today'** + String get today; + + /// No description provided for @yesterday. + /// + /// In en, this message translates to: + /// **'Yesterday'** + String get yesterday; + + /// No description provided for @last7Days. + /// + /// In en, this message translates to: + /// **'Last 7 Days'** + String get last7Days; + + /// No description provided for @last30Days. + /// + /// In en, this message translates to: + /// **'Last 30 Days'** + String get last30Days; + + /// No description provided for @earlier. + /// + /// In en, this message translates to: + /// **'Earlier'** + String get earlier; + + /// No description provided for @confirmDeleteSelected. + /// + /// In en, this message translates to: + /// **'Are you sure you want to delete the selected conversations?'** + String get confirmDeleteSelected; + + /// No description provided for @confirmThisChat. + /// + /// In en, this message translates to: + /// **'Are you sure you want to delete the this conversations'** + String get confirmThisChat; + + /// No description provided for @ok. + /// + /// In en, this message translates to: + /// **'OK'** + String get ok; + + /// No description provided for @askMeAnything. + /// + /// In en, this message translates to: + /// **'Ask me anything...'** + String get askMeAnything; + + /// No description provided for @uploadFiles. + /// + /// In en, this message translates to: + /// **'Upload Files'** + String get uploadFiles; + + /// No description provided for @welcomeMessage. + /// + /// In en, this message translates to: + /// **'How can I help you today?'** + String get welcomeMessage; + + /// No description provided for @copy. + /// + /// In en, this message translates to: + /// **'Copy'** + String get copy; + + /// No description provided for @copied. + /// + /// In en, this message translates to: + /// **'Copied to clipboard'** + String get copied; + + /// No description provided for @retry. + /// + /// In en, this message translates to: + /// **'Retry'** + String get retry; + + /// No description provided for @brokenImage. + /// + /// In en, this message translates to: + /// **'Broken Image'** + String get brokenImage; + + /// No description provided for @toolCall. + /// + /// In en, this message translates to: + /// **'call {name}'** + String toolCall(Object name); + + /// No description provided for @toolResult. + /// + /// In en, this message translates to: + /// **'call {name} result'** + String toolResult(Object name); + + /// No description provided for @selectModel. + /// + /// In en, this message translates to: + /// **'Select Model'** + String get selectModel; + + /// No description provided for @close. + /// + /// In en, this message translates to: + /// **'Close'** + String get close; + + /// No description provided for @selectFromGallery. + /// + /// In en, this message translates to: + /// **'Select from Gallery'** + String get selectFromGallery; + + /// No description provided for @selectFile. + /// + /// In en, this message translates to: + /// **'Select File'** + String get selectFile; + + /// No description provided for @uploadFile. + /// + /// In en, this message translates to: + /// **'Upload File'** + String get uploadFile; + + /// No description provided for @openBrowser. + /// + /// In en, this message translates to: + /// **'Open Browser'** + String get openBrowser; + + /// No description provided for @codeCopiedToClipboard. + /// + /// In en, this message translates to: + /// **'Code copied to clipboard'** + String get codeCopiedToClipboard; + + /// No description provided for @thinking. + /// + /// In en, this message translates to: + /// **'Thinking'** + String get thinking; + + /// No description provided for @thinkingEnd. + /// + /// In en, this message translates to: + /// **'Thinking End'** + String get thinkingEnd; + + /// No description provided for @tool. + /// + /// In en, this message translates to: + /// **'Tool'** + String get tool; + + /// No description provided for @userCancelledToolCall. + /// + /// In en, this message translates to: + /// **'Tool execution failed'** + String get userCancelledToolCall; + + /// No description provided for @code. + /// + /// In en, this message translates to: + /// **'Code'** + String get code; + + /// No description provided for @preview. + /// + /// In en, this message translates to: + /// **'Preview'** + String get preview; + + /// No description provided for @loadContentFailed. + /// + /// In en, this message translates to: + /// **'Failed to load content, please retry'** + String get loadContentFailed; + + /// No description provided for @openingBrowser. + /// + /// In en, this message translates to: + /// **'Opening browser'** + String get openingBrowser; + + /// No description provided for @functionCallAuth. + /// + /// In en, this message translates to: + /// **'Tool Call Authorization'** + String get functionCallAuth; + + /// No description provided for @allowFunctionExecution. + /// + /// In en, this message translates to: + /// **'Do you want to allow the following tool to execute:'** + String get allowFunctionExecution; + + /// No description provided for @parameters. + /// + /// In en, this message translates to: + /// **'Parameters: {params}'** + String parameters(Object params); + + /// No description provided for @allow. + /// + /// In en, this message translates to: + /// **'Allow'** + String get allow; + + /// No description provided for @loadDiagramFailed. + /// + /// In en, this message translates to: + /// **'Failed to load diagram, please retry'** + String get loadDiagramFailed; + + /// No description provided for @copiedToClipboard. + /// + /// In en, this message translates to: + /// **'Copied to clipboard'** + String get copiedToClipboard; + + /// No description provided for @chinese. + /// + /// In en, this message translates to: + /// **'Chinese'** + String get chinese; + + /// No description provided for @turkish. + /// + /// In en, this message translates to: + /// **'Turkish'** + String get turkish; + + /// No description provided for @functionRunning. + /// + /// In en, this message translates to: + /// **'Running Tool...'** + String get functionRunning; + + /// No description provided for @thinkingProcess. + /// + /// In en, this message translates to: + /// **'Thinking'** + String get thinkingProcess; + + /// No description provided for @thinkingProcessWithDuration. + /// + /// In en, this message translates to: + /// **'Thinking, time used'** + String get thinkingProcessWithDuration; + + /// No description provided for @thinkingEndWithDuration. + /// + /// In en, this message translates to: + /// **'Thinking finished, time used'** + String get thinkingEndWithDuration; + + /// No description provided for @thinkingEndComplete. + /// + /// In en, this message translates to: + /// **'Thinking finished'** + String get thinkingEndComplete; + + /// No description provided for @seconds. + /// + /// In en, this message translates to: + /// **'{seconds}s'** + String seconds(Object seconds); + + /// No description provided for @fieldRequired. + /// + /// In en, this message translates to: + /// **'This field is required'** + String get fieldRequired; + + /// No description provided for @autoApprove. + /// + /// In en, this message translates to: + /// **'Auto Approve'** + String get autoApprove; + + /// No description provided for @verify. + /// + /// In en, this message translates to: + /// **'Verify Key'** + String get verify; + + /// No description provided for @howToGet. + /// + /// In en, this message translates to: + /// **'How to get'** + String get howToGet; + + /// No description provided for @modelList. + /// + /// In en, this message translates to: + /// **'Model List'** + String get modelList; + + /// No description provided for @enableModels. + /// + /// In en, this message translates to: + /// **'Enable Models'** + String get enableModels; + + /// No description provided for @disableAllModels. + /// + /// In en, this message translates to: + /// **'Disable All Models'** + String get disableAllModels; + + /// No description provided for @saveSuccess. + /// + /// In en, this message translates to: + /// **'Settings saved successfully'** + String get saveSuccess; + + /// No description provided for @genTitleModel. + /// + /// In en, this message translates to: + /// **'Gen Title'** + String get genTitleModel; + + /// No description provided for @serverNameTooLong. + /// + /// In en, this message translates to: + /// **'Server name cannot exceed 50 characters'** + String get serverNameTooLong; + + /// No description provided for @confirm. + /// + /// In en, this message translates to: + /// **'Confirm'** + String get confirm; + + /// No description provided for @providerName. + /// + /// In en, this message translates to: + /// **'Provider Name'** + String get providerName; + + /// No description provided for @apiStyle. + /// + /// In en, this message translates to: + /// **'API Style'** + String get apiStyle; + + /// No description provided for @enterProviderName. + /// + /// In en, this message translates to: + /// **'Enter provider name'** + String get enterProviderName; + + /// No description provided for @providerNameRequired. + /// + /// In en, this message translates to: + /// **'Provider name is required'** + String get providerNameRequired; + + /// No description provided for @addModel. + /// + /// In en, this message translates to: + /// **'Add Model'** + String get addModel; + + /// No description provided for @modelName. + /// + /// In en, this message translates to: + /// **'Model Name'** + String get modelName; + + /// No description provided for @enterModelName. + /// + /// In en, this message translates to: + /// **'Enter model name'** + String get enterModelName; + + /// No description provided for @noApiConfigs. + /// + /// In en, this message translates to: + /// **'No API configurations available'** + String get noApiConfigs; + + /// No description provided for @add. + /// + /// In en, this message translates to: + /// **'Add'** + String get add; + + /// No description provided for @fetch. + /// + /// In en, this message translates to: + /// **'Fetch'** + String get fetch; + + /// No description provided for @on. + /// + /// In en, this message translates to: + /// **'ON'** + String get on; + + /// No description provided for @off. + /// + /// In en, this message translates to: + /// **'OFF'** + String get off; + + /// No description provided for @apiUrl. + /// + /// In en, this message translates to: + /// **'API URL'** + String get apiUrl; + + /// No description provided for @selectApiStyle. + /// + /// In en, this message translates to: + /// **'Please select API style'** + String get selectApiStyle; + + /// No description provided for @serverType. + /// + /// In en, this message translates to: + /// **'Server Type'** + String get serverType; + + /// No description provided for @reset. + /// + /// In en, this message translates to: + /// **'Reset'** + String get reset; + + /// No description provided for @start. + /// + /// In en, this message translates to: + /// **'Start'** + String get start; + + /// No description provided for @stop. + /// + /// In en, this message translates to: + /// **'stop'** + String get stop; + + /// No description provided for @search. + /// + /// In en, this message translates to: + /// **'Search'** + String get search; + + /// No description provided for @newVersionFound. + /// + /// In en, this message translates to: + /// **'New version {version} available'** + String newVersionFound(Object version); + + /// No description provided for @newVersionAvailable. + /// + /// In en, this message translates to: + /// **'New version available'** + String get newVersionAvailable; + + /// No description provided for @updateNow. + /// + /// In en, this message translates to: + /// **'Update Now'** + String get updateNow; + + /// No description provided for @updateLater. + /// + /// In en, this message translates to: + /// **'Update Later'** + String get updateLater; + + /// No description provided for @ignoreThisVersion. + /// + /// In en, this message translates to: + /// **'Ignore This Version'** + String get ignoreThisVersion; + + /// No description provided for @releaseNotes. + /// + /// In en, this message translates to: + /// **'Release Notes:'** + String get releaseNotes; + + /// No description provided for @openUrlFailed. + /// + /// In en, this message translates to: + /// **'Failed to open URL'** + String get openUrlFailed; + + /// No description provided for @checkingForUpdates. + /// + /// In en, this message translates to: + /// **'Checking for updates...'** + String get checkingForUpdates; + + /// No description provided for @checkUpdate. + /// + /// In en, this message translates to: + /// **'Update Check'** + String get checkUpdate; + + /// No description provided for @appDescription. + /// + /// In en, this message translates to: + /// **'ChatMCP is a cross-platform AI client, dedicated to making AI accessible to more people.'** + String get appDescription; + + /// No description provided for @visitWebsite. + /// + /// In en, this message translates to: + /// **'website'** + String get visitWebsite; + + /// No description provided for @aboutApp. + /// + /// In en, this message translates to: + /// **'About'** + String get aboutApp; + + /// No description provided for @networkError. + /// + /// In en, this message translates to: + /// **'Network error occurred'** + String get networkError; + + /// No description provided for @noElementError. + /// + /// In en, this message translates to: + /// **'No element found'** + String get noElementError; + + /// No description provided for @permissionError. + /// + /// In en, this message translates to: + /// **'Permission denied'** + String get permissionError; + + /// No description provided for @unknownError. + /// + /// In en, this message translates to: + /// **'Unknown error occurred'** + String get unknownError; + + /// No description provided for @timeoutError. + /// + /// In en, this message translates to: + /// **'Request timed out'** + String get timeoutError; + + /// No description provided for @notFoundError. + /// + /// In en, this message translates to: + /// **'Resource not found'** + String get notFoundError; + + /// No description provided for @invalidError. + /// + /// In en, this message translates to: + /// **'Invalid request'** + String get invalidError; + + /// No description provided for @unauthorizedError. + /// + /// In en, this message translates to: + /// **'Unauthorized access'** + String get unauthorizedError; + + /// No description provided for @minimize. + /// + /// In en, this message translates to: + /// **'Minimize'** + String get minimize; + + /// No description provided for @maximize. + /// + /// In en, this message translates to: + /// **'Maximize'** + String get maximize; + + /// No description provided for @conversationSettings. + /// + /// In en, this message translates to: + /// **'Conversation Settings'** + String get conversationSettings; + + /// No description provided for @maxMessages. + /// + /// In en, this message translates to: + /// **'Max Messages'** + String get maxMessages; + + /// No description provided for @maxMessagesDescription. + /// + /// In en, this message translates to: + /// **'Limit the maximum number of messages passed to LLM (1-1000)'** + String get maxMessagesDescription; + + /// No description provided for @maxLoops. + /// + /// In en, this message translates to: + /// **'Max Loops'** + String get maxLoops; + + /// No description provided for @maxLoopsDescription. + /// + /// In en, this message translates to: + /// **'Limit the maximum number of tool call loops to prevent infinite loops (1-1000)'** + String get maxLoopsDescription; + + /// No description provided for @mcpServers. + /// + /// In en, this message translates to: + /// **'MCP Servers'** + String get mcpServers; + + /// No description provided for @getApiKey. + /// + /// In en, this message translates to: + /// **'Get API Key'** + String get getApiKey; + + /// No description provided for @proxySettings. + /// + /// In en, this message translates to: + /// **'Proxy Settings'** + String get proxySettings; + + /// No description provided for @enableProxy. + /// + /// In en, this message translates to: + /// **'Enable Proxy'** + String get enableProxy; + + /// No description provided for @enableProxyDescription. + /// + /// In en, this message translates to: + /// **'When enabled, network requests will go through the configured proxy server'** + String get enableProxyDescription; + + /// No description provided for @proxyType. + /// + /// In en, this message translates to: + /// **'Proxy Type'** + String get proxyType; + + /// No description provided for @proxyHost. + /// + /// In en, this message translates to: + /// **'Proxy Host'** + String get proxyHost; + + /// No description provided for @proxyPort. + /// + /// In en, this message translates to: + /// **'Proxy Port'** + String get proxyPort; + + /// No description provided for @proxyUsername. + /// + /// In en, this message translates to: + /// **'Username'** + String get proxyUsername; + + /// No description provided for @proxyPassword. + /// + /// In en, this message translates to: + /// **'Password'** + String get proxyPassword; + + /// No description provided for @enterProxyHost. + /// + /// In en, this message translates to: + /// **'Enter proxy server address'** + String get enterProxyHost; + + /// No description provided for @enterProxyPort. + /// + /// In en, this message translates to: + /// **'Enter proxy port'** + String get enterProxyPort; + + /// No description provided for @enterProxyUsername. + /// + /// In en, this message translates to: + /// **'Enter username (optional)'** + String get enterProxyUsername; + + /// No description provided for @enterProxyPassword. + /// + /// In en, this message translates to: + /// **'Enter password (optional)'** + String get enterProxyPassword; + + /// No description provided for @proxyHostRequired. + /// + /// In en, this message translates to: + /// **'Proxy host is required'** + String get proxyHostRequired; + + /// No description provided for @proxyPortInvalid. + /// + /// In en, this message translates to: + /// **'Proxy port must be between 1-65535'** + String get proxyPortInvalid; + + /// No description provided for @saved. + /// + /// In en, this message translates to: + /// **'Saved'** + String get saved; + + /// No description provided for @dataSync. + /// + /// In en, this message translates to: + /// **'Data Sync'** + String get dataSync; + + /// No description provided for @syncServerRunning. + /// + /// In en, this message translates to: + /// **'Sync server is running'** + String get syncServerRunning; + + /// No description provided for @maintenance. + /// + /// In en, this message translates to: + /// **'Maintenance'** + String get maintenance; + + /// No description provided for @cleanupLogs. + /// + /// In en, this message translates to: + /// **'Cleanup Old Logs'** + String get cleanupLogs; + + /// No description provided for @cleanupLogsDescription. + /// + /// In en, this message translates to: + /// **'Cleanup log files'** + String get cleanupLogsDescription; + + /// No description provided for @confirmCleanup. + /// + /// In en, this message translates to: + /// **'Confirm Cleanup'** + String get confirmCleanup; + + /// No description provided for @confirmCleanupMessage. + /// + /// In en, this message translates to: + /// **'Are you sure you want to delete log files? This action cannot be undone.'** + String get confirmCleanupMessage; + + /// No description provided for @cleanupSuccess. + /// + /// In en, this message translates to: + /// **'Old logs cleanup completed'** + String get cleanupSuccess; + + /// No description provided for @cleanupFailed. + /// + /// In en, this message translates to: + /// **'Cleanup failed'** + String get cleanupFailed; + + /// No description provided for @syncServerStopped. + /// + /// In en, this message translates to: + /// **'Sync server stopped'** + String get syncServerStopped; + + /// No description provided for @scanQRToConnect. + /// + /// In en, this message translates to: + /// **'Other devices scan this QR code to connect:'** + String get scanQRToConnect; + + /// No description provided for @addressCopied. + /// + /// In en, this message translates to: + /// **'Address copied to clipboard'** + String get addressCopied; + + /// No description provided for @otherDevicesCanScan. + /// + /// In en, this message translates to: + /// **'Other devices can scan this QR code to connect quickly'** + String get otherDevicesCanScan; + + /// No description provided for @startServer. + /// + /// In en, this message translates to: + /// **'Start Server'** + String get startServer; + + /// No description provided for @stopServer. + /// + /// In en, this message translates to: + /// **'Stop Server'** + String get stopServer; + + /// No description provided for @connectToOtherDevices. + /// + /// In en, this message translates to: + /// **'Connect to Other Devices'** + String get connectToOtherDevices; + + /// No description provided for @scanQRCode. + /// + /// In en, this message translates to: + /// **'Scan QR Code to Connect'** + String get scanQRCode; + + /// No description provided for @connectionHistory. + /// + /// In en, this message translates to: + /// **'Connection History:'** + String get connectionHistory; + + /// No description provided for @connect. + /// + /// In en, this message translates to: + /// **'Connect'** + String get connect; + + /// No description provided for @manualInputAddress. + /// + /// In en, this message translates to: + /// **'Or manually enter server address:'** + String get manualInputAddress; + + /// No description provided for @serverAddress. + /// + /// In en, this message translates to: + /// **'Server Address'** + String get serverAddress; + + /// No description provided for @syncFromServer. + /// + /// In en, this message translates to: + /// **'Sync from Server'** + String get syncFromServer; + + /// No description provided for @pushToServer. + /// + /// In en, this message translates to: + /// **'Push to Server'** + String get pushToServer; + + /// No description provided for @usageInstructions. + /// + /// In en, this message translates to: + /// **'Usage Instructions'** + String get usageInstructions; + + /// No description provided for @desktopAsServer. + /// + /// In en, this message translates to: + /// **'Desktop as Server:'** + String get desktopAsServer; + + /// No description provided for @desktopStep1. + /// + /// In en, this message translates to: + /// **'1. Click \"Start Server\" button'** + String get desktopStep1; + + /// No description provided for @desktopStep2. + /// + /// In en, this message translates to: + /// **'2. Show QR code for mobile to scan'** + String get desktopStep2; + + /// No description provided for @desktopStep3. + /// + /// In en, this message translates to: + /// **'3. Mobile can sync data after scanning'** + String get desktopStep3; + + /// No description provided for @mobileConnect. + /// + /// In en, this message translates to: + /// **'Mobile Connection:'** + String get mobileConnect; + + /// No description provided for @mobileStep1. + /// + /// In en, this message translates to: + /// **'1. Click \"Scan QR Code to Connect\"'** + String get mobileStep1; + + /// No description provided for @mobileStep2. + /// + /// In en, this message translates to: + /// **'2. Scan the QR code displayed on desktop'** + String get mobileStep2; + + /// No description provided for @mobileStep3. + /// + /// In en, this message translates to: + /// **'3. Choose sync direction (upload/download)'** + String get mobileStep3; + + /// No description provided for @uploadDescription. + /// + /// In en, this message translates to: + /// **'• Upload: Push local device data to server'** + String get uploadDescription; + + /// No description provided for @downloadDescription. + /// + /// In en, this message translates to: + /// **'• Download: Get data from server to local device'** + String get downloadDescription; + + /// No description provided for @syncContent. + /// + /// In en, this message translates to: + /// **'• Sync Content: Chat history, settings, MCP configs'** + String get syncContent; + + /// No description provided for @syncServerStarted. + /// + /// In en, this message translates to: + /// **'Sync server started'** + String get syncServerStarted; + + /// No description provided for @syncServerStartFailed. + /// + /// In en, this message translates to: + /// **'Failed to start server'** + String get syncServerStartFailed; + + /// No description provided for @syncServerStopFailed. + /// + /// In en, this message translates to: + /// **'Failed to stop server'** + String get syncServerStopFailed; + + /// No description provided for @scanQRCodeTitle. + /// + /// In en, this message translates to: + /// **'Scan QR Code'** + String get scanQRCodeTitle; + + /// No description provided for @flashOn. + /// + /// In en, this message translates to: + /// **'Flash On'** + String get flashOn; + + /// No description provided for @flashOff. + /// + /// In en, this message translates to: + /// **'Flash Off'** + String get flashOff; + + /// No description provided for @aimQRCode. + /// + /// In en, this message translates to: + /// **'Aim the QR code at the scanning frame'** + String get aimQRCode; + + /// No description provided for @scanSyncQRCode. + /// + /// In en, this message translates to: + /// **'Scan the sync QR code displayed on desktop'** + String get scanSyncQRCode; + + /// No description provided for @manualInputAddressButton. + /// + /// In en, this message translates to: + /// **'Manual Input Address'** + String get manualInputAddressButton; + + /// No description provided for @manualInputServerAddress. + /// + /// In en, this message translates to: + /// **'Manually Input Server Address'** + String get manualInputServerAddress; + + /// No description provided for @enterValidServerAddress. + /// + /// In en, this message translates to: + /// **'Please enter a valid server address'** + String get enterValidServerAddress; + + /// No description provided for @scanSuccessConnectTo. + /// + /// In en, this message translates to: + /// **'Scan successful, connected to: {deviceName}'** + String scanSuccessConnectTo(Object deviceName); + + /// No description provided for @scanSuccessAddressFilled. + /// + /// In en, this message translates to: + /// **'Scan successful, server address filled'** + String get scanSuccessAddressFilled; + + /// No description provided for @scannerOpenFailed. + /// + /// In en, this message translates to: + /// **'Failed to open scanner'** + String get scannerOpenFailed; + + /// No description provided for @pleaseInputServerAddress. + /// + /// In en, this message translates to: + /// **'Please scan QR code or input server address first'** + String get pleaseInputServerAddress; + + /// No description provided for @connectingToServer. + /// + /// In en, this message translates to: + /// **'Connecting to server...'** + String get connectingToServer; + + /// No description provided for @downloadingData. + /// + /// In en, this message translates to: + /// **'Downloading data...'** + String get downloadingData; + + /// No description provided for @importingData. + /// + /// In en, this message translates to: + /// **'Importing data...'** + String get importingData; + + /// No description provided for @reinitializingData. + /// + /// In en, this message translates to: + /// **'Reinitializing app data...'** + String get reinitializingData; + + /// No description provided for @dataSyncSuccess. + /// + /// In en, this message translates to: + /// **'Data sync successful'** + String get dataSyncSuccess; + + /// No description provided for @preparingData. + /// + /// In en, this message translates to: + /// **'Preparing data...'** + String get preparingData; + + /// No description provided for @uploadingData. + /// + /// In en, this message translates to: + /// **'Uploading data...'** + String get uploadingData; + + /// No description provided for @dataPushSuccess. + /// + /// In en, this message translates to: + /// **'Data push successful'** + String get dataPushSuccess; + + /// No description provided for @syncFailed. + /// + /// In en, this message translates to: + /// **'Sync failed'** + String get syncFailed; + + /// No description provided for @pushFailed. + /// + /// In en, this message translates to: + /// **'Push failed'** + String get pushFailed; + + /// No description provided for @justNow. + /// + /// In en, this message translates to: + /// **'Just now'** + String get justNow; + + /// No description provided for @minutesAgo. + /// + /// In en, this message translates to: + /// **'{minutes} minutes ago'** + String minutesAgo(Object minutes); + + /// No description provided for @hoursAgo. + /// + /// In en, this message translates to: + /// **'{hours} hours ago'** + String hoursAgo(Object hours); + + /// No description provided for @daysAgo. + /// + /// In en, this message translates to: + /// **'{days} days ago'** + String daysAgo(Object days); + + /// No description provided for @serverSelected. + /// + /// In en, this message translates to: + /// **'Server selected: {deviceName}'** + String serverSelected(Object deviceName); + + /// No description provided for @connectionRecordDeleted. + /// + /// In en, this message translates to: + /// **'Connection record deleted'** + String get connectionRecordDeleted; + + /// No description provided for @viewAllConnections. + /// + /// In en, this message translates to: + /// **'View all {count} connections'** + String viewAllConnections(Object count); + + /// No description provided for @clearAllHistory. + /// + /// In en, this message translates to: + /// **'Clear All'** + String get clearAllHistory; + + /// No description provided for @clearAllConnectionHistory. + /// + /// In en, this message translates to: + /// **'All connection history cleared'** + String get clearAllConnectionHistory; + + /// No description provided for @unknownDevice. + /// + /// In en, this message translates to: + /// **'Unknown Device'** + String get unknownDevice; + + /// No description provided for @unknownPlatform. + /// + /// In en, this message translates to: + /// **'Unknown Platform'** + String get unknownPlatform; + + /// No description provided for @inmemory. + /// + /// In en, this message translates to: + /// **'In Memory'** + String get inmemory; + + /// No description provided for @toggleSidebar. + /// + /// In en, this message translates to: + /// **'Toggle Sidebar'** + String get toggleSidebar; + + /// No description provided for @deleteChat. + /// + /// In en, this message translates to: + /// **'Delete Chat'** + String get deleteChat; + + /// No description provided for @selectAll. + /// + /// In en, this message translates to: + /// **'Select All'** + String get selectAll; + + /// No description provided for @newChat. + /// + /// In en, this message translates to: + /// **'New Chat'** + String get newChat; + + /// No description provided for @send. + /// + /// In en, this message translates to: + /// **'Send'** + String get send; + + /// No description provided for @more. + /// + /// In en, this message translates to: + /// **'More'** + String get more; + + /// No description provided for @noMoreData. + /// + /// In en, this message translates to: + /// **'No more data'** + String get noMoreData; +} + +class _AppLocalizationsDelegate extends LocalizationsDelegate { + const _AppLocalizationsDelegate(); + + @override + Future load(Locale locale) { + return SynchronousFuture(lookupAppLocalizations(locale)); + } + + @override + bool isSupported(Locale locale) => ['de', 'en', 'tr', 'zh'].contains(locale.languageCode); + + @override + bool shouldReload(_AppLocalizationsDelegate old) => false; +} + +AppLocalizations lookupAppLocalizations(Locale locale) { + // Lookup logic when only language code is specified. + switch (locale.languageCode) { + case 'de': + return AppLocalizationsDe(); + case 'en': + return AppLocalizationsEn(); + case 'tr': + return AppLocalizationsTr(); + case 'zh': + return AppLocalizationsZh(); + } + + throw FlutterError( + 'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely ' + 'an issue with the localizations generation tool. Please file an issue ' + 'on GitHub with a reproducible sample app and the gen-l10n configuration ' + 'that was used.', + ); +} diff --git a/lib/generated/app_localizations_de.dart b/lib/generated/app_localizations_de.dart new file mode 100644 index 0000000..4243236 --- /dev/null +++ b/lib/generated/app_localizations_de.dart @@ -0,0 +1,878 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for German (`de`). +class AppLocalizationsDe extends AppLocalizations { + AppLocalizationsDe([String locale = 'de']) : super(locale); + + @override + String get settings => 'Einstellungen'; + + @override + String get general => 'Allgemein'; + + @override + String get providers => 'Anbieter'; + + @override + String get mcpServer => 'MCP Server'; + + @override + String get language => 'Sprache'; + + @override + String get theme => 'Design'; + + @override + String get dark => 'Dunkel'; + + @override + String get light => 'Hell'; + + @override + String get system => 'System'; + + @override + String get languageSettings => 'Spracheinstellungen'; + + @override + String get featureSettings => 'Funktionseinstellungen'; + + @override + String get enableArtifacts => 'Artifacts aktivieren'; + + @override + String get enableArtifactsDescription => 'Artifacts des KI-Assistenten in der Unterhaltung aktivieren, verbraucht mehr Token'; + + @override + String get enableToolUsage => 'Werkzeugnutzung aktivieren'; + + @override + String get enableToolUsageDescription => 'Nutzung von Werkzeugen in der Unterhaltung aktivieren, verbraucht mehr Token'; + + @override + String get themeSettings => 'Design-Einstellungen'; + + @override + String get lightTheme => 'Helles Design'; + + @override + String get darkTheme => 'Dunkles Design'; + + @override + String get followSystem => 'System folgen'; + + @override + String get showAvatar => 'Avatar anzeigen'; + + @override + String get showAssistantAvatar => 'Assistenten-Avatar anzeigen'; + + @override + String get showAssistantAvatarDescription => 'Avatar des KI-Assistenten in der Unterhaltung anzeigen'; + + @override + String get showUserAvatar => 'Benutzer-Avatar anzeigen'; + + @override + String get showUserAvatarDescription => 'Avatar des Benutzers in der Unterhaltung anzeigen'; + + @override + String get systemPrompt => 'System-Prompt'; + + @override + String get systemPromptDescription => + 'Dies ist der System-Prompt für die Unterhaltung mit dem KI-Assistenten, wird verwendet um Verhalten und Stil des Assistenten festzulegen'; + + @override + String get llmKey => 'LLM Schlüssel'; + + @override + String get toolKey => 'Werkzeug-Schlüssel'; + + @override + String get saveSettings => 'Einstellungen speichern'; + + @override + String get apiKey => 'API Schlüssel'; + + @override + String enterApiKey(Object provider) { + return 'Geben Sie Ihren $provider API Schlüssel ein'; + } + + @override + String get apiKeyValidation => 'API Schlüssel muss mindestens 10 Zeichen haben'; + + @override + String get apiEndpoint => 'API Endpunkt'; + + @override + String get enterApiEndpoint => 'API Endpunkt URL eingeben'; + + @override + String get apiVersion => 'API Version'; + + @override + String get enterApiVersion => 'API Version eingeben'; + + @override + String get platformNotSupported => 'Aktuelle Plattform unterstützt MCP Server nicht'; + + @override + String get mcpServerDesktopOnly => 'MCP Server unterstützt nur Desktop-Plattformen (Windows, macOS, Linux)'; + + @override + String get searchServer => 'Server suchen...'; + + @override + String get noServerConfigs => 'Keine Server-Konfigurationen gefunden'; + + @override + String get addProvider => 'Anbieter hinzufügen'; + + @override + String get refresh => 'Aktualisieren'; + + @override + String get install => 'Installieren'; + + @override + String get edit => 'Bearbeiten'; + + @override + String get delete => 'Löschen'; + + @override + String get command => 'Befehl oder Server-URL'; + + @override + String get arguments => 'Argumente'; + + @override + String get environmentVariables => 'Umgebungsvariablen'; + + @override + String get serverName => 'Servername'; + + @override + String get commandExample => 'Zum Beispiel: npx, uvx, https://mcpserver.com'; + + @override + String get argumentsExample => + 'Argumente durch Leerzeichen trennen, Anführungszeichen für Argumente mit Leerzeichen verwenden, zum Beispiel: -y obsidian-mcp \'/Users/username/Documents/Obsidian Vault\''; + + @override + String get envVarsFormat => 'Eine pro Zeile, Format: SCHLÜSSEL=WERT'; + + @override + String get cancel => 'Abbrechen'; + + @override + String get save => 'Speichern'; + + @override + String get confirmDelete => 'Löschen bestätigen'; + + @override + String confirmDeleteServer(Object name) { + return 'Sind Sie sicher, dass Sie Server \"$name\" löschen möchten?'; + } + + @override + String get error => 'Fehler'; + + @override + String commandNotExist(Object command, Object path) { + return 'Befehl \"$command\" existiert nicht, bitte zuerst installieren\n\nAktueller PATH:\n$path'; + } + + @override + String get all => 'Alle'; + + @override + String get installed => 'Installiert'; + + @override + String get modelSettings => 'Modell-Einstellungen'; + + @override + String temperature(Object value) { + return 'Temperatur: $value'; + } + + @override + String get temperatureTooltip => + 'Sampling-Temperatur kontrolliert die Zufälligkeit der Ausgabe:\n• 0.0: Geeignet für Code-Generierung und Mathe-Probleme\n• 1.0: Geeignet für Datenextraktion und Analyse\n• 1.3: Geeignet für allgemeine Unterhaltung und Übersetzung\n• 1.5: Geeignet für kreatives Schreiben und Poesie'; + + @override + String topP(Object value) { + return 'Top P: $value'; + } + + @override + String get topPTooltip => + 'Top P (Nucleus-Sampling) ist eine Alternative zur Temperatur. Das Modell berücksichtigt nur Token, deren kumulative Wahrscheinlichkeit P überschreitet. Es wird empfohlen, nicht gleichzeitig Temperatur und top_p zu ändern.'; + + @override + String get maxTokens => 'Max Token'; + + @override + String get maxTokensTooltip => + 'Maximale Anzahl zu generierender Token. Ein Token entspricht etwa 4 Zeichen. Längere Unterhaltungen benötigen mehr Token.'; + + @override + String frequencyPenalty(Object value) { + return 'Häufigkeits-Bestrafung: $value'; + } + + @override + String get frequencyPenaltyTooltip => + 'Häufigkeits-Bestrafungsparameter. Positive Werte bestrafen neue Token basierend auf ihrer vorhandenen Häufigkeit im Text, wodurch die Wahrscheinlichkeit des Modells verringert wird, denselben Inhalt wörtlich zu wiederholen.'; + + @override + String presencePenalty(Object value) { + return 'Präsenz-Bestrafung: $value'; + } + + @override + String get presencePenaltyTooltip => + 'Präsenz-Bestrafungsparameter. Positive Werte bestrafen neue Token basierend darauf, ob sie im Text erscheinen, wodurch die Wahrscheinlichkeit des Modells erhöht wird, über neue Themen zu sprechen.'; + + @override + String get enterMaxTokens => 'Max Token eingeben'; + + @override + String get share => 'Teilen'; + + @override + String get modelConfig => 'Modell-Konfiguration'; + + @override + String get debug => 'Debug'; + + @override + String get webSearchTest => 'Web-Suche Test'; + + @override + String get today => 'Heute'; + + @override + String get yesterday => 'Gestern'; + + @override + String get last7Days => 'Letzte 7 Tage'; + + @override + String get last30Days => 'Letzte 30 Tage'; + + @override + String get earlier => 'Früher'; + + @override + String get confirmDeleteSelected => 'Sind Sie sicher, dass Sie die ausgewählten Unterhaltungen löschen möchten?'; + + @override + String get confirmThisChat => 'Sind Sie sicher, dass Sie diese Unterhaltung löschen möchten?'; + + @override + String get ok => 'OK'; + + @override + String get askMeAnything => 'Fragen Sie mich alles...'; + + @override + String get uploadFiles => 'Dateien hochladen'; + + @override + String get welcomeMessage => 'Wie kann ich Ihnen heute helfen?'; + + @override + String get copy => 'Kopieren'; + + @override + String get copied => 'In Zwischenablage kopiert'; + + @override + String get retry => 'Wiederholen'; + + @override + String get brokenImage => 'Defektes Bild'; + + @override + String toolCall(Object name) { + return '$name aufrufen'; + } + + @override + String toolResult(Object name) { + return '$name Aufruf-Ergebnis'; + } + + @override + String get selectModel => 'Modell auswählen'; + + @override + String get close => 'Schließen'; + + @override + String get selectFromGallery => 'Aus Galerie auswählen'; + + @override + String get selectFile => 'Datei auswählen'; + + @override + String get uploadFile => 'Datei hochladen'; + + @override + String get openBrowser => 'Browser öffnen'; + + @override + String get codeCopiedToClipboard => 'Code in Zwischenablage kopiert'; + + @override + String get thinking => 'Denkt nach'; + + @override + String get thinkingEnd => 'Denken beendet'; + + @override + String get tool => 'Werkzeug'; + + @override + String get userCancelledToolCall => 'Benutzer hat Werkzeug-Aufruf abgebrochen'; + + @override + String get code => 'Code'; + + @override + String get preview => 'Vorschau'; + + @override + String get loadContentFailed => 'Laden des Inhalts fehlgeschlagen, bitte wiederholen'; + + @override + String get openingBrowser => 'Browser wird geöffnet'; + + @override + String get functionCallAuth => 'Werkzeug-Aufruf-Autorisierung'; + + @override + String get allowFunctionExecution => 'Möchten Sie die Ausführung des folgenden Werkzeugs erlauben:'; + + @override + String parameters(Object params) { + return 'Parameter: $params'; + } + + @override + String get allow => 'Erlauben'; + + @override + String get loadDiagramFailed => 'Laden des Diagramms fehlgeschlagen, bitte wiederholen'; + + @override + String get copiedToClipboard => 'In Zwischenablage kopiert'; + + @override + String get chinese => 'Chinesisch'; + + @override + String get turkish => 'Türkisch'; + + @override + String get functionRunning => 'Werkzeug wird ausgeführt...'; + + @override + String get thinkingProcess => 'Denkt nach'; + + @override + String get thinkingProcessWithDuration => 'Denkt nach, Zeit verbraucht'; + + @override + String get thinkingEndWithDuration => 'Denken beendet, Zeit verbraucht'; + + @override + String get thinkingEndComplete => 'Denken beendet'; + + @override + String seconds(Object seconds) { + return '${seconds}s'; + } + + @override + String get fieldRequired => 'Dieses Feld ist erforderlich'; + + @override + String get autoApprove => 'Automatisch genehmigen'; + + @override + String get verify => 'Schlüssel verifizieren'; + + @override + String get howToGet => 'Wie man es bekommt'; + + @override + String get modelList => 'Modell-Liste'; + + @override + String get enableModels => 'Modelle aktivieren'; + + @override + String get disableAllModels => 'Alle Modelle deaktivieren'; + + @override + String get saveSuccess => 'Einstellungen erfolgreich gespeichert'; + + @override + String get genTitleModel => 'Titel generieren'; + + @override + String get serverNameTooLong => 'Servername darf nicht länger als 50 Zeichen sein'; + + @override + String get confirm => 'Bestätigen'; + + @override + String get providerName => 'Anbieter-Name'; + + @override + String get apiStyle => 'API-Stil'; + + @override + String get enterProviderName => 'Anbieter-Name eingeben'; + + @override + String get providerNameRequired => 'Anbieter-Name ist erforderlich'; + + @override + String get addModel => 'Modell hinzufügen'; + + @override + String get modelName => 'Modell-Name'; + + @override + String get enterModelName => 'Modell-Name eingeben'; + + @override + String get noApiConfigs => 'Keine API-Konfigurationen verfügbar'; + + @override + String get add => 'Hinzufügen'; + + @override + String get fetch => 'Abrufen'; + + @override + String get on => 'AN'; + + @override + String get off => 'AUS'; + + @override + String get apiUrl => 'API URL'; + + @override + String get selectApiStyle => 'Bitte API-Stil auswählen'; + + @override + String get serverType => 'Server-Typ'; + + @override + String get reset => 'Zurücksetzen'; + + @override + String get start => 'Starten'; + + @override + String get stop => 'Stoppen'; + + @override + String get search => 'Suchen'; + + @override + String newVersionFound(Object version) { + return 'Neue Version $version verfügbar'; + } + + @override + String get newVersionAvailable => 'Neue Version verfügbar'; + + @override + String get updateNow => 'Jetzt aktualisieren'; + + @override + String get updateLater => 'Später aktualisieren'; + + @override + String get ignoreThisVersion => 'Diese Version ignorieren'; + + @override + String get releaseNotes => 'Versionshinweise:'; + + @override + String get openUrlFailed => 'Öffnen der URL fehlgeschlagen'; + + @override + String get checkingForUpdates => 'Suche nach Updates...'; + + @override + String get checkUpdate => 'Update-Prüfung'; + + @override + String get appDescription => 'ChatMCP ist ein plattformübergreifender KI-Client, der darauf abzielt, KI für mehr Menschen zugänglich zu machen.'; + + @override + String get visitWebsite => 'Website'; + + @override + String get aboutApp => 'Über die App'; + + @override + String get networkError => 'Netzwerkfehler aufgetreten'; + + @override + String get noElementError => 'Kein Element gefunden'; + + @override + String get permissionError => 'Zugriff verweigert'; + + @override + String get unknownError => 'Unbekannter Fehler aufgetreten'; + + @override + String get timeoutError => 'Anfrage-Timeout'; + + @override + String get notFoundError => 'Ressource nicht gefunden'; + + @override + String get invalidError => 'Ungültige Anfrage'; + + @override + String get unauthorizedError => 'Unbefugter Zugriff'; + + @override + String get minimize => 'Minimieren'; + + @override + String get maximize => 'Maximieren'; + + @override + String get conversationSettings => 'Unterhaltungs-Einstellungen'; + + @override + String get maxMessages => 'Max Nachrichten'; + + @override + String get maxMessagesDescription => 'Maximale Anzahl von Nachrichten, die an LLM weitergegeben werden (1-1000)'; + + @override + String get maxLoops => 'Max Schleifen'; + + @override + String get maxLoopsDescription => 'Maximale Anzahl von Werkzeug-Aufruf-Schleifen, um Endlosschleifen zu verhindern (1-1000)'; + + @override + String get mcpServers => 'MCP Server'; + + @override + String get getApiKey => 'API Schlüssel erhalten'; + + @override + String get proxySettings => 'Proxy-Einstellungen'; + + @override + String get enableProxy => 'Proxy aktivieren'; + + @override + String get enableProxyDescription => 'Wenn aktiviert, werden Netzwerkanfragen über den konfigurierten Proxy-Server geleitet'; + + @override + String get proxyType => 'Proxy-Typ'; + + @override + String get proxyHost => 'Proxy-Host'; + + @override + String get proxyPort => 'Proxy-Port'; + + @override + String get proxyUsername => 'Benutzername'; + + @override + String get proxyPassword => 'Passwort'; + + @override + String get enterProxyHost => 'Proxy-Server-Adresse eingeben'; + + @override + String get enterProxyPort => 'Proxy-Port eingeben'; + + @override + String get enterProxyUsername => 'Benutzername eingeben (optional)'; + + @override + String get enterProxyPassword => 'Passwort eingeben (optional)'; + + @override + String get proxyHostRequired => 'Proxy-Host ist erforderlich'; + + @override + String get proxyPortInvalid => 'Proxy-Port muss zwischen 1-65535 liegen'; + + @override + String get saved => 'Gespeichert'; + + @override + String get dataSync => 'Daten-Synchronisation'; + + @override + String get syncServerRunning => 'Sync-Server läuft'; + + @override + String get maintenance => 'Wartung'; + + @override + String get cleanupLogs => 'Alte Logs aufräumen'; + + @override + String get cleanupLogsDescription => 'Log-Dateien aufräumen'; + + @override + String get confirmCleanup => 'Aufräumen bestätigen'; + + @override + String get confirmCleanupMessage => 'Sind Sie sicher, dass Sie Log-Dateien löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.'; + + @override + String get cleanupSuccess => 'Aufräumen alter Logs abgeschlossen'; + + @override + String get cleanupFailed => 'Aufräumen fehlgeschlagen'; + + @override + String get syncServerStopped => 'Sync-Server gestoppt'; + + @override + String get scanQRToConnect => 'Andere Geräte scannen diesen QR-Code zum Verbinden:'; + + @override + String get addressCopied => 'Adresse in Zwischenablage kopiert'; + + @override + String get otherDevicesCanScan => 'Andere Geräte können diesen QR-Code scannen, um sich schnell zu verbinden'; + + @override + String get startServer => 'Server starten'; + + @override + String get stopServer => 'Server stoppen'; + + @override + String get connectToOtherDevices => 'Mit anderen Geräten verbinden'; + + @override + String get scanQRCode => 'QR-Code scannen zum Verbinden'; + + @override + String get connectionHistory => 'Verbindungs-Verlauf:'; + + @override + String get connect => 'Verbinden'; + + @override + String get manualInputAddress => 'Oder Server-Adresse manuell eingeben:'; + + @override + String get serverAddress => 'Server-Adresse'; + + @override + String get syncFromServer => 'Vom Server synchronisieren'; + + @override + String get pushToServer => 'Zum Server übertragen'; + + @override + String get usageInstructions => 'Nutzungsanweisungen'; + + @override + String get desktopAsServer => 'Desktop als Server:'; + + @override + String get desktopStep1 => '1. \"Server starten\" Button klicken'; + + @override + String get desktopStep2 => '2. QR-Code für Mobile zum Scannen anzeigen'; + + @override + String get desktopStep3 => '3. Mobile kann nach dem Scannen Daten synchronisieren'; + + @override + String get mobileConnect => 'Mobile-Verbindung:'; + + @override + String get mobileStep1 => '1. \"QR-Code scannen zum Verbinden\" klicken'; + + @override + String get mobileStep2 => '2. QR-Code auf Desktop scannen'; + + @override + String get mobileStep3 => '3. Sync-Richtung wählen (upload/download)'; + + @override + String get uploadDescription => '• Upload: Lokale Gerätedaten zum Server übertragen'; + + @override + String get downloadDescription => '• Download: Daten vom Server auf lokales Gerät holen'; + + @override + String get syncContent => '• Sync-Inhalt: Chat-Verlauf, Einstellungen, MCP-Konfigurationen'; + + @override + String get syncServerStarted => 'Sync-Server gestartet'; + + @override + String get syncServerStartFailed => 'Server-Start fehlgeschlagen'; + + @override + String get syncServerStopFailed => 'Server-Stopp fehlgeschlagen'; + + @override + String get scanQRCodeTitle => 'QR-Code scannen'; + + @override + String get flashOn => 'Blitz an'; + + @override + String get flashOff => 'Blitz aus'; + + @override + String get aimQRCode => 'QR-Code auf den Scan-Rahmen richten'; + + @override + String get scanSyncQRCode => 'Sync QR-Code auf Desktop scannen'; + + @override + String get manualInputAddressButton => 'Adresse manuell eingeben'; + + @override + String get manualInputServerAddress => 'Server-Adresse manuell eingeben'; + + @override + String get enterValidServerAddress => 'Bitte gültige Server-Adresse eingeben'; + + @override + String scanSuccessConnectTo(Object deviceName) { + return 'Scan erfolgreich, verbunden mit: $deviceName'; + } + + @override + String get scanSuccessAddressFilled => 'Scan erfolgreich, Server-Adresse ausgefüllt'; + + @override + String get scannerOpenFailed => 'Scanner-Öffnung fehlgeschlagen'; + + @override + String get pleaseInputServerAddress => 'Bitte zuerst QR-Code scannen oder Server-Adresse eingeben'; + + @override + String get connectingToServer => 'Verbindung zum Server...'; + + @override + String get downloadingData => 'Daten werden heruntergeladen...'; + + @override + String get importingData => 'Daten werden importiert...'; + + @override + String get reinitializingData => 'App-Daten werden neu initialisiert...'; + + @override + String get dataSyncSuccess => 'Daten-Synchronisation erfolgreich'; + + @override + String get preparingData => 'Daten werden vorbereitet...'; + + @override + String get uploadingData => 'Daten werden hochgeladen...'; + + @override + String get dataPushSuccess => 'Daten-Übertragung erfolgreich'; + + @override + String get syncFailed => 'Synchronisation fehlgeschlagen'; + + @override + String get pushFailed => 'Übertragung fehlgeschlagen'; + + @override + String get justNow => 'Gerade eben'; + + @override + String minutesAgo(Object minutes) { + return 'vor $minutes Minuten'; + } + + @override + String hoursAgo(Object hours) { + return 'vor $hours Stunden'; + } + + @override + String daysAgo(Object days) { + return 'vor $days Tagen'; + } + + @override + String serverSelected(Object deviceName) { + return 'Server ausgewählt: $deviceName'; + } + + @override + String get connectionRecordDeleted => 'Verbindungseintrag gelöscht'; + + @override + String viewAllConnections(Object count) { + return 'Alle $count Verbindungen anzeigen'; + } + + @override + String get clearAllHistory => 'Alles löschen'; + + @override + String get clearAllConnectionHistory => 'Gesamter Verbindungs-Verlauf gelöscht'; + + @override + String get unknownDevice => 'Unbekanntes Gerät'; + + @override + String get unknownPlatform => 'Unbekannte Plattform'; + + @override + String get inmemory => 'Im Speicher'; + + @override + String get toggleSidebar => 'Seitenleiste umschalten'; + + @override + String get deleteChat => 'Chat löschen'; + + @override + String get selectAll => 'Alle auswählen'; + + @override + String get newChat => 'Neuer Chat'; + + @override + String get send => 'Senden'; + + @override + String get more => 'Mehr'; + + @override + String get noMoreData => 'Keine weiteren Daten'; +} diff --git a/lib/generated/app_localizations_en.dart b/lib/generated/app_localizations_en.dart new file mode 100644 index 0000000..2ef7fb7 --- /dev/null +++ b/lib/generated/app_localizations_en.dart @@ -0,0 +1,878 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for English (`en`). +class AppLocalizationsEn extends AppLocalizations { + AppLocalizationsEn([String locale = 'en']) : super(locale); + + @override + String get settings => 'Settings'; + + @override + String get general => 'General'; + + @override + String get providers => 'Providers'; + + @override + String get mcpServer => 'MCP Server'; + + @override + String get language => 'Language'; + + @override + String get theme => 'Theme'; + + @override + String get dark => 'Dark'; + + @override + String get light => 'Light'; + + @override + String get system => 'System'; + + @override + String get languageSettings => 'Language Settings'; + + @override + String get featureSettings => 'Feature Settings'; + + @override + String get enableArtifacts => 'Enable Artifacts'; + + @override + String get enableArtifactsDescription => 'Enable the artifacts of the AI assistant in the conversation, will use more tokens'; + + @override + String get enableToolUsage => 'Enable Tool Usage'; + + @override + String get enableToolUsageDescription => 'Enable the usage of tools in the conversation, will use more tokens'; + + @override + String get themeSettings => 'Theme Settings'; + + @override + String get lightTheme => 'Light Theme'; + + @override + String get darkTheme => 'Dark Theme'; + + @override + String get followSystem => 'Follow System'; + + @override + String get showAvatar => 'Show Avatar'; + + @override + String get showAssistantAvatar => 'Show Assistant Avatar'; + + @override + String get showAssistantAvatarDescription => 'Show the avatar of the AI assistant in the conversation'; + + @override + String get showUserAvatar => 'Show User Avatar'; + + @override + String get showUserAvatarDescription => 'Show the avatar of the user in the conversation'; + + @override + String get systemPrompt => 'System Prompt'; + + @override + String get systemPromptDescription => + 'This is the system prompt for the conversation with the AI assistant, used to set the behavior and style of the assistant'; + + @override + String get llmKey => 'LLM Key'; + + @override + String get toolKey => 'Tool Key'; + + @override + String get saveSettings => 'Save Settings'; + + @override + String get apiKey => 'API Key'; + + @override + String enterApiKey(Object provider) { + return 'Enter your $provider API Key'; + } + + @override + String get apiKeyValidation => 'API Key must be at least 10 characters'; + + @override + String get apiEndpoint => 'API Endpoint'; + + @override + String get enterApiEndpoint => 'Enter API endpoint URL'; + + @override + String get apiVersion => 'API Version'; + + @override + String get enterApiVersion => 'Enter API Version'; + + @override + String get platformNotSupported => 'Current platform does not support MCP Server'; + + @override + String get mcpServerDesktopOnly => 'MCP Server only supports desktop platforms (Windows, macOS, Linux)'; + + @override + String get searchServer => 'Search server...'; + + @override + String get noServerConfigs => 'No server configurations found'; + + @override + String get addProvider => 'Add Provider'; + + @override + String get refresh => 'Refresh'; + + @override + String get install => 'Install'; + + @override + String get edit => 'Edit'; + + @override + String get delete => 'Delete'; + + @override + String get command => 'Command Or Sever Url'; + + @override + String get arguments => 'Arguments'; + + @override + String get environmentVariables => 'Environment Variables'; + + @override + String get serverName => 'Server Name'; + + @override + String get commandExample => 'For example: npx, uvx, https://mcpserver.com'; + + @override + String get argumentsExample => + 'Separate arguments with spaces, use quotes for arguments with spaces, for example: -y obsidian-mcp \'/Users/username/Documents/Obsidian Vault\''; + + @override + String get envVarsFormat => 'One per line, format: KEY=VALUE'; + + @override + String get cancel => 'Cancel'; + + @override + String get save => 'Save'; + + @override + String get confirmDelete => 'Confirm Delete'; + + @override + String confirmDeleteServer(Object name) { + return 'Are you sure you want to delete server \"$name\" ?'; + } + + @override + String get error => 'Error'; + + @override + String commandNotExist(Object command, Object path) { + return 'Command \"$command\" does not exist, please install it first\n\nCurrent PATH:\n$path'; + } + + @override + String get all => 'All'; + + @override + String get installed => 'Installed'; + + @override + String get modelSettings => 'Model Settings'; + + @override + String temperature(Object value) { + return 'Temperature: $value'; + } + + @override + String get temperatureTooltip => + 'Sampling temperature controls the randomness of output:\n• 0.0: Suitable for code generation and math problems\n• 1.0: Suitable for data extraction and analysis\n• 1.3: Suitable for general conversation and translation\n• 1.5: Suitable for creative writing and poetry'; + + @override + String topP(Object value) { + return 'Top P: $value'; + } + + @override + String get topPTooltip => + 'Top P (nucleus sampling) is an alternative to temperature. The model only considers tokens whose cumulative probability exceeds P. It is recommended not to modify both temperature and top_p at the same time.'; + + @override + String get maxTokens => 'Max Tokens'; + + @override + String get maxTokensTooltip => + 'Maximum number of tokens to generate. One token is approximately equal to 4 characters. Longer conversations require more tokens.'; + + @override + String frequencyPenalty(Object value) { + return 'Frequency Penalty: $value'; + } + + @override + String get frequencyPenaltyTooltip => + 'Frequency penalty parameter. Positive values penalize new tokens based on their existing frequency in the text, decreasing the model\'s likelihood of repeating the same content verbatim.'; + + @override + String presencePenalty(Object value) { + return 'Presence Penalty: $value'; + } + + @override + String get presencePenaltyTooltip => + 'Presence penalty parameter. Positive values penalize new tokens based on whether they appear in the text, increasing the model\'s likelihood of talking about new topics.'; + + @override + String get enterMaxTokens => 'Enter max tokens'; + + @override + String get share => 'Share'; + + @override + String get modelConfig => 'Model Config'; + + @override + String get debug => 'Debug'; + + @override + String get webSearchTest => 'Web Search Test'; + + @override + String get today => 'Today'; + + @override + String get yesterday => 'Yesterday'; + + @override + String get last7Days => 'Last 7 Days'; + + @override + String get last30Days => 'Last 30 Days'; + + @override + String get earlier => 'Earlier'; + + @override + String get confirmDeleteSelected => 'Are you sure you want to delete the selected conversations?'; + + @override + String get confirmThisChat => 'Are you sure you want to delete the this conversations'; + + @override + String get ok => 'OK'; + + @override + String get askMeAnything => 'Ask me anything...'; + + @override + String get uploadFiles => 'Upload Files'; + + @override + String get welcomeMessage => 'How can I help you today?'; + + @override + String get copy => 'Copy'; + + @override + String get copied => 'Copied to clipboard'; + + @override + String get retry => 'Retry'; + + @override + String get brokenImage => 'Broken Image'; + + @override + String toolCall(Object name) { + return 'call $name'; + } + + @override + String toolResult(Object name) { + return 'call $name result'; + } + + @override + String get selectModel => 'Select Model'; + + @override + String get close => 'Close'; + + @override + String get selectFromGallery => 'Select from Gallery'; + + @override + String get selectFile => 'Select File'; + + @override + String get uploadFile => 'Upload File'; + + @override + String get openBrowser => 'Open Browser'; + + @override + String get codeCopiedToClipboard => 'Code copied to clipboard'; + + @override + String get thinking => 'Thinking'; + + @override + String get thinkingEnd => 'Thinking End'; + + @override + String get tool => 'Tool'; + + @override + String get userCancelledToolCall => 'Tool execution failed'; + + @override + String get code => 'Code'; + + @override + String get preview => 'Preview'; + + @override + String get loadContentFailed => 'Failed to load content, please retry'; + + @override + String get openingBrowser => 'Opening browser'; + + @override + String get functionCallAuth => 'Tool Call Authorization'; + + @override + String get allowFunctionExecution => 'Do you want to allow the following tool to execute:'; + + @override + String parameters(Object params) { + return 'Parameters: $params'; + } + + @override + String get allow => 'Allow'; + + @override + String get loadDiagramFailed => 'Failed to load diagram, please retry'; + + @override + String get copiedToClipboard => 'Copied to clipboard'; + + @override + String get chinese => 'Chinese'; + + @override + String get turkish => 'Turkish'; + + @override + String get functionRunning => 'Running Tool...'; + + @override + String get thinkingProcess => 'Thinking'; + + @override + String get thinkingProcessWithDuration => 'Thinking, time used'; + + @override + String get thinkingEndWithDuration => 'Thinking finished, time used'; + + @override + String get thinkingEndComplete => 'Thinking finished'; + + @override + String seconds(Object seconds) { + return '${seconds}s'; + } + + @override + String get fieldRequired => 'This field is required'; + + @override + String get autoApprove => 'Auto Approve'; + + @override + String get verify => 'Verify Key'; + + @override + String get howToGet => 'How to get'; + + @override + String get modelList => 'Model List'; + + @override + String get enableModels => 'Enable Models'; + + @override + String get disableAllModels => 'Disable All Models'; + + @override + String get saveSuccess => 'Settings saved successfully'; + + @override + String get genTitleModel => 'Gen Title'; + + @override + String get serverNameTooLong => 'Server name cannot exceed 50 characters'; + + @override + String get confirm => 'Confirm'; + + @override + String get providerName => 'Provider Name'; + + @override + String get apiStyle => 'API Style'; + + @override + String get enterProviderName => 'Enter provider name'; + + @override + String get providerNameRequired => 'Provider name is required'; + + @override + String get addModel => 'Add Model'; + + @override + String get modelName => 'Model Name'; + + @override + String get enterModelName => 'Enter model name'; + + @override + String get noApiConfigs => 'No API configurations available'; + + @override + String get add => 'Add'; + + @override + String get fetch => 'Fetch'; + + @override + String get on => 'ON'; + + @override + String get off => 'OFF'; + + @override + String get apiUrl => 'API URL'; + + @override + String get selectApiStyle => 'Please select API style'; + + @override + String get serverType => 'Server Type'; + + @override + String get reset => 'Reset'; + + @override + String get start => 'Start'; + + @override + String get stop => 'stop'; + + @override + String get search => 'Search'; + + @override + String newVersionFound(Object version) { + return 'New version $version available'; + } + + @override + String get newVersionAvailable => 'New version available'; + + @override + String get updateNow => 'Update Now'; + + @override + String get updateLater => 'Update Later'; + + @override + String get ignoreThisVersion => 'Ignore This Version'; + + @override + String get releaseNotes => 'Release Notes:'; + + @override + String get openUrlFailed => 'Failed to open URL'; + + @override + String get checkingForUpdates => 'Checking for updates...'; + + @override + String get checkUpdate => 'Update Check'; + + @override + String get appDescription => 'ChatMCP is a cross-platform AI client, dedicated to making AI accessible to more people.'; + + @override + String get visitWebsite => 'website'; + + @override + String get aboutApp => 'About'; + + @override + String get networkError => 'Network error occurred'; + + @override + String get noElementError => 'No element found'; + + @override + String get permissionError => 'Permission denied'; + + @override + String get unknownError => 'Unknown error occurred'; + + @override + String get timeoutError => 'Request timed out'; + + @override + String get notFoundError => 'Resource not found'; + + @override + String get invalidError => 'Invalid request'; + + @override + String get unauthorizedError => 'Unauthorized access'; + + @override + String get minimize => 'Minimize'; + + @override + String get maximize => 'Maximize'; + + @override + String get conversationSettings => 'Conversation Settings'; + + @override + String get maxMessages => 'Max Messages'; + + @override + String get maxMessagesDescription => 'Limit the maximum number of messages passed to LLM (1-1000)'; + + @override + String get maxLoops => 'Max Loops'; + + @override + String get maxLoopsDescription => 'Limit the maximum number of tool call loops to prevent infinite loops (1-1000)'; + + @override + String get mcpServers => 'MCP Servers'; + + @override + String get getApiKey => 'Get API Key'; + + @override + String get proxySettings => 'Proxy Settings'; + + @override + String get enableProxy => 'Enable Proxy'; + + @override + String get enableProxyDescription => 'When enabled, network requests will go through the configured proxy server'; + + @override + String get proxyType => 'Proxy Type'; + + @override + String get proxyHost => 'Proxy Host'; + + @override + String get proxyPort => 'Proxy Port'; + + @override + String get proxyUsername => 'Username'; + + @override + String get proxyPassword => 'Password'; + + @override + String get enterProxyHost => 'Enter proxy server address'; + + @override + String get enterProxyPort => 'Enter proxy port'; + + @override + String get enterProxyUsername => 'Enter username (optional)'; + + @override + String get enterProxyPassword => 'Enter password (optional)'; + + @override + String get proxyHostRequired => 'Proxy host is required'; + + @override + String get proxyPortInvalid => 'Proxy port must be between 1-65535'; + + @override + String get saved => 'Saved'; + + @override + String get dataSync => 'Data Sync'; + + @override + String get syncServerRunning => 'Sync server is running'; + + @override + String get maintenance => 'Maintenance'; + + @override + String get cleanupLogs => 'Cleanup Old Logs'; + + @override + String get cleanupLogsDescription => 'Cleanup log files'; + + @override + String get confirmCleanup => 'Confirm Cleanup'; + + @override + String get confirmCleanupMessage => 'Are you sure you want to delete log files? This action cannot be undone.'; + + @override + String get cleanupSuccess => 'Old logs cleanup completed'; + + @override + String get cleanupFailed => 'Cleanup failed'; + + @override + String get syncServerStopped => 'Sync server stopped'; + + @override + String get scanQRToConnect => 'Other devices scan this QR code to connect:'; + + @override + String get addressCopied => 'Address copied to clipboard'; + + @override + String get otherDevicesCanScan => 'Other devices can scan this QR code to connect quickly'; + + @override + String get startServer => 'Start Server'; + + @override + String get stopServer => 'Stop Server'; + + @override + String get connectToOtherDevices => 'Connect to Other Devices'; + + @override + String get scanQRCode => 'Scan QR Code to Connect'; + + @override + String get connectionHistory => 'Connection History:'; + + @override + String get connect => 'Connect'; + + @override + String get manualInputAddress => 'Or manually enter server address:'; + + @override + String get serverAddress => 'Server Address'; + + @override + String get syncFromServer => 'Sync from Server'; + + @override + String get pushToServer => 'Push to Server'; + + @override + String get usageInstructions => 'Usage Instructions'; + + @override + String get desktopAsServer => 'Desktop as Server:'; + + @override + String get desktopStep1 => '1. Click \"Start Server\" button'; + + @override + String get desktopStep2 => '2. Show QR code for mobile to scan'; + + @override + String get desktopStep3 => '3. Mobile can sync data after scanning'; + + @override + String get mobileConnect => 'Mobile Connection:'; + + @override + String get mobileStep1 => '1. Click \"Scan QR Code to Connect\"'; + + @override + String get mobileStep2 => '2. Scan the QR code displayed on desktop'; + + @override + String get mobileStep3 => '3. Choose sync direction (upload/download)'; + + @override + String get uploadDescription => '• Upload: Push local device data to server'; + + @override + String get downloadDescription => '• Download: Get data from server to local device'; + + @override + String get syncContent => '• Sync Content: Chat history, settings, MCP configs'; + + @override + String get syncServerStarted => 'Sync server started'; + + @override + String get syncServerStartFailed => 'Failed to start server'; + + @override + String get syncServerStopFailed => 'Failed to stop server'; + + @override + String get scanQRCodeTitle => 'Scan QR Code'; + + @override + String get flashOn => 'Flash On'; + + @override + String get flashOff => 'Flash Off'; + + @override + String get aimQRCode => 'Aim the QR code at the scanning frame'; + + @override + String get scanSyncQRCode => 'Scan the sync QR code displayed on desktop'; + + @override + String get manualInputAddressButton => 'Manual Input Address'; + + @override + String get manualInputServerAddress => 'Manually Input Server Address'; + + @override + String get enterValidServerAddress => 'Please enter a valid server address'; + + @override + String scanSuccessConnectTo(Object deviceName) { + return 'Scan successful, connected to: $deviceName'; + } + + @override + String get scanSuccessAddressFilled => 'Scan successful, server address filled'; + + @override + String get scannerOpenFailed => 'Failed to open scanner'; + + @override + String get pleaseInputServerAddress => 'Please scan QR code or input server address first'; + + @override + String get connectingToServer => 'Connecting to server...'; + + @override + String get downloadingData => 'Downloading data...'; + + @override + String get importingData => 'Importing data...'; + + @override + String get reinitializingData => 'Reinitializing app data...'; + + @override + String get dataSyncSuccess => 'Data sync successful'; + + @override + String get preparingData => 'Preparing data...'; + + @override + String get uploadingData => 'Uploading data...'; + + @override + String get dataPushSuccess => 'Data push successful'; + + @override + String get syncFailed => 'Sync failed'; + + @override + String get pushFailed => 'Push failed'; + + @override + String get justNow => 'Just now'; + + @override + String minutesAgo(Object minutes) { + return '$minutes minutes ago'; + } + + @override + String hoursAgo(Object hours) { + return '$hours hours ago'; + } + + @override + String daysAgo(Object days) { + return '$days days ago'; + } + + @override + String serverSelected(Object deviceName) { + return 'Server selected: $deviceName'; + } + + @override + String get connectionRecordDeleted => 'Connection record deleted'; + + @override + String viewAllConnections(Object count) { + return 'View all $count connections'; + } + + @override + String get clearAllHistory => 'Clear All'; + + @override + String get clearAllConnectionHistory => 'All connection history cleared'; + + @override + String get unknownDevice => 'Unknown Device'; + + @override + String get unknownPlatform => 'Unknown Platform'; + + @override + String get inmemory => 'In Memory'; + + @override + String get toggleSidebar => 'Toggle Sidebar'; + + @override + String get deleteChat => 'Delete Chat'; + + @override + String get selectAll => 'Select All'; + + @override + String get newChat => 'New Chat'; + + @override + String get send => 'Send'; + + @override + String get more => 'More'; + + @override + String get noMoreData => 'No more data'; +} diff --git a/lib/generated/app_localizations_tr.dart b/lib/generated/app_localizations_tr.dart new file mode 100644 index 0000000..a56d71f --- /dev/null +++ b/lib/generated/app_localizations_tr.dart @@ -0,0 +1,877 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Turkish (`tr`). +class AppLocalizationsTr extends AppLocalizations { + AppLocalizationsTr([String locale = 'tr']) : super(locale); + + @override + String get settings => 'Ayarlar'; + + @override + String get general => 'Genel'; + + @override + String get providers => 'Sağlayıcılar'; + + @override + String get mcpServer => 'MCP Sunucusu'; + + @override + String get language => 'Dil'; + + @override + String get theme => 'Tema'; + + @override + String get dark => 'Koyu'; + + @override + String get light => 'Açık'; + + @override + String get system => 'Sistem'; + + @override + String get languageSettings => 'Dil Ayarları'; + + @override + String get featureSettings => 'Özellik Ayarları'; + + @override + String get enableArtifacts => 'Artifact\'leri Etkinleştir'; + + @override + String get enableArtifactsDescription => 'Sohbette yapay zeka asistanının Artifact\'lerini etkinleştirir, bu özellik daha fazla token kullanır.'; + + @override + String get enableToolUsage => 'Araç Kullanımını Etkinleştir'; + + @override + String get enableToolUsageDescription => 'Sohbette araçların kullanımını etkinleştirir, bu özellik daha fazla token kullanır.'; + + @override + String get themeSettings => 'Tema Ayarları'; + + @override + String get lightTheme => 'Açık Tema'; + + @override + String get darkTheme => 'Koyu Tema'; + + @override + String get followSystem => 'Sistem Ayarlarına Uygula'; + + @override + String get showAvatar => 'Avatar Gösterimi'; + + @override + String get showAssistantAvatar => 'Asistan Avatarını Göster'; + + @override + String get showAssistantAvatarDescription => 'Sohbette yapay zeka asistanının avatarını gösterir.'; + + @override + String get showUserAvatar => 'Kullanıcı Avatarını Göster'; + + @override + String get showUserAvatarDescription => 'Sohbette kullanıcının avatarını gösterir.'; + + @override + String get systemPrompt => 'Sistem Prompt'; + + @override + String get systemPromptDescription => 'Bu, yapay zeka asistanının davranışını ve tarzını belirlemek için kullanılan sistem yönergesidir.'; + + @override + String get llmKey => 'LLM Anahtarı'; + + @override + String get toolKey => 'Araç Anahtarı'; + + @override + String get saveSettings => 'Ayarları Kaydet'; + + @override + String get apiKey => 'API Anahtarı'; + + @override + String enterApiKey(Object provider) { + return '$provider API Anahtarınızı Girin'; + } + + @override + String get apiKeyValidation => 'API Anahtarı en az 10 karakter olmalıdır.'; + + @override + String get apiEndpoint => 'API Uç Noktası'; + + @override + String get enterApiEndpoint => 'API uç noktası URL\'sini girin'; + + @override + String get apiVersion => 'API Versiyonu'; + + @override + String get enterApiVersion => 'API versiyonunu girin'; + + @override + String get platformNotSupported => 'Mevcut platform MCP Sunucusunu desteklemiyor.'; + + @override + String get mcpServerDesktopOnly => 'MCP Sunucusu yalnızca masaüstü platformlarını (Windows, macOS, Linux) destekler.'; + + @override + String get searchServer => 'Sunucu ara...'; + + @override + String get noServerConfigs => 'Sunucu yapılandırması bulunamadı.'; + + @override + String get addProvider => 'Sağlayıcı Ekle'; + + @override + String get refresh => 'Yenile'; + + @override + String get install => 'Yükle'; + + @override + String get edit => 'Düzenle'; + + @override + String get delete => 'Sil'; + + @override + String get command => 'Komut veya Sunucu Adresi'; + + @override + String get arguments => 'Argümanlar'; + + @override + String get environmentVariables => 'Ortam Değişkenleri'; + + @override + String get serverName => 'Sunucu Adı'; + + @override + String get commandExample => 'Örneğin: npx, uvx, https://mcpserver.com'; + + @override + String get argumentsExample => + 'Argümanları boşlukla ayırın. Boşluk içerenler için tırnak işareti kullanın, örn: -y obsidian-mcp \'/Kullanıcılar/kullaniciadi/Belgeler/Obsidian Kasası\''; + + @override + String get envVarsFormat => 'Her satıra bir tane, ANAHTAR=DEĞER formatında'; + + @override + String get cancel => 'İptal'; + + @override + String get save => 'Kaydet'; + + @override + String get confirmDelete => 'Silmeyi Onayla'; + + @override + String confirmDeleteServer(Object name) { + return '\"$name\" adlı sunucuyu silmek istediğinize emin misiniz?'; + } + + @override + String get error => 'Hata'; + + @override + String commandNotExist(Object command, Object path) { + return '\"$command\" komutu bulunamadı. Lütfen önce bu komutu yükleyin.\n\nMevcut PATH:\n$path'; + } + + @override + String get all => 'Tümü'; + + @override + String get installed => 'Yüklü'; + + @override + String get modelSettings => 'Model Ayarları'; + + @override + String temperature(Object value) { + return 'Temperature: $value'; + } + + @override + String get temperatureTooltip => + 'Temperature , çıktının rastgeleliğini kontrol eder:\n• 0.0: Kod üretimi ve matematiksel problemler için idealdir.\n• 1.0: Veri çıkarma ve analiz için uygundur.\n• 1.3: Genel sohbet ve çeviri için uygundur.\n• 1.5: Yaratıcı yazarlık ve şiir için harikadır.'; + + @override + String topP(Object value) { + return 'Çekirdek Örnekleme (Top P): $value'; + } + + @override + String get topPTooltip => + 'Top P (Çekirdek Örnekleme), sıcaklık parametresine bir alternatiftir. Model, yalnızca kümülatif olasılığı P\'yi aşan token\'ları dikkate alır. Sıcaklık ve top_p değerlerini aynı anda değiştirmeniz önerilmez.'; + + @override + String get maxTokens => 'Maksimum Token'; + + @override + String get maxTokensTooltip => + 'Üretilecek maksimum token sayısı. Bir token yaklaşık 4 karaktere eşittir. Daha uzun sohbetler daha fazla token gerektirir.'; + + @override + String frequencyPenalty(Object value) { + return 'Frequency Cezası: $value'; + } + + @override + String get frequencyPenaltyTooltip => + 'Frequency cezası parametresi. Pozitif değerler, metindeki mevcut frekanslarına göre yeni token\'ları cezalandırarak modelin aynı içeriği kelimesi kelimesine tekrarlama olasılığını azaltır.'; + + @override + String presencePenalty(Object value) { + return 'Presence Cezası: $value'; + } + + @override + String get presencePenaltyTooltip => + 'Presence cezası parametresi. Pozitif değerler, metinde daha önce geçip geçmediklerine göre yeni token\'ları cezalandırarak modelin yeni konular hakkında konuşma olasılığını artırır.'; + + @override + String get enterMaxTokens => 'Maksimum token sayısını girin'; + + @override + String get share => 'Paylaş'; + + @override + String get modelConfig => 'Model Ayarları'; + + @override + String get debug => 'Debug Modu'; + + @override + String get webSearchTest => 'Web Araması Testi'; + + @override + String get today => 'Bugün'; + + @override + String get yesterday => 'Dün'; + + @override + String get last7Days => 'Son 7 Gün'; + + @override + String get last30Days => 'Son 30 Gün'; + + @override + String get earlier => 'Daha Eski'; + + @override + String get confirmDeleteSelected => 'Seçili sohbetleri silmek istediğinize emin misiniz?'; + + @override + String get confirmThisChat => 'Bu sohbetleri silmek istediğinize emin misiniz?'; + + @override + String get ok => 'Tamam'; + + @override + String get askMeAnything => 'Aklındakini sor...'; + + @override + String get uploadFiles => 'Dosya Yükle'; + + @override + String get welcomeMessage => 'Bugün sana nasıl yardımcı olabilirim?'; + + @override + String get copy => 'Kopyala'; + + @override + String get copied => 'Panoya kopyalandı!'; + + @override + String get retry => 'Yeniden Dene'; + + @override + String get brokenImage => 'Bozuk Resim'; + + @override + String toolCall(Object name) { + return '$name çağrılıyor'; + } + + @override + String toolResult(Object name) { + return '$name çağrısının sonucu'; + } + + @override + String get selectModel => 'Model Seç'; + + @override + String get close => 'Kapat'; + + @override + String get selectFromGallery => 'Galeriden Seç'; + + @override + String get selectFile => 'Dosya Seç'; + + @override + String get uploadFile => 'Dosya Yükle'; + + @override + String get openBrowser => 'Tarayıcıda Aç'; + + @override + String get codeCopiedToClipboard => 'Kod panoya kopyalandı.'; + + @override + String get thinking => 'Düşünüyor...'; + + @override + String get thinkingEnd => 'Düşünme tamamlandı.'; + + @override + String get tool => 'Araç'; + + @override + String get userCancelledToolCall => 'Araç çalıştırılamadı.'; + + @override + String get code => 'Kod'; + + @override + String get preview => 'Önizleme'; + + @override + String get loadContentFailed => 'İçerik yüklenemedi, lütfen tekrar deneyin.'; + + @override + String get openingBrowser => 'Tarayıcı açılıyor...'; + + @override + String get functionCallAuth => 'Araç Kullanım İzni'; + + @override + String get allowFunctionExecution => 'Aşağıdaki aracın çalışmasına izin veriyor musunuz?'; + + @override + String parameters(Object params) { + return 'Parametreler: $params'; + } + + @override + String get allow => 'İzin Ver'; + + @override + String get loadDiagramFailed => 'Diyagram yüklenemedi, lütfen tekrar deneyin.'; + + @override + String get copiedToClipboard => 'Panoya kopyalandı.'; + + @override + String get chinese => 'Çince'; + + @override + String get turkish => 'Türkçe'; + + @override + String get functionRunning => 'Araç çalıştırılıyor...'; + + @override + String get thinkingProcess => 'Düşünme Süreci ...'; + + @override + String get thinkingProcessWithDuration => 'Düşünme, geçen süre'; + + @override + String get thinkingEndWithDuration => 'Düşünme tamamlandı, geçen süre'; + + @override + String get thinkingEndComplete => 'Düşünme tamamlandı'; + + @override + String seconds(Object seconds) { + return '${seconds}sn'; + } + + @override + String get fieldRequired => 'Bu alan zorunludur.'; + + @override + String get autoApprove => 'Otomatik Onayla'; + + @override + String get verify => 'Anahtarı Doğrula'; + + @override + String get howToGet => 'Nasıl alınır?'; + + @override + String get modelList => 'Model Listesi'; + + @override + String get enableModels => 'Modelleri Etkinleştir'; + + @override + String get disableAllModels => 'Tüm Modelleri Devre Dışı Bırak'; + + @override + String get saveSuccess => 'Ayarlar başarıyla kaydedildi!'; + + @override + String get genTitleModel => 'Başlık Oluşturma Modeli'; + + @override + String get serverNameTooLong => 'Sunucu adı 50 karakterden uzun olamaz.'; + + @override + String get confirm => 'Onayla'; + + @override + String get providerName => 'Sağlayıcı Adı'; + + @override + String get apiStyle => 'API Tarzı'; + + @override + String get enterProviderName => 'Sağlayıcı adını girin'; + + @override + String get providerNameRequired => 'Sağlayıcı adı zorunludur.'; + + @override + String get addModel => 'Model Ekle'; + + @override + String get modelName => 'Model Adı'; + + @override + String get enterModelName => 'Model adını girin'; + + @override + String get noApiConfigs => 'Kullanılabilir API yapılandırması yok.'; + + @override + String get add => 'Ekle'; + + @override + String get fetch => 'Getir'; + + @override + String get on => 'AÇIK'; + + @override + String get off => 'KAPALI'; + + @override + String get apiUrl => 'API Adresi'; + + @override + String get selectApiStyle => 'Lütfen bir API tarzı seçin'; + + @override + String get serverType => 'Sunucu Türü'; + + @override + String get reset => 'Sıfırla'; + + @override + String get start => 'Başlat'; + + @override + String get stop => 'Durdur'; + + @override + String get search => 'Ara'; + + @override + String newVersionFound(Object version) { + return 'Yeni bir $version sürümü mevcut!'; + } + + @override + String get newVersionAvailable => 'Yeni Sürüm Mevcut'; + + @override + String get updateNow => 'Şimdi Güncelle'; + + @override + String get updateLater => 'Daha Sonra'; + + @override + String get ignoreThisVersion => 'Bu Sürümü Atla'; + + @override + String get releaseNotes => 'Sürüm Notları:'; + + @override + String get openUrlFailed => 'Bağlantı açılamadı.'; + + @override + String get checkingForUpdates => 'Güncellemeler kontrol ediliyor...'; + + @override + String get checkUpdate => 'Güncellemeleri Kontrol Et'; + + @override + String get appDescription => 'ChatMCP, yapay zekayı daha fazla insana ulaştırmayı hedefleyen, platformlar arası bir yapay zeka istemcisidir.'; + + @override + String get visitWebsite => 'Web Sitesi'; + + @override + String get aboutApp => 'Hakkında'; + + @override + String get networkError => 'Ağ bağlantı hatası. Lütfen internetinizi kontrol edip tekrar deneyin.'; + + @override + String get noElementError => 'Eşleşen içerik bulunamadı, lütfen tekrar deneyin.'; + + @override + String get permissionError => 'Yetersiz izin. Lütfen ayarlarınızı kontrol edin.'; + + @override + String get unknownError => 'Bilinmeyen bir hata oluştu.'; + + @override + String get timeoutError => 'İstek zaman aşımına uğradı. Lütfen bir süre sonra tekrar deneyin.'; + + @override + String get notFoundError => 'İstenen kaynak bulunamadı.'; + + @override + String get invalidError => 'Geçersiz istek veya parametre.'; + + @override + String get unauthorizedError => 'Yetkisiz erişim. Lütfen izinlerinizi kontrol edin.'; + + @override + String get minimize => 'Küçült'; + + @override + String get maximize => 'Büyüt'; + + @override + String get conversationSettings => 'Sohbet Ayarları'; + + @override + String get maxMessages => 'Maksimum Mesaj Sayısı'; + + @override + String get maxMessagesDescription => 'LLM\'e gönderilecek maksimum mesaj sayısını sınırlar (1-1000).'; + + @override + String get maxLoops => 'Maksimum Döngü Sayısı'; + + @override + String get maxLoopsDescription => 'Sonsuz döngüleri önlemek için araç çağırma döngü sayısını sınırlar (1-1000).'; + + @override + String get mcpServers => 'MCP Sunucuları'; + + @override + String get getApiKey => 'API Anahtarı Al'; + + @override + String get proxySettings => 'Proxy Ayarları'; + + @override + String get enableProxy => 'Proxy\'yi Etkinleştir'; + + @override + String get enableProxyDescription => 'Etkinleştirildiğinde, ağ istekleri yapılandırılan proxy sunucu üzerinden gidecektir'; + + @override + String get proxyType => 'Proxy Türü'; + + @override + String get proxyHost => 'Proxy Adresi'; + + @override + String get proxyPort => 'Proxy Portu'; + + @override + String get proxyUsername => 'Kullanıcı Adı'; + + @override + String get proxyPassword => 'Şifre'; + + @override + String get enterProxyHost => 'Proxy sunucu adresini girin'; + + @override + String get enterProxyPort => 'Proxy portunu girin'; + + @override + String get enterProxyUsername => 'Kullanıcı adını girin (isteğe bağlı)'; + + @override + String get enterProxyPassword => 'Şifreyi girin (isteğe bağlı)'; + + @override + String get proxyHostRequired => 'Proxy adresi zorunludur'; + + @override + String get proxyPortInvalid => 'Proxy portu 1-65535 arasında olmalıdır'; + + @override + String get saved => 'Kaydedildi'; + + @override + String get dataSync => 'Veri Senkronizasyonu'; + + @override + String get syncServerRunning => 'Senkronizasyon sunucusu çalışıyor'; + + @override + String get maintenance => 'Bakım'; + + @override + String get cleanupLogs => 'Eski Günlükleri Temizle'; + + @override + String get cleanupLogsDescription => 'Günlük dosyalarını temizle'; + + @override + String get confirmCleanup => 'Temizlemeyi Onayla'; + + @override + String get confirmCleanupMessage => 'Günlük dosyalarını silmek istediğinize emin misiniz? Bu işlem geri alınamaz.'; + + @override + String get cleanupSuccess => 'Eski günlükler temizlendi'; + + @override + String get cleanupFailed => 'Temizleme başarısız'; + + @override + String get syncServerStopped => 'Senkronizasyon sunucusu durduruldu'; + + @override + String get scanQRToConnect => 'Diğer cihazlar bağlanmak için bu QR kodu tarayabilir:'; + + @override + String get addressCopied => 'Adres panoya kopyalandı'; + + @override + String get otherDevicesCanScan => 'Diğer cihazlar hızlı bağlantı için bu QR kodu tarayabilir'; + + @override + String get startServer => 'Sunucuyu Başlat'; + + @override + String get stopServer => 'Sunucuyu Durdur'; + + @override + String get connectToOtherDevices => 'Diğer Cihazlara Bağlan'; + + @override + String get scanQRCode => 'QR Kod Tarayarak Bağlan'; + + @override + String get connectionHistory => 'Bağlantı Geçmişi:'; + + @override + String get connect => 'Bağlan'; + + @override + String get manualInputAddress => 'Veya sunucu adresini manuel olarak girin:'; + + @override + String get serverAddress => 'Sunucu Adresi'; + + @override + String get syncFromServer => 'Sunucudan Senkronize Et'; + + @override + String get pushToServer => 'Sunucuya Gönder'; + + @override + String get usageInstructions => 'Kullanım Talimatları'; + + @override + String get desktopAsServer => 'Masaüstü Sunucu Olarak:'; + + @override + String get desktopStep1 => '1. \"Sunucuyu Başlat\" düğmesine tıklayın'; + + @override + String get desktopStep2 => '2. Mobil cihazın taraması için QR kodu gösterin'; + + @override + String get desktopStep3 => '3. Mobil cihaz tarama sonrası veri senkronizasyonu yapabilir'; + + @override + String get mobileConnect => 'Mobil Bağlantı:'; + + @override + String get mobileStep1 => '1. \"QR Kod Tarayarak Bağlan\" düğmesine tıklayın'; + + @override + String get mobileStep2 => '2. Masaüstünde gösterilen QR kodu tarayın'; + + @override + String get mobileStep3 => '3. Senkronizasyon yönünü seçin (yükleme/indirme)'; + + @override + String get uploadDescription => '• Yükleme: Yerel cihaz verilerini sunucuya gönder'; + + @override + String get downloadDescription => '• İndirme: Sunucudan yerel cihaza veri al'; + + @override + String get syncContent => '• Senkronizasyon İçeriği: Sohbet geçmişi, ayarlar, MCP yapılandırmaları'; + + @override + String get syncServerStarted => 'Senkronizasyon sunucusu başlatıldı'; + + @override + String get syncServerStartFailed => 'Sunucu başlatılamadı'; + + @override + String get syncServerStopFailed => 'Sunucu durdurulamadı'; + + @override + String get scanQRCodeTitle => 'QR Kod Tarama'; + + @override + String get flashOn => 'Flaş Açık'; + + @override + String get flashOff => 'Flaş Kapalı'; + + @override + String get aimQRCode => 'QR kodu tarama çerçevesine hizalayın'; + + @override + String get scanSyncQRCode => 'Masaüstünde gösterilen senkronizasyon QR kodunu tarayın'; + + @override + String get manualInputAddressButton => 'Manuel Adres Girişi'; + + @override + String get manualInputServerAddress => 'Sunucu Adresini Manuel Olarak Girin'; + + @override + String get enterValidServerAddress => 'Lütfen geçerli bir sunucu adresi girin'; + + @override + String scanSuccessConnectTo(Object deviceName) { + return 'Tarama başarılı, bağlanıldı: $deviceName'; + } + + @override + String get scanSuccessAddressFilled => 'Tarama başarılı, sunucu adresi dolduruldu'; + + @override + String get scannerOpenFailed => 'Tarayıcı açılamadı'; + + @override + String get pleaseInputServerAddress => 'Lütfen önce QR kodu tarayın veya sunucu adresi girin'; + + @override + String get connectingToServer => 'Sunucuya bağlanıyor...'; + + @override + String get downloadingData => 'Veri indiriliyor...'; + + @override + String get importingData => 'Veri içe aktarılıyor...'; + + @override + String get reinitializingData => 'Uygulama verileri yeniden başlatılıyor...'; + + @override + String get dataSyncSuccess => 'Veri senkronizasyonu başarılı'; + + @override + String get preparingData => 'Veri hazırlanıyor...'; + + @override + String get uploadingData => 'Veri yükleniyor...'; + + @override + String get dataPushSuccess => 'Veri gönderimi başarılı'; + + @override + String get syncFailed => 'Senkronizasyon başarısız'; + + @override + String get pushFailed => 'Gönderim başarısız'; + + @override + String get justNow => 'Az önce'; + + @override + String minutesAgo(Object minutes) { + return '$minutes dakika önce'; + } + + @override + String hoursAgo(Object hours) { + return '$hours saat önce'; + } + + @override + String daysAgo(Object days) { + return '$days gün önce'; + } + + @override + String serverSelected(Object deviceName) { + return 'Sunucu seçildi: $deviceName'; + } + + @override + String get connectionRecordDeleted => 'Bağlantı kaydı silindi'; + + @override + String viewAllConnections(Object count) { + return 'Tüm $count bağlantıyı görüntüle'; + } + + @override + String get clearAllHistory => 'Tümünü Temizle'; + + @override + String get clearAllConnectionHistory => 'Tüm bağlantı geçmişi temizlendi'; + + @override + String get unknownDevice => 'Bilinmeyen Cihaz'; + + @override + String get unknownPlatform => 'Bilinmeyen Platform'; + + @override + String get inmemory => 'En Memoria'; + + @override + String get toggleSidebar => 'Kenar Çubuğunu Değiştir'; + + @override + String get deleteChat => 'Sohbeti Sil'; + + @override + String get selectAll => 'Tümünü Seç'; + + @override + String get newChat => 'Yeni Sohbet'; + + @override + String get send => 'Gönder'; + + @override + String get more => 'Daha Fazla'; + + @override + String get noMoreData => 'Daha fazla veri yok'; +} diff --git a/lib/generated/app_localizations_zh.dart b/lib/generated/app_localizations_zh.dart new file mode 100644 index 0000000..769f02e --- /dev/null +++ b/lib/generated/app_localizations_zh.dart @@ -0,0 +1,871 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Chinese (`zh`). +class AppLocalizationsZh extends AppLocalizations { + AppLocalizationsZh([String locale = 'zh']) : super(locale); + + @override + String get settings => '设置'; + + @override + String get general => '通用'; + + @override + String get providers => '服务提供商'; + + @override + String get mcpServer => 'MCP 服务器'; + + @override + String get language => '语言'; + + @override + String get theme => '主题'; + + @override + String get dark => '深色'; + + @override + String get light => '浅色'; + + @override + String get system => '跟随系统'; + + @override + String get languageSettings => '语言设置'; + + @override + String get featureSettings => '功能设置'; + + @override + String get enableArtifacts => '启用人工制品'; + + @override + String get enableArtifactsDescription => '在对话中启用 AI 助手的人工制品,这将使用更多的令牌'; + + @override + String get enableToolUsage => '启用工具使用'; + + @override + String get enableToolUsageDescription => '在对话中启用工具的使用,这将使用更多的令牌'; + + @override + String get themeSettings => '主题设置'; + + @override + String get lightTheme => '浅色主题'; + + @override + String get darkTheme => '深色主题'; + + @override + String get followSystem => '跟随系统'; + + @override + String get showAvatar => '显示头像'; + + @override + String get showAssistantAvatar => '显示助手头像'; + + @override + String get showAssistantAvatarDescription => '在对话中显示 AI 助手的头像'; + + @override + String get showUserAvatar => '显示用户头像'; + + @override + String get showUserAvatarDescription => '在对话中显示用户的头像'; + + @override + String get systemPrompt => '系统提示词'; + + @override + String get systemPromptDescription => '这是与 AI 助手对话的系统提示词,用于设置助手的行为和风格'; + + @override + String get llmKey => 'LLM 密钥'; + + @override + String get toolKey => '工具密钥'; + + @override + String get saveSettings => '保存设置'; + + @override + String get apiKey => 'API 密钥'; + + @override + String enterApiKey(Object provider) { + return '请输入您的 $provider API 密钥'; + } + + @override + String get apiKeyValidation => 'API 密钥必须至少包含 10 个字符'; + + @override + String get apiEndpoint => 'API 端点'; + + @override + String get enterApiEndpoint => '请输入 API 端点 URL'; + + @override + String get apiVersion => 'API 版本'; + + @override + String get enterApiVersion => '输入 API 版本'; + + @override + String get platformNotSupported => '当前平台不支持 MCP Server'; + + @override + String get mcpServerDesktopOnly => 'MCP Server 仅支持桌面端(Windows、macOS、Linux)'; + + @override + String get searchServer => '搜索服务器...'; + + @override + String get noServerConfigs => '未找到服务器配置'; + + @override + String get addProvider => '添加服务商'; + + @override + String get refresh => '刷新'; + + @override + String get install => '安装'; + + @override + String get edit => '编辑'; + + @override + String get delete => '删除'; + + @override + String get command => '命令 或 服务地址'; + + @override + String get arguments => '参数'; + + @override + String get environmentVariables => '环境变量'; + + @override + String get serverName => '服务器名称'; + + @override + String get commandExample => '例如:npx、uvx、https://mcpserver.com'; + + @override + String get argumentsExample => '参数之间用空格分隔,包含空格的参数请用引号包围,例如:-y obsidian-mcp \'/Users/username/Documents/Obsidian Vault\''; + + @override + String get envVarsFormat => '每行一个,格式:KEY=VALUE'; + + @override + String get cancel => '取消'; + + @override + String get save => '保存'; + + @override + String get confirmDelete => '确认删除'; + + @override + String confirmDeleteServer(Object name) { + return '您确定要删除服务器 \"$name\" 吗?'; + } + + @override + String get error => '错误'; + + @override + String commandNotExist(Object command, Object path) { + return '命令 \"$command\" 不存在,请先安装\n\n当前 PATH:\n$path'; + } + + @override + String get all => '全部'; + + @override + String get installed => '已安装'; + + @override + String get modelSettings => '模型设置'; + + @override + String temperature(Object value) { + return '采样温度: $value'; + } + + @override + String get temperatureTooltip => '采样温度控制输出的随机性:\n• 0.0:适合代码生成和数学解题\n• 1.0:适合数据抽取和分析\n• 1.3:适合通用对话和翻译\n• 1.5:适合创意写作和诗歌创作'; + + @override + String topP(Object value) { + return '核采样: $value'; + } + + @override + String get topPTooltip => 'Top P(核采样)是temperature的替代方案。模型只考虑累积概率超过P的标记。建议不要同时修改temperature和top_p。'; + + @override + String get maxTokens => '最大令牌数'; + + @override + String get maxTokensTooltip => '生成的最大令牌数。一个令牌大约等于4个字符。较长的对话需要更多的令牌。'; + + @override + String frequencyPenalty(Object value) { + return '频率惩罚: $value'; + } + + @override + String get frequencyPenaltyTooltip => '频率惩罚参数。正值会根据新标记在文本中的现有频率来惩罚它们,降低模型逐字重复同样内容的可能性。'; + + @override + String presencePenalty(Object value) { + return '存在惩罚: $value'; + } + + @override + String get presencePenaltyTooltip => '存在惩罚参数。正值会根据新标记是否出现在文本中来惩罚它们,增加模型谈论新主题的可能性。'; + + @override + String get enterMaxTokens => '输入最大令牌数'; + + @override + String get share => '分享'; + + @override + String get modelConfig => '模型配置'; + + @override + String get debug => '调试'; + + @override + String get webSearchTest => '网页搜索测试'; + + @override + String get today => '今天'; + + @override + String get yesterday => '昨天'; + + @override + String get last7Days => '前 7 天'; + + @override + String get last30Days => '前 30 天'; + + @override + String get earlier => '更早'; + + @override + String get confirmDeleteSelected => '确定要删除选中的对话吗?'; + + @override + String get confirmThisChat => '您确定要删除这些对话吗?'; + + @override + String get ok => '确定'; + + @override + String get askMeAnything => '问我任何问题...'; + + @override + String get uploadFiles => '上传文件'; + + @override + String get welcomeMessage => '今天我能帮您什么?'; + + @override + String get copy => '复制'; + + @override + String get copied => '已复制到剪贴板'; + + @override + String get retry => '重试'; + + @override + String get brokenImage => '图片损坏'; + + @override + String toolCall(Object name) { + return '调用 $name'; + } + + @override + String toolResult(Object name) { + return '调用 $name 结果'; + } + + @override + String get selectModel => '选择模型'; + + @override + String get close => '关闭'; + + @override + String get selectFromGallery => '从图库选择'; + + @override + String get selectFile => '选择文件'; + + @override + String get uploadFile => '上传文件'; + + @override + String get openBrowser => '打开浏览器'; + + @override + String get codeCopiedToClipboard => '代码已复制到剪贴板'; + + @override + String get thinking => '思考中'; + + @override + String get thinkingEnd => '思考结束'; + + @override + String get tool => '工具'; + + @override + String get userCancelledToolCall => '工具执行失败'; + + @override + String get code => '代码'; + + @override + String get preview => '预览'; + + @override + String get loadContentFailed => '加载内容失败,请重试'; + + @override + String get openingBrowser => '正在打开浏览器'; + + @override + String get functionCallAuth => '工具调用授权'; + + @override + String get allowFunctionExecution => '是否允许执行以下工具:'; + + @override + String parameters(Object params) { + return '参数: $params'; + } + + @override + String get allow => '允许'; + + @override + String get loadDiagramFailed => '加载图表失败,请重试'; + + @override + String get copiedToClipboard => '已复制到剪贴板'; + + @override + String get chinese => '中文'; + + @override + String get turkish => '土耳其语'; + + @override + String get functionRunning => '正在执行工具...'; + + @override + String get thinkingProcess => '思考中'; + + @override + String get thinkingProcessWithDuration => '思考中, 用时'; + + @override + String get thinkingEndWithDuration => '思考完成,用时'; + + @override + String get thinkingEndComplete => '思考完成'; + + @override + String seconds(Object seconds) { + return '$seconds秒'; + } + + @override + String get fieldRequired => '此字段为必填项'; + + @override + String get autoApprove => '自动批准'; + + @override + String get verify => '验证密钥'; + + @override + String get howToGet => '如何获取'; + + @override + String get modelList => '模型列表'; + + @override + String get enableModels => '启用模型'; + + @override + String get disableAllModels => '禁用所有模型'; + + @override + String get saveSuccess => '设置保存成功'; + + @override + String get genTitleModel => '标题生成'; + + @override + String get serverNameTooLong => '服务名称长度不能超过 50 个字符'; + + @override + String get confirm => '确认'; + + @override + String get providerName => '提供商名称'; + + @override + String get apiStyle => 'API 风格'; + + @override + String get enterProviderName => '输入提供商名称'; + + @override + String get providerNameRequired => '提供商名称为必填项'; + + @override + String get addModel => '添加模型'; + + @override + String get modelName => '模型名称'; + + @override + String get enterModelName => '输入模型名称'; + + @override + String get noApiConfigs => '无可用的 API 配置'; + + @override + String get add => '添加'; + + @override + String get fetch => '获取'; + + @override + String get on => '开启'; + + @override + String get off => '关闭'; + + @override + String get apiUrl => 'API 地址'; + + @override + String get selectApiStyle => '请选择 API 风格'; + + @override + String get serverType => '服务类型'; + + @override + String get reset => '重置'; + + @override + String get start => '启动'; + + @override + String get stop => '停止'; + + @override + String get search => '搜索'; + + @override + String newVersionFound(Object version) { + return '发现新版本 $version'; + } + + @override + String get newVersionAvailable => '发现新版本'; + + @override + String get updateNow => '立即更新'; + + @override + String get updateLater => '稍后更新'; + + @override + String get ignoreThisVersion => '忽略此版本'; + + @override + String get releaseNotes => '更新内容:'; + + @override + String get openUrlFailed => '无法打开链接'; + + @override + String get checkingForUpdates => '正在检查更新...'; + + @override + String get checkUpdate => '检查更新'; + + @override + String get appDescription => 'ChatMCP 是一款跨平台的 AI 客户端,致力于让更多人方便地使用 AI。'; + + @override + String get visitWebsite => '站点'; + + @override + String get aboutApp => '关于'; + + @override + String get networkError => '网络连接问题,请检查网络后重试'; + + @override + String get noElementError => '未找到匹配内容,请重试'; + + @override + String get permissionError => '权限不足,请检查设置'; + + @override + String get unknownError => '发生未知错误'; + + @override + String get timeoutError => '请求超时,请稍后重试'; + + @override + String get notFoundError => '未找到请求的资源'; + + @override + String get invalidError => '无效的请求或参数'; + + @override + String get unauthorizedError => '未授权访问,请检查权限'; + + @override + String get minimize => '最小化'; + + @override + String get maximize => '最大化'; + + @override + String get conversationSettings => '对话设置'; + + @override + String get maxMessages => '最大消息数'; + + @override + String get maxMessagesDescription => '限制传递给 LLM 的最大消息数量 (1-1000)'; + + @override + String get maxLoops => '最大循环数'; + + @override + String get maxLoopsDescription => '限制工具调用的最大循环次数,防止无限循环 (1-1000)'; + + @override + String get mcpServers => 'MCP 服务器'; + + @override + String get getApiKey => '获取 API 秘钥'; + + @override + String get proxySettings => '代理设置'; + + @override + String get enableProxy => '启用代理'; + + @override + String get enableProxyDescription => '启用代理后,网络请求将通过配置的代理服务器'; + + @override + String get proxyType => '代理类型'; + + @override + String get proxyHost => '代理地址'; + + @override + String get proxyPort => '代理端口'; + + @override + String get proxyUsername => '用户名'; + + @override + String get proxyPassword => '密码'; + + @override + String get enterProxyHost => '请输入代理服务器地址'; + + @override + String get enterProxyPort => '请输入代理端口'; + + @override + String get enterProxyUsername => '请输入用户名(可选)'; + + @override + String get enterProxyPassword => '请输入密码(可选)'; + + @override + String get proxyHostRequired => '代理地址为必填项'; + + @override + String get proxyPortInvalid => '代理端口必须在 1-65535 之间'; + + @override + String get saved => '已保存'; + + @override + String get dataSync => '数据同步'; + + @override + String get syncServerRunning => '同步服务器运行中'; + + @override + String get maintenance => '维护'; + + @override + String get cleanupLogs => '清理旧日志'; + + @override + String get cleanupLogsDescription => '清理日志文件'; + + @override + String get confirmCleanup => '确认清理'; + + @override + String get confirmCleanupMessage => '确定要删除日志文件吗?此操作不可撤销。'; + + @override + String get cleanupSuccess => '旧日志清理完成'; + + @override + String get cleanupFailed => '清理失败'; + + @override + String get syncServerStopped => '同步服务器已停止'; + + @override + String get scanQRToConnect => '其他设备扫描此二维码连接:'; + + @override + String get addressCopied => '地址已复制到剪贴板'; + + @override + String get otherDevicesCanScan => '其他设备可以扫描此二维码快速连接'; + + @override + String get startServer => '启动服务器'; + + @override + String get stopServer => '停止服务器'; + + @override + String get connectToOtherDevices => '连接到其他设备'; + + @override + String get scanQRCode => '扫描二维码连接'; + + @override + String get connectionHistory => '连接历史:'; + + @override + String get connect => '连接'; + + @override + String get manualInputAddress => '或手动输入服务器地址:'; + + @override + String get serverAddress => '服务器地址'; + + @override + String get syncFromServer => '从服务器同步'; + + @override + String get pushToServer => '推送到服务器'; + + @override + String get usageInstructions => '使用说明'; + + @override + String get desktopAsServer => '桌面端作为服务器:'; + + @override + String get desktopStep1 => '1. 点击\"启动服务器\"按钮'; + + @override + String get desktopStep2 => '2. 显示二维码给手机扫描'; + + @override + String get desktopStep3 => '3. 手机扫码后可进行数据同步'; + + @override + String get mobileConnect => '手机端连接:'; + + @override + String get mobileStep1 => '1. 点击\"扫描二维码连接\"'; + + @override + String get mobileStep2 => '2. 扫描桌面端显示的二维码'; + + @override + String get mobileStep3 => '3. 选择同步方向(上传/下载)'; + + @override + String get uploadDescription => '• 上传:将本设备数据推送到服务器'; + + @override + String get downloadDescription => '• 下载:从服务器获取数据到本设备'; + + @override + String get syncContent => '• 同步内容:聊天记录、设置、MCP配置'; + + @override + String get syncServerStarted => '同步服务器已启动'; + + @override + String get syncServerStartFailed => '启动服务器失败'; + + @override + String get syncServerStopFailed => '停止服务器失败'; + + @override + String get scanQRCodeTitle => '扫描二维码'; + + @override + String get flashOn => '开启闪光灯'; + + @override + String get flashOff => '关闭闪光灯'; + + @override + String get aimQRCode => '将二维码对准扫描框'; + + @override + String get scanSyncQRCode => '扫描桌面端显示的同步二维码'; + + @override + String get manualInputAddressButton => '手动输入地址'; + + @override + String get manualInputServerAddress => '手动输入服务器地址'; + + @override + String get enterValidServerAddress => '请输入有效的服务器地址'; + + @override + String scanSuccessConnectTo(Object deviceName) { + return '扫描成功,连接到: $deviceName'; + } + + @override + String get scanSuccessAddressFilled => '扫描成功,已填入服务器地址'; + + @override + String get scannerOpenFailed => '打开扫码器失败'; + + @override + String get pleaseInputServerAddress => '请先扫码或输入服务器地址'; + + @override + String get connectingToServer => '正在连接服务器...'; + + @override + String get downloadingData => '正在下载数据...'; + + @override + String get importingData => '正在导入数据...'; + + @override + String get reinitializingData => '正在重新初始化应用数据...'; + + @override + String get dataSyncSuccess => '数据同步成功'; + + @override + String get preparingData => '正在准备数据...'; + + @override + String get uploadingData => '正在上传数据...'; + + @override + String get dataPushSuccess => '数据推送成功'; + + @override + String get syncFailed => '同步失败'; + + @override + String get pushFailed => '推送失败'; + + @override + String get justNow => '刚刚'; + + @override + String minutesAgo(Object minutes) { + return '$minutes分钟前'; + } + + @override + String hoursAgo(Object hours) { + return '$hours小时前'; + } + + @override + String daysAgo(Object days) { + return '$days天前'; + } + + @override + String serverSelected(Object deviceName) { + return '已选择服务器: $deviceName'; + } + + @override + String get connectionRecordDeleted => '已删除连接记录'; + + @override + String viewAllConnections(Object count) { + return '查看全部 $count 个连接'; + } + + @override + String get clearAllHistory => '清空所有'; + + @override + String get clearAllConnectionHistory => '已清空所有连接历史'; + + @override + String get unknownDevice => '未知设备'; + + @override + String get unknownPlatform => '未知平台'; + + @override + String get inmemory => '内置'; + + @override + String get toggleSidebar => '切换侧边栏'; + + @override + String get deleteChat => '删除聊天'; + + @override + String get selectAll => '全选'; + + @override + String get newChat => '新聊天'; + + @override + String get send => '发送'; + + @override + String get more => '更多'; + + @override + String get noMoreData => '没有更多了'; +} diff --git a/lib/globals.dart b/lib/globals.dart new file mode 100644 index 0000000..a279a4f --- /dev/null +++ b/lib/globals.dart @@ -0,0 +1,4 @@ +import 'package:flutter/material.dart'; + +// 全局 navigator key,用于在非 Widget 上下文中获取 BuildContext +final GlobalKey navigatorKey = GlobalKey(); diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb new file mode 100644 index 0000000..5c2e434 --- /dev/null +++ b/lib/l10n/app_de.arb @@ -0,0 +1,279 @@ +{ + "@@locale": "de", + "settings": "Einstellungen", + "general": "Allgemein", + "providers": "Anbieter", + "mcpServer": "MCP Server", + "language": "Sprache", + "theme": "Design", + "dark": "Dunkel", + "light": "Hell", + "system": "System", + "languageSettings": "Spracheinstellungen", + "featureSettings": "Funktionseinstellungen", + "enableArtifacts": "Artifacts aktivieren", + "enableArtifactsDescription": "Artifacts des KI-Assistenten in der Unterhaltung aktivieren, verbraucht mehr Token", + "enableToolUsage": "Werkzeugnutzung aktivieren", + "enableToolUsageDescription": "Nutzung von Werkzeugen in der Unterhaltung aktivieren, verbraucht mehr Token", + "themeSettings": "Design-Einstellungen", + "lightTheme": "Helles Design", + "darkTheme": "Dunkles Design", + "followSystem": "System folgen", + "showAvatar": "Avatar anzeigen", + "showAssistantAvatar": "Assistenten-Avatar anzeigen", + "showAssistantAvatarDescription": "Avatar des KI-Assistenten in der Unterhaltung anzeigen", + "showUserAvatar": "Benutzer-Avatar anzeigen", + "showUserAvatarDescription": "Avatar des Benutzers in der Unterhaltung anzeigen", + "systemPrompt": "System-Prompt", + "systemPromptDescription": "Dies ist der System-Prompt für die Unterhaltung mit dem KI-Assistenten, wird verwendet um Verhalten und Stil des Assistenten festzulegen", + "llmKey": "LLM Schlüssel", + "toolKey": "Werkzeug-Schlüssel", + "saveSettings": "Einstellungen speichern", + "apiKey": "API Schlüssel", + "enterApiKey": "Geben Sie Ihren {provider} API Schlüssel ein", + "apiKeyValidation": "API Schlüssel muss mindestens 10 Zeichen haben", + "apiEndpoint": "API Endpunkt", + "enterApiEndpoint": "API Endpunkt URL eingeben", + "apiVersion": "API Version", + "enterApiVersion": "API Version eingeben", + "platformNotSupported": "Aktuelle Plattform unterstützt MCP Server nicht", + "mcpServerDesktopOnly": "MCP Server unterstützt nur Desktop-Plattformen (Windows, macOS, Linux)", + "searchServer": "Server suchen...", + "noServerConfigs": "Keine Server-Konfigurationen gefunden", + "addProvider": "Anbieter hinzufügen", + "refresh": "Aktualisieren", + "install": "Installieren", + "edit": "Bearbeiten", + "delete": "Löschen", + "command": "Befehl oder Server-URL", + "arguments": "Argumente", + "environmentVariables": "Umgebungsvariablen", + "serverName": "Servername", + "commandExample": "Zum Beispiel: npx, uvx, https://mcpserver.com", + "argumentsExample": "Argumente durch Leerzeichen trennen, Anführungszeichen für Argumente mit Leerzeichen verwenden, zum Beispiel: -y obsidian-mcp '/Users/username/Documents/Obsidian Vault'", + "envVarsFormat": "Eine pro Zeile, Format: SCHLÜSSEL=WERT", + "cancel": "Abbrechen", + "save": "Speichern", + "confirmDelete": "Löschen bestätigen", + "confirmDeleteServer": "Sind Sie sicher, dass Sie Server \"{name}\" löschen möchten?", + "error": "Fehler", + "commandNotExist": "Befehl \"{command}\" existiert nicht, bitte zuerst installieren\n\nAktueller PATH:\n{path}", + "all": "Alle", + "installed": "Installiert", + "modelSettings": "Modell-Einstellungen", + "temperature": "Temperatur: {value}", + "temperatureTooltip": "Sampling-Temperatur kontrolliert die Zufälligkeit der Ausgabe:\n• 0.0: Geeignet für Code-Generierung und Mathe-Probleme\n• 1.0: Geeignet für Datenextraktion und Analyse\n• 1.3: Geeignet für allgemeine Unterhaltung und Übersetzung\n• 1.5: Geeignet für kreatives Schreiben und Poesie", + "topP": "Top P: {value}", + "topPTooltip": "Top P (Nucleus-Sampling) ist eine Alternative zur Temperatur. Das Modell berücksichtigt nur Token, deren kumulative Wahrscheinlichkeit P überschreitet. Es wird empfohlen, nicht gleichzeitig Temperatur und top_p zu ändern.", + "maxTokens": "Max Token", + "maxTokensTooltip": "Maximale Anzahl zu generierender Token. Ein Token entspricht etwa 4 Zeichen. Längere Unterhaltungen benötigen mehr Token.", + "frequencyPenalty": "Häufigkeits-Bestrafung: {value}", + "frequencyPenaltyTooltip": "Häufigkeits-Bestrafungsparameter. Positive Werte bestrafen neue Token basierend auf ihrer vorhandenen Häufigkeit im Text, wodurch die Wahrscheinlichkeit des Modells verringert wird, denselben Inhalt wörtlich zu wiederholen.", + "presencePenalty": "Präsenz-Bestrafung: {value}", + "presencePenaltyTooltip": "Präsenz-Bestrafungsparameter. Positive Werte bestrafen neue Token basierend darauf, ob sie im Text erscheinen, wodurch die Wahrscheinlichkeit des Modells erhöht wird, über neue Themen zu sprechen.", + "enterMaxTokens": "Max Token eingeben", + "share": "Teilen", + "modelConfig": "Modell-Konfiguration", + "debug": "Debug", + "webSearchTest": "Web-Suche Test", + "today": "Heute", + "yesterday": "Gestern", + "last7Days": "Letzte 7 Tage", + "last30Days": "Letzte 30 Tage", + "earlier": "Früher", + "confirmDeleteSelected": "Sind Sie sicher, dass Sie die ausgewählten Unterhaltungen löschen möchten?", + "confirmThisChat": "Sind Sie sicher, dass Sie diese Unterhaltung löschen möchten?", + "ok": "OK", + "askMeAnything": "Fragen Sie mich alles...", + "uploadFiles": "Dateien hochladen", + "welcomeMessage": "Wie kann ich Ihnen heute helfen?", + "copy": "Kopieren", + "copied": "In Zwischenablage kopiert", + "retry": "Wiederholen", + "brokenImage": "Defektes Bild", + "toolCall": "{name} aufrufen", + "toolResult": "{name} Aufruf-Ergebnis", + "selectModel": "Modell auswählen", + "close": "Schließen", + "selectFromGallery": "Aus Galerie auswählen", + "selectFile": "Datei auswählen", + "uploadFile": "Datei hochladen", + "openBrowser": "Browser öffnen", + "codeCopiedToClipboard": "Code in Zwischenablage kopiert", + "thinking": "Denkt nach", + "thinkingEnd": "Denken beendet", + "tool": "Werkzeug", + "userCancelledToolCall": "Benutzer hat Werkzeug-Aufruf abgebrochen", + "code": "Code", + "preview": "Vorschau", + "loadContentFailed": "Laden des Inhalts fehlgeschlagen, bitte wiederholen", + "openingBrowser": "Browser wird geöffnet", + "functionCallAuth": "Werkzeug-Aufruf-Autorisierung", + "allowFunctionExecution": "Möchten Sie die Ausführung des folgenden Werkzeugs erlauben:", + "parameters": "Parameter: {params}", + "allow": "Erlauben", + "loadDiagramFailed": "Laden des Diagramms fehlgeschlagen, bitte wiederholen", + "copiedToClipboard": "In Zwischenablage kopiert", + "chinese": "Chinesisch", + "turkish": "Türkisch", + "functionRunning": "Werkzeug wird ausgeführt...", + "thinkingProcess": "Denkt nach", + "thinkingProcessWithDuration": "Denkt nach, Zeit verbraucht", + "thinkingEndWithDuration": "Denken beendet, Zeit verbraucht", + "thinkingEndComplete": "Denken beendet", + "seconds": "{seconds}s", + "fieldRequired": "Dieses Feld ist erforderlich", + "autoApprove": "Automatisch genehmigen", + "verify": "Schlüssel verifizieren", + "howToGet": "Wie man es bekommt", + "modelList": "Modell-Liste", + "enableModels": "Modelle aktivieren", + "disableAllModels": "Alle Modelle deaktivieren", + "saveSuccess": "Einstellungen erfolgreich gespeichert", + "genTitleModel": "Titel generieren", + "serverNameTooLong": "Servername darf nicht länger als 50 Zeichen sein", + "confirm": "Bestätigen", + "providerName": "Anbieter-Name", + "apiStyle": "API-Stil", + "enterProviderName": "Anbieter-Name eingeben", + "providerNameRequired": "Anbieter-Name ist erforderlich", + "addModel": "Modell hinzufügen", + "modelName": "Modell-Name", + "enterModelName": "Modell-Name eingeben", + "noApiConfigs": "Keine API-Konfigurationen verfügbar", + "add": "Hinzufügen", + "fetch": "Abrufen", + "on": "AN", + "off": "AUS", + "apiUrl": "API URL", + "selectApiStyle": "Bitte API-Stil auswählen", + "serverType": "Server-Typ", + "reset": "Zurücksetzen", + "start": "Starten", + "stop": "Stoppen", + "search": "Suchen", + "newVersionFound": "Neue Version {version} verfügbar", + "newVersionAvailable": "Neue Version verfügbar", + "updateNow": "Jetzt aktualisieren", + "updateLater": "Später aktualisieren", + "ignoreThisVersion": "Diese Version ignorieren", + "releaseNotes": "Versionshinweise:", + "openUrlFailed": "Öffnen der URL fehlgeschlagen", + "checkingForUpdates": "Suche nach Updates...", + "checkUpdate": "Update-Prüfung", + "appDescription": "ChatMCP ist ein plattformübergreifender KI-Client, der darauf abzielt, KI für mehr Menschen zugänglich zu machen.", + "visitWebsite": "Website", + "aboutApp": "Über die App", + "networkError": "Netzwerkfehler aufgetreten", + "noElementError": "Kein Element gefunden", + "permissionError": "Zugriff verweigert", + "unknownError": "Unbekannter Fehler aufgetreten", + "timeoutError": "Anfrage-Timeout", + "notFoundError": "Ressource nicht gefunden", + "invalidError": "Ungültige Anfrage", + "unauthorizedError": "Unbefugter Zugriff", + "minimize": "Minimieren", + "maximize": "Maximieren", + "conversationSettings": "Unterhaltungs-Einstellungen", + "maxMessages": "Max Nachrichten", + "maxMessagesDescription": "Maximale Anzahl von Nachrichten, die an LLM weitergegeben werden (1-1000)", + "maxLoops": "Max Schleifen", + "maxLoopsDescription": "Maximale Anzahl von Werkzeug-Aufruf-Schleifen, um Endlosschleifen zu verhindern (1-1000)", + "mcpServers": "MCP Server", + "getApiKey": "API Schlüssel erhalten", + "proxySettings": "Proxy-Einstellungen", + "enableProxy": "Proxy aktivieren", + "enableProxyDescription": "Wenn aktiviert, werden Netzwerkanfragen über den konfigurierten Proxy-Server geleitet", + "proxyType": "Proxy-Typ", + "proxyHost": "Proxy-Host", + "proxyPort": "Proxy-Port", + "proxyUsername": "Benutzername", + "proxyPassword": "Passwort", + "enterProxyHost": "Proxy-Server-Adresse eingeben", + "enterProxyPort": "Proxy-Port eingeben", + "enterProxyUsername": "Benutzername eingeben (optional)", + "enterProxyPassword": "Passwort eingeben (optional)", + "proxyHostRequired": "Proxy-Host ist erforderlich", + "proxyPortInvalid": "Proxy-Port muss zwischen 1-65535 liegen", + "saved": "Gespeichert", + "dataSync": "Daten-Synchronisation", + "syncServerRunning": "Sync-Server läuft", + "maintenance": "Wartung", + "cleanupLogs": "Alte Logs aufräumen", + "cleanupLogsDescription": "Log-Dateien aufräumen", + "confirmCleanup": "Aufräumen bestätigen", + "confirmCleanupMessage": "Sind Sie sicher, dass Sie Log-Dateien löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.", + "cleanupSuccess": "Aufräumen alter Logs abgeschlossen", + "cleanupFailed": "Aufräumen fehlgeschlagen", + "syncServerStopped": "Sync-Server gestoppt", + "scanQRToConnect": "Andere Geräte scannen diesen QR-Code zum Verbinden:", + "addressCopied": "Adresse in Zwischenablage kopiert", + "otherDevicesCanScan": "Andere Geräte können diesen QR-Code scannen, um sich schnell zu verbinden", + "startServer": "Server starten", + "stopServer": "Server stoppen", + "connectToOtherDevices": "Mit anderen Geräten verbinden", + "scanQRCode": "QR-Code scannen zum Verbinden", + "connectionHistory": "Verbindungs-Verlauf:", + "connect": "Verbinden", + "manualInputAddress": "Oder Server-Adresse manuell eingeben:", + "serverAddress": "Server-Adresse", + "syncFromServer": "Vom Server synchronisieren", + "pushToServer": "Zum Server übertragen", + "usageInstructions": "Nutzungsanweisungen", + "desktopAsServer": "Desktop als Server:", + "desktopStep1": "1. \"Server starten\" Button klicken", + "desktopStep2": "2. QR-Code für Mobile zum Scannen anzeigen", + "desktopStep3": "3. Mobile kann nach dem Scannen Daten synchronisieren", + "mobileConnect": "Mobile-Verbindung:", + "mobileStep1": "1. \"QR-Code scannen zum Verbinden\" klicken", + "mobileStep2": "2. QR-Code auf Desktop scannen", + "mobileStep3": "3. Sync-Richtung wählen (upload/download)", + "uploadDescription": "• Upload: Lokale Gerätedaten zum Server übertragen", + "downloadDescription": "• Download: Daten vom Server auf lokales Gerät holen", + "syncContent": "• Sync-Inhalt: Chat-Verlauf, Einstellungen, MCP-Konfigurationen", + "syncServerStarted": "Sync-Server gestartet", + "syncServerStartFailed": "Server-Start fehlgeschlagen", + "syncServerStopped": "Sync-Server gestoppt", + "syncServerStopFailed": "Server-Stopp fehlgeschlagen", + "scanQRCodeTitle": "QR-Code scannen", + "flashOn": "Blitz an", + "flashOff": "Blitz aus", + "aimQRCode": "QR-Code auf den Scan-Rahmen richten", + "scanSyncQRCode": "Sync QR-Code auf Desktop scannen", + "manualInputAddressButton": "Adresse manuell eingeben", + "manualInputServerAddress": "Server-Adresse manuell eingeben", + "enterValidServerAddress": "Bitte gültige Server-Adresse eingeben", + "scanSuccessConnectTo": "Scan erfolgreich, verbunden mit: {deviceName}", + "scanSuccessAddressFilled": "Scan erfolgreich, Server-Adresse ausgefüllt", + "scannerOpenFailed": "Scanner-Öffnung fehlgeschlagen", + "pleaseInputServerAddress": "Bitte zuerst QR-Code scannen oder Server-Adresse eingeben", + "connectingToServer": "Verbindung zum Server...", + "downloadingData": "Daten werden heruntergeladen...", + "importingData": "Daten werden importiert...", + "reinitializingData": "App-Daten werden neu initialisiert...", + "dataSyncSuccess": "Daten-Synchronisation erfolgreich", + "preparingData": "Daten werden vorbereitet...", + "uploadingData": "Daten werden hochgeladen...", + "dataPushSuccess": "Daten-Übertragung erfolgreich", + "syncFailed": "Synchronisation fehlgeschlagen", + "pushFailed": "Übertragung fehlgeschlagen", + "justNow": "Gerade eben", + "minutesAgo": "vor {minutes} Minuten", + "hoursAgo": "vor {hours} Stunden", + "daysAgo": "vor {days} Tagen", + "serverSelected": "Server ausgewählt: {deviceName}", + "connectionRecordDeleted": "Verbindungseintrag gelöscht", + "viewAllConnections": "Alle {count} Verbindungen anzeigen", + "clearAllHistory": "Alles löschen", + "clearAllConnectionHistory": "Gesamter Verbindungs-Verlauf gelöscht", + "unknownDevice": "Unbekanntes Gerät", + "unknownPlatform": "Unbekannte Plattform", + "inmemory": "Im Speicher", + "toggleSidebar": "Seitenleiste umschalten", + "deleteChat": "Chat löschen", + "selectAll": "Alle auswählen", + "newChat": "Neuer Chat", + "send": "Senden", + "more": "Mehr", + "noMoreData": "Keine weiteren Daten" +} \ No newline at end of file diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb new file mode 100644 index 0000000..7daa542 --- /dev/null +++ b/lib/l10n/app_en.arb @@ -0,0 +1,281 @@ +{ + "@@locale": "en", + "settings": "Settings", + "general": "General", + "providers": "Providers", + "mcpServer": "MCP Server", + "language": "Language", + "theme": "Theme", + "dark": "Dark", + "light": "Light", + "system": "System", + "languageSettings": "Language Settings", + "featureSettings": "Feature Settings", + "enableArtifacts": "Enable Artifacts", + "enableArtifactsDescription": "Enable the artifacts of the AI assistant in the conversation, will use more tokens", + "enableToolUsage": "Enable Tool Usage", + "enableToolUsageDescription": "Enable the usage of tools in the conversation, will use more tokens", + "themeSettings": "Theme Settings", + "lightTheme": "Light Theme", + "darkTheme": "Dark Theme", + "followSystem": "Follow System", + "showAvatar": "Show Avatar", + "showAssistantAvatar": "Show Assistant Avatar", + "showAssistantAvatarDescription": "Show the avatar of the AI assistant in the conversation", + "showUserAvatar": "Show User Avatar", + "showUserAvatarDescription": "Show the avatar of the user in the conversation", + "systemPrompt": "System Prompt", + "systemPromptDescription": "This is the system prompt for the conversation with the AI assistant, used to set the behavior and style of the assistant", + "llmKey": "LLM Key", + "toolKey": "Tool Key", + "saveSettings": "Save Settings", + "apiKey": "API Key", + "enterApiKey": "Enter your {provider} API Key", + "apiKeyValidation": "API Key must be at least 10 characters", + "apiEndpoint": "API Endpoint", + "enterApiEndpoint": "Enter API endpoint URL", + "apiVersion": "API Version", + "enterApiVersion": "Enter API Version", + "platformNotSupported": "Current platform does not support MCP Server", + "mcpServerDesktopOnly": "MCP Server only supports desktop platforms (Windows, macOS, Linux)", + "searchServer": "Search server...", + "noServerConfigs": "No server configurations found", + "addProvider": "Add Provider", + "refresh": "Refresh", + "install": "Install", + "edit": "Edit", + "delete": "Delete", + "command": "Command Or Sever Url", + "arguments": "Arguments", + "environmentVariables": "Environment Variables", + "serverName": "Server Name", + "commandExample": "For example: npx, uvx, https://mcpserver.com", + "argumentsExample": "Separate arguments with spaces, use quotes for arguments with spaces, for example: -y obsidian-mcp '/Users/username/Documents/Obsidian Vault'", + "envVarsFormat": "One per line, format: KEY=VALUE", + "cancel": "Cancel", + "save": "Save", + "confirmDelete": "Confirm Delete", + "confirmDeleteServer": "Are you sure you want to delete server \"{name}\" ?", + "error": "Error", + "commandNotExist": "Command \"{command}\" does not exist, please install it first\n\nCurrent PATH:\n{path}", + "all": "All", + "installed": "Installed", + "modelSettings": "Model Settings", + "temperature": "Temperature: {value}", + "temperatureTooltip": "Sampling temperature controls the randomness of output:\n• 0.0: Suitable for code generation and math problems\n• 1.0: Suitable for data extraction and analysis\n• 1.3: Suitable for general conversation and translation\n• 1.5: Suitable for creative writing and poetry", + "topP": "Top P: {value}", + "topPTooltip": "Top P (nucleus sampling) is an alternative to temperature. The model only considers tokens whose cumulative probability exceeds P. It is recommended not to modify both temperature and top_p at the same time.", + "maxTokens": "Max Tokens", + "maxTokensTooltip": "Maximum number of tokens to generate. One token is approximately equal to 4 characters. Longer conversations require more tokens.", + "frequencyPenalty": "Frequency Penalty: {value}", + "frequencyPenaltyTooltip": "Frequency penalty parameter. Positive values penalize new tokens based on their existing frequency in the text, decreasing the model's likelihood of repeating the same content verbatim.", + "presencePenalty": "Presence Penalty: {value}", + "presencePenaltyTooltip": "Presence penalty parameter. Positive values penalize new tokens based on whether they appear in the text, increasing the model's likelihood of talking about new topics.", + "enterMaxTokens": "Enter max tokens", + "share": "Share", + "modelConfig": "Model Config", + "debug": "Debug", + "webSearchTest": "Web Search Test", + "today": "Today", + "yesterday": "Yesterday", + "last7Days": "Last 7 Days", + "last30Days": "Last 30 Days", + "earlier": "Earlier", + "confirmDeleteSelected": "Are you sure you want to delete the selected conversations?", + "confirmThisChat": "Are you sure you want to delete the this conversations", + "ok": "OK", + "askMeAnything": "Ask me anything...", + "uploadFiles": "Upload Files", + "welcomeMessage": "How can I help you today?", + "copy": "Copy", + "copied": "Copied to clipboard", + "retry": "Retry", + "brokenImage": "Broken Image", + "toolCall": "call {name}", + "toolResult": "call {name} result", + "selectModel": "Select Model", + "close": "Close", + "selectFromGallery": "Select from Gallery", + "selectFile": "Select File", + "uploadFile": "Upload File", + "openBrowser": "Open Browser", + "codeCopiedToClipboard": "Code copied to clipboard", + "thinking": "Thinking", + "thinkingEnd": "Thinking End", + "tool": "Tool", + "userCancelledToolCall": "User cancelled tool call", + "code": "Code", + "preview": "Preview", + "loadContentFailed": "Failed to load content, please retry", + "openingBrowser": "Opening browser", + "functionCallAuth": "Tool Call Authorization", + "allowFunctionExecution": "Do you want to allow the following tool to execute:", + "parameters": "Parameters: {params}", + "allow": "Allow", + "loadDiagramFailed": "Failed to load diagram, please retry", + "copiedToClipboard": "Copied to clipboard", + "chinese": "Chinese", + "turkish": "Turkish", + "functionRunning": "Running Tool...", + "userCancelledToolCall": "Tool execution failed", + "thinkingProcess": "Thinking", + "thinkingProcessWithDuration": "Thinking, time used", + "thinkingEndWithDuration": "Thinking finished, time used", + "thinkingEndComplete": "Thinking finished", + "seconds": "{seconds}s", + "fieldRequired": "This field is required", + "autoApprove": "Auto Approve", + "verify": "Verify Key", + "howToGet": "How to get", + "modelList": "Model List", + "enableModels": "Enable Models", + "disableAllModels": "Disable All Models", + "saveSuccess": "Settings saved successfully", + "genTitleModel": "Gen Title", + "serverNameTooLong": "Server name cannot exceed 50 characters", + "confirm": "Confirm", + "providerName": "Provider Name", + "apiStyle": "API Style", + "enterProviderName": "Enter provider name", + "providerNameRequired": "Provider name is required", + "addModel": "Add Model", + "modelName": "Model Name", + "enterModelName": "Enter model name", + "noApiConfigs": "No API configurations available", + "add": "Add", + "fetch": "Fetch", + "on": "ON", + "off": "OFF", + "apiUrl": "API URL", + "selectApiStyle": "Please select API style", + "serverType": "Server Type", + "reset": "Reset", + "start": "Start", + "stop": "stop", + "search": "Search", + "newVersionFound": "New version {version} available", + "newVersionAvailable": "New version available", + "updateNow": "Update Now", + "updateLater": "Update Later", + "ignoreThisVersion": "Ignore This Version", + "releaseNotes": "Release Notes:", + "openUrlFailed": "Failed to open URL", + "checkingForUpdates": "Checking for updates...", + "checkUpdate": "Update Check", + "appDescription": "ChatMCP is a cross-platform AI client, dedicated to making AI accessible to more people.", + "visitWebsite": "website", + "aboutApp": "About", + "networkError": "Network error occurred", + "noElementError": "No element found", + "permissionError": "Permission denied", + "unknownError": "Unknown error occurred", + "timeoutError": "Request timed out", + "notFoundError": "Resource not found", + "invalidError": "Invalid request", + "unauthorizedError": "Unauthorized access", + "minimize": "Minimize", + "maximize": "Maximize", + "conversationSettings": "Conversation Settings", + "maxMessages": "Max Messages", + "maxMessagesDescription": "Limit the maximum number of messages passed to LLM (1-1000)", + "maxLoops": "Max Loops", + "maxLoopsDescription": "Limit the maximum number of tool call loops to prevent infinite loops (1-1000)", + "mcpServers": "MCP Servers", + "getApiKey": "Get API Key", + "proxySettings": "Proxy Settings", + "enableProxy": "Enable Proxy", + "enableProxyDescription": "When enabled, network requests will go through the configured proxy server", + "proxyType": "Proxy Type", + "proxyHost": "Proxy Host", + "proxyPort": "Proxy Port", + "proxyUsername": "Username", + "proxyPassword": "Password", + "enterProxyHost": "Enter proxy server address", + "enterProxyPort": "Enter proxy port", + "enterProxyUsername": "Enter username (optional)", + "enterProxyPassword": "Enter password (optional)", + "proxyHostRequired": "Proxy host is required", + "proxyPortInvalid": "Proxy port must be between 1-65535", + "saved": "Saved", + "dataSync": "Data Sync", + "syncServerRunning": "Sync server is running", + "maintenance": "Maintenance", + "cleanupLogs": "Cleanup Old Logs", + "cleanupLogsDescription": "Cleanup log files", + "confirmCleanup": "Confirm Cleanup", + "confirmCleanupMessage": "Are you sure you want to delete log files? This action cannot be undone.", + "cleanupSuccess": "Old logs cleanup completed", + "cleanupFailed": "Cleanup failed", + "syncServerStopped": "Sync server is stopped", + "scanQRToConnect": "Other devices scan this QR code to connect:", + "addressCopied": "Address copied to clipboard", + "otherDevicesCanScan": "Other devices can scan this QR code to connect quickly", + "startServer": "Start Server", + "stopServer": "Stop Server", + "connectToOtherDevices": "Connect to Other Devices", + "scanQRCode": "Scan QR Code to Connect", + "connectionHistory": "Connection History:", + "connect": "Connect", + "manualInputAddress": "Or manually enter server address:", + "serverAddress": "Server Address", + "syncFromServer": "Sync from Server", + "pushToServer": "Push to Server", + "usageInstructions": "Usage Instructions", + "desktopAsServer": "Desktop as Server:", + "desktopStep1": "1. Click \"Start Server\" button", + "desktopStep2": "2. Show QR code for mobile to scan", + "desktopStep3": "3. Mobile can sync data after scanning", + "mobileConnect": "Mobile Connection:", + "mobileStep1": "1. Click \"Scan QR Code to Connect\"", + "mobileStep2": "2. Scan the QR code displayed on desktop", + "mobileStep3": "3. Choose sync direction (upload/download)", + "dataSync": "Data Sync", + "uploadDescription": "• Upload: Push local device data to server", + "downloadDescription": "• Download: Get data from server to local device", + "syncContent": "• Sync Content: Chat history, settings, MCP configs", + "syncServerStarted": "Sync server started", + "syncServerStartFailed": "Failed to start server", + "syncServerStopped": "Sync server stopped", + "syncServerStopFailed": "Failed to stop server", + "scanQRCodeTitle": "Scan QR Code", + "flashOn": "Flash On", + "flashOff": "Flash Off", + "aimQRCode": "Aim the QR code at the scanning frame", + "scanSyncQRCode": "Scan the sync QR code displayed on desktop", + "manualInputAddressButton": "Manual Input Address", + "manualInputServerAddress": "Manually Input Server Address", + "enterValidServerAddress": "Please enter a valid server address", + "scanSuccessConnectTo": "Scan successful, connected to: {deviceName}", + "scanSuccessAddressFilled": "Scan successful, server address filled", + "scannerOpenFailed": "Failed to open scanner", + "pleaseInputServerAddress": "Please scan QR code or input server address first", + "connectingToServer": "Connecting to server...", + "downloadingData": "Downloading data...", + "importingData": "Importing data...", + "reinitializingData": "Reinitializing app data...", + "dataSyncSuccess": "Data sync successful", + "preparingData": "Preparing data...", + "uploadingData": "Uploading data...", + "dataPushSuccess": "Data push successful", + "syncFailed": "Sync failed", + "pushFailed": "Push failed", + "justNow": "Just now", + "minutesAgo": "{minutes} minutes ago", + "hoursAgo": "{hours} hours ago", + "daysAgo": "{days} days ago", + "serverSelected": "Server selected: {deviceName}", + "connectionRecordDeleted": "Connection record deleted", + "viewAllConnections": "View all {count} connections", + "clearAllHistory": "Clear All", + "clearAllConnectionHistory": "All connection history cleared", + "unknownDevice": "Unknown Device", + "unknownPlatform": "Unknown Platform", + "inmemory": "In Memory", + "toggleSidebar": "Toggle Sidebar", + "deleteChat": "Delete Chat", + "selectAll": "Select All", + "newChat": "New Chat", + "send": "Send", + "more": "More", + "noMoreData": "No more data" +} diff --git a/lib/l10n/app_tr.arb b/lib/l10n/app_tr.arb new file mode 100644 index 0000000..8b23797 --- /dev/null +++ b/lib/l10n/app_tr.arb @@ -0,0 +1,281 @@ +{ + "@@locale": "tr", + "settings": "Ayarlar", + "general": "Genel", + "providers": "Sağlayıcılar", + "mcpServer": "MCP Sunucusu", + "language": "Dil", + "theme": "Tema", + "dark": "Koyu", + "light": "Açık", + "system": "Sistem", + "languageSettings": "Dil Ayarları", + "featureSettings": "Özellik Ayarları", + "enableArtifacts": "Artifact'leri Etkinleştir", + "enableArtifactsDescription": "Sohbette yapay zeka asistanının Artifact'lerini etkinleştirir, bu özellik daha fazla token kullanır.", + "enableToolUsage": "Araç Kullanımını Etkinleştir", + "enableToolUsageDescription": "Sohbette araçların kullanımını etkinleştirir, bu özellik daha fazla token kullanır.", + "themeSettings": "Tema Ayarları", + "lightTheme": "Açık Tema", + "darkTheme": "Koyu Tema", + "followSystem": "Sistem Ayarlarına Uygula", + "showAvatar": "Avatar Gösterimi", + "showAssistantAvatar": "Asistan Avatarını Göster", + "showAssistantAvatarDescription": "Sohbette yapay zeka asistanının avatarını gösterir.", + "showUserAvatar": "Kullanıcı Avatarını Göster", + "showUserAvatarDescription": "Sohbette kullanıcının avatarını gösterir.", + "systemPrompt": "Sistem Prompt", + "systemPromptDescription": "Bu, yapay zeka asistanının davranışını ve tarzını belirlemek için kullanılan sistem yönergesidir.", + "llmKey": "LLM Anahtarı", + "toolKey": "Araç Anahtarı", + "saveSettings": "Ayarları Kaydet", + "apiKey": "API Anahtarı", + "enterApiKey": "{provider} API Anahtarınızı Girin", + "apiKeyValidation": "API Anahtarı en az 10 karakter olmalıdır.", + "apiEndpoint": "API Uç Noktası", + "enterApiEndpoint": "API uç noktası URL'sini girin", + "apiVersion": "API Versiyonu", + "enterApiVersion": "API versiyonunu girin", + "platformNotSupported": "Mevcut platform MCP Sunucusunu desteklemiyor.", + "mcpServerDesktopOnly": "MCP Sunucusu yalnızca masaüstü platformlarını (Windows, macOS, Linux) destekler.", + "searchServer": "Sunucu ara...", + "noServerConfigs": "Sunucu yapılandırması bulunamadı.", + "addProvider": "Sağlayıcı Ekle", + "refresh": "Yenile", + "install": "Yükle", + "edit": "Düzenle", + "delete": "Sil", + "command": "Komut veya Sunucu Adresi", + "arguments": "Argümanlar", + "environmentVariables": "Ortam Değişkenleri", + "serverName": "Sunucu Adı", + "commandExample": "Örneğin: npx, uvx, https://mcpserver.com", + "argumentsExample": "Argümanları boşlukla ayırın. Boşluk içerenler için tırnak işareti kullanın, örn: -y obsidian-mcp '/Kullanıcılar/kullaniciadi/Belgeler/Obsidian Kasası'", + "envVarsFormat": "Her satıra bir tane, ANAHTAR=DEĞER formatında", + "cancel": "İptal", + "save": "Kaydet", + "confirmDelete": "Silmeyi Onayla", + "confirmDeleteServer": "\"{name}\" adlı sunucuyu silmek istediğinize emin misiniz?", + "error": "Hata", + "commandNotExist": "\"{command}\" komutu bulunamadı. Lütfen önce bu komutu yükleyin.\n\nMevcut PATH:\n{path}", + "all": "Tümü", + "installed": "Yüklü", + "modelSettings": "Model Ayarları", + "temperature": "Temperature: {value}", + "temperatureTooltip": "Temperature , çıktının rastgeleliğini kontrol eder:\n• 0.0: Kod üretimi ve matematiksel problemler için idealdir.\n• 1.0: Veri çıkarma ve analiz için uygundur.\n• 1.3: Genel sohbet ve çeviri için uygundur.\n• 1.5: Yaratıcı yazarlık ve şiir için harikadır.", + "topP": "Çekirdek Örnekleme (Top P): {value}", + "topPTooltip": "Top P (Çekirdek Örnekleme), sıcaklık parametresine bir alternatiftir. Model, yalnızca kümülatif olasılığı P'yi aşan token'ları dikkate alır. Sıcaklık ve top_p değerlerini aynı anda değiştirmeniz önerilmez.", + "maxTokens": "Maksimum Token", + "maxTokensTooltip": "Üretilecek maksimum token sayısı. Bir token yaklaşık 4 karaktere eşittir. Daha uzun sohbetler daha fazla token gerektirir.", + "frequencyPenalty": "Frequency Cezası: {value}", + "frequencyPenaltyTooltip": "Frequency cezası parametresi. Pozitif değerler, metindeki mevcut frekanslarına göre yeni token'ları cezalandırarak modelin aynı içeriği kelimesi kelimesine tekrarlama olasılığını azaltır.", + "presencePenalty": "Presence Cezası: {value}", + "presencePenaltyTooltip": "Presence cezası parametresi. Pozitif değerler, metinde daha önce geçip geçmediklerine göre yeni token'ları cezalandırarak modelin yeni konular hakkında konuşma olasılığını artırır.", + "enterMaxTokens": "Maksimum token sayısını girin", + "share": "Paylaş", + "modelConfig": "Model Ayarları", + "debug": "Debug Modu", + "webSearchTest": "Web Araması Testi", + "today": "Bugün", + "yesterday": "Dün", + "last7Days": "Son 7 Gün", + "last30Days": "Son 30 Gün", + "earlier": "Daha Eski", + "confirmDeleteSelected": "Seçili sohbetleri silmek istediğinize emin misiniz?", + "confirmThisChat": "Bu sohbetleri silmek istediğinize emin misiniz?", + "ok": "Tamam", + "askMeAnything": "Aklındakini sor...", + "uploadFiles": "Dosya Yükle", + "welcomeMessage": "Bugün sana nasıl yardımcı olabilirim?", + "copy": "Kopyala", + "copied": "Panoya kopyalandı!", + "retry": "Yeniden Dene", + "brokenImage": "Bozuk Resim", + "toolCall": "{name} çağrılıyor", + "toolResult": "{name} çağrısının sonucu", + "selectModel": "Model Seç", + "close": "Kapat", + "selectFromGallery": "Galeriden Seç", + "selectFile": "Dosya Seç", + "uploadFile": "Dosya Yükle", + "openBrowser": "Tarayıcıda Aç", + "codeCopiedToClipboard": "Kod panoya kopyalandı.", + "thinking": "Düşünüyor...", + "thinkingEnd": "Düşünme tamamlandı.", + "tool": "Araç", + "userCancelledToolCall": "Kullanıcı araç çağrısını iptal etti.", + "code": "Kod", + "preview": "Önizleme", + "functionCallAuth": "Araç Kullanım İzni", + "allowFunctionExecution": "Aşağıdaki aracın çalışmasına izin veriyor musunuz?", + "parameters": "Parametreler: {params}", + "allow": "İzin Ver", + "loadContentFailed": "İçerik yüklenemedi, lütfen tekrar deneyin.", + "loadDiagramFailed": "Diyagram yüklenemedi, lütfen tekrar deneyin.", + "copiedToClipboard": "Panoya kopyalandı.", + "chinese": "Çince", + "turkish": "Türkçe", + "functionRunning": "Araç çalıştırılıyor...", + "userCancelledToolCall": "Araç çalıştırılamadı.", + "thinkingProcess": "Düşünme Süreci ...", + "thinkingProcessWithDuration": "Düşünme, geçen süre", + "thinkingEndWithDuration": "Düşünme tamamlandı, geçen süre", + "thinkingEndComplete": "Düşünme tamamlandı", + "seconds": "{seconds}sn", + "fieldRequired": "Bu alan zorunludur.", + "autoApprove": "Otomatik Onayla", + "verify": "Anahtarı Doğrula", + "howToGet": "Nasıl alınır?", + "modelList": "Model Listesi", + "enableModels": "Modelleri Etkinleştir", + "disableAllModels": "Tüm Modelleri Devre Dışı Bırak", + "saveSuccess": "Ayarlar başarıyla kaydedildi!", + "genTitleModel": "Başlık Oluşturma Modeli", + "serverNameTooLong": "Sunucu adı 50 karakterden uzun olamaz.", + "serverType": "Sunucu Türü", + "reset": "Sıfırla", + "start": "Başlat", + "stop": "Durdur", + "search": "Ara", + "newVersionFound": "Yeni bir {version} sürümü mevcut!", + "newVersionAvailable": "Yeni Sürüm Mevcut", + "updateNow": "Şimdi Güncelle", + "updateLater": "Daha Sonra", + "ignoreThisVersion": "Bu Sürümü Atla", + "releaseNotes": "Sürüm Notları:", + "openUrlFailed": "Bağlantı açılamadı.", + "checkingForUpdates": "Güncellemeler kontrol ediliyor...", + "checkUpdate": "Güncellemeleri Kontrol Et", + "appDescription": "ChatMCP, yapay zekayı daha fazla insana ulaştırmayı hedefleyen, platformlar arası bir yapay zeka istemcisidir.", + "visitWebsite": "Web Sitesi", + "aboutApp": "Hakkında", + "networkError": "Ağ bağlantı hatası. Lütfen internetinizi kontrol edip tekrar deneyin.", + "noElementError": "Eşleşen içerik bulunamadı, lütfen tekrar deneyin.", + "permissionError": "Yetersiz izin. Lütfen ayarlarınızı kontrol edin.", + "unknownError": "Bilinmeyen bir hata oluştu.", + "timeoutError": "İstek zaman aşımına uğradı. Lütfen bir süre sonra tekrar deneyin.", + "notFoundError": "İstenen kaynak bulunamadı.", + "invalidError": "Geçersiz istek veya parametre.", + "unauthorizedError": "Yetkisiz erişim. Lütfen izinlerinizi kontrol edin.", + "minimize": "Küçült", + "maximize": "Büyüt", + "conversationSettings": "Sohbet Ayarları", + "maxMessages": "Maksimum Mesaj Sayısı", + "maxMessagesDescription": "LLM'e gönderilecek maksimum mesaj sayısını sınırlar (1-1000).", + "maxLoops": "Maksimum Döngü Sayısı", + "maxLoopsDescription": "Sonsuz döngüleri önlemek için araç çağırma döngü sayısını sınırlar (1-1000).", + "mcpServers": "MCP Sunucuları", + "getApiKey": "API Anahtarı Al", + "openingBrowser": "Tarayıcı açılıyor...", + "confirm": "Onayla", + "providerName": "Sağlayıcı Adı", + "apiStyle": "API Tarzı", + "enterProviderName": "Sağlayıcı adını girin", + "providerNameRequired": "Sağlayıcı adı zorunludur.", + "addModel": "Model Ekle", + "modelName": "Model Adı", + "enterModelName": "Model adını girin", + "noApiConfigs": "Kullanılabilir API yapılandırması yok.", + "add": "Ekle", + "fetch": "Getir", + "on": "AÇIK", + "off": "KAPALI", + "apiUrl": "API Adresi", + "selectApiStyle": "Lütfen bir API tarzı seçin", + "proxySettings": "Proxy Ayarları", + "enableProxy": "Proxy'yi Etkinleştir", + "enableProxyDescription": "Etkinleştirildiğinde, ağ istekleri yapılandırılan proxy sunucu üzerinden gidecektir", + "proxyType": "Proxy Türü", + "proxyHost": "Proxy Adresi", + "proxyPort": "Proxy Portu", + "proxyUsername": "Kullanıcı Adı", + "proxyPassword": "Şifre", + "enterProxyHost": "Proxy sunucu adresini girin", + "enterProxyPort": "Proxy portunu girin", + "enterProxyUsername": "Kullanıcı adını girin (isteğe bağlı)", + "enterProxyPassword": "Şifreyi girin (isteğe bağlı)", + "proxyHostRequired": "Proxy adresi zorunludur", + "proxyPortInvalid": "Proxy portu 1-65535 arasında olmalıdır", + "saved": "Kaydedildi", + "dataSync": "Veri Senkronizasyonu", + "syncServerRunning": "Senkronizasyon sunucusu çalışıyor", + "maintenance": "Bakım", + "cleanupLogs": "Eski Günlükleri Temizle", + "cleanupLogsDescription": "Günlük dosyalarını temizle", + "confirmCleanup": "Temizlemeyi Onayla", + "confirmCleanupMessage": "Günlük dosyalarını silmek istediğinize emin misiniz? Bu işlem geri alınamaz.", + "cleanupSuccess": "Eski günlükler temizlendi", + "cleanupFailed": "Temizleme başarısız", + "syncServerStopped": "Senkronizasyon sunucusu durduruldu", + "scanQRToConnect": "Diğer cihazlar bağlanmak için bu QR kodu tarayabilir:", + "addressCopied": "Adres panoya kopyalandı", + "otherDevicesCanScan": "Diğer cihazlar hızlı bağlantı için bu QR kodu tarayabilir", + "startServer": "Sunucuyu Başlat", + "stopServer": "Sunucuyu Durdur", + "connectToOtherDevices": "Diğer Cihazlara Bağlan", + "scanQRCode": "QR Kod Tarayarak Bağlan", + "connectionHistory": "Bağlantı Geçmişi:", + "connect": "Bağlan", + "manualInputAddress": "Veya sunucu adresini manuel olarak girin:", + "serverAddress": "Sunucu Adresi", + "syncFromServer": "Sunucudan Senkronize Et", + "pushToServer": "Sunucuya Gönder", + "usageInstructions": "Kullanım Talimatları", + "desktopAsServer": "Masaüstü Sunucu Olarak:", + "desktopStep1": "1. \"Sunucuyu Başlat\" düğmesine tıklayın", + "desktopStep2": "2. Mobil cihazın taraması için QR kodu gösterin", + "desktopStep3": "3. Mobil cihaz tarama sonrası veri senkronizasyonu yapabilir", + "mobileConnect": "Mobil Bağlantı:", + "mobileStep1": "1. \"QR Kod Tarayarak Bağlan\" düğmesine tıklayın", + "mobileStep2": "2. Masaüstünde gösterilen QR kodu tarayın", + "mobileStep3": "3. Senkronizasyon yönünü seçin (yükleme/indirme)", + "dataSync": "Veri Senkronizasyonu", + "uploadDescription": "• Yükleme: Yerel cihaz verilerini sunucuya gönder", + "downloadDescription": "• İndirme: Sunucudan yerel cihaza veri al", + "syncContent": "• Senkronizasyon İçeriği: Sohbet geçmişi, ayarlar, MCP yapılandırmaları", + "syncServerStarted": "Senkronizasyon sunucusu başlatıldı", + "syncServerStartFailed": "Sunucu başlatılamadı", + "syncServerStopped": "Senkronizasyon sunucusu durduruldu", + "syncServerStopFailed": "Sunucu durdurulamadı", + "scanQRCodeTitle": "QR Kod Tarama", + "flashOn": "Flaş Açık", + "flashOff": "Flaş Kapalı", + "aimQRCode": "QR kodu tarama çerçevesine hizalayın", + "scanSyncQRCode": "Masaüstünde gösterilen senkronizasyon QR kodunu tarayın", + "manualInputAddressButton": "Manuel Adres Girişi", + "manualInputServerAddress": "Sunucu Adresini Manuel Olarak Girin", + "enterValidServerAddress": "Lütfen geçerli bir sunucu adresi girin", + "scanSuccessConnectTo": "Tarama başarılı, bağlanıldı: {deviceName}", + "scanSuccessAddressFilled": "Tarama başarılı, sunucu adresi dolduruldu", + "scannerOpenFailed": "Tarayıcı açılamadı", + "pleaseInputServerAddress": "Lütfen önce QR kodu tarayın veya sunucu adresi girin", + "connectingToServer": "Sunucuya bağlanıyor...", + "downloadingData": "Veri indiriliyor...", + "importingData": "Veri içe aktarılıyor...", + "reinitializingData": "Uygulama verileri yeniden başlatılıyor...", + "dataSyncSuccess": "Veri senkronizasyonu başarılı", + "preparingData": "Veri hazırlanıyor...", + "uploadingData": "Veri yükleniyor...", + "dataPushSuccess": "Veri gönderimi başarılı", + "syncFailed": "Senkronizasyon başarısız", + "pushFailed": "Gönderim başarısız", + "justNow": "Az önce", + "minutesAgo": "{minutes} dakika önce", + "hoursAgo": "{hours} saat önce", + "daysAgo": "{days} gün önce", + "serverSelected": "Sunucu seçildi: {deviceName}", + "connectionRecordDeleted": "Bağlantı kaydı silindi", + "viewAllConnections": "Tüm {count} bağlantıyı görüntüle", + "clearAllHistory": "Tümünü Temizle", + "clearAllConnectionHistory": "Tüm bağlantı geçmişi temizlendi", + "unknownDevice": "Bilinmeyen Cihaz", + "unknownPlatform": "Bilinmeyen Platform", + "inmemory": "En Memoria", + "toggleSidebar": "Kenar Çubuğunu Değiştir", + "deleteChat": "Sohbeti Sil", + "selectAll": "Tümünü Seç", + "newChat": "Yeni Sohbet", + "send": "Gönder", + "more": "Daha Fazla", + "noMoreData": "Daha fazla veri yok" +} \ No newline at end of file diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb new file mode 100644 index 0000000..f1989ee --- /dev/null +++ b/lib/l10n/app_zh.arb @@ -0,0 +1,281 @@ +{ + "@@locale": "zh", + "settings": "设置", + "general": "通用", + "providers": "服务提供商", + "mcpServer": "MCP 服务器", + "language": "语言", + "theme": "主题", + "dark": "深色", + "light": "浅色", + "system": "跟随系统", + "languageSettings": "语言设置", + "featureSettings": "功能设置", + "enableArtifacts": "启用人工制品", + "enableArtifactsDescription": "在对话中启用 AI 助手的人工制品,这将使用更多的令牌", + "enableToolUsage": "启用工具使用", + "enableToolUsageDescription": "在对话中启用工具的使用,这将使用更多的令牌", + "themeSettings": "主题设置", + "lightTheme": "浅色主题", + "darkTheme": "深色主题", + "followSystem": "跟随系统", + "showAvatar": "显示头像", + "showAssistantAvatar": "显示助手头像", + "showAssistantAvatarDescription": "在对话中显示 AI 助手的头像", + "showUserAvatar": "显示用户头像", + "showUserAvatarDescription": "在对话中显示用户的头像", + "systemPrompt": "系统提示词", + "systemPromptDescription": "这是与 AI 助手对话的系统提示词,用于设置助手的行为和风格", + "llmKey": "LLM 密钥", + "toolKey": "工具密钥", + "saveSettings": "保存设置", + "apiKey": "API 密钥", + "enterApiKey": "请输入您的 {provider} API 密钥", + "apiKeyValidation": "API 密钥必须至少包含 10 个字符", + "apiEndpoint": "API 端点", + "enterApiEndpoint": "请输入 API 端点 URL", + "apiVersion": "API 版本", + "enterApiVersion": "输入 API 版本", + "platformNotSupported": "当前平台不支持 MCP Server", + "mcpServerDesktopOnly": "MCP Server 仅支持桌面端(Windows、macOS、Linux)", + "searchServer": "搜索服务器...", + "noServerConfigs": "未找到服务器配置", + "addProvider": "添加服务商", + "refresh": "刷新", + "install": "安装", + "edit": "编辑", + "delete": "删除", + "command": "命令 或 服务地址", + "arguments": "参数", + "environmentVariables": "环境变量", + "serverName": "服务器名称", + "commandExample": "例如:npx、uvx、https://mcpserver.com", + "argumentsExample": "参数之间用空格分隔,包含空格的参数请用引号包围,例如:-y obsidian-mcp '/Users/username/Documents/Obsidian Vault'", + "envVarsFormat": "每行一个,格式:KEY=VALUE", + "cancel": "取消", + "save": "保存", + "confirmDelete": "确认删除", + "confirmDeleteServer": "您确定要删除服务器 \"{name}\" 吗?", + "error": "错误", + "commandNotExist": "命令 \"{command}\" 不存在,请先安装\n\n当前 PATH:\n{path}", + "all": "全部", + "installed": "已安装", + "modelSettings": "模型设置", + "temperature": "采样温度: {value}", + "temperatureTooltip": "采样温度控制输出的随机性:\n• 0.0:适合代码生成和数学解题\n• 1.0:适合数据抽取和分析\n• 1.3:适合通用对话和翻译\n• 1.5:适合创意写作和诗歌创作", + "topP": "核采样: {value}", + "topPTooltip": "Top P(核采样)是temperature的替代方案。模型只考虑累积概率超过P的标记。建议不要同时修改temperature和top_p。", + "maxTokens": "最大令牌数", + "maxTokensTooltip": "生成的最大令牌数。一个令牌大约等于4个字符。较长的对话需要更多的令牌。", + "frequencyPenalty": "频率惩罚: {value}", + "frequencyPenaltyTooltip": "频率惩罚参数。正值会根据新标记在文本中的现有频率来惩罚它们,降低模型逐字重复同样内容的可能性。", + "presencePenalty": "存在惩罚: {value}", + "presencePenaltyTooltip": "存在惩罚参数。正值会根据新标记是否出现在文本中来惩罚它们,增加模型谈论新主题的可能性。", + "enterMaxTokens": "输入最大令牌数", + "share": "分享", + "modelConfig": "模型配置", + "debug": "调试", + "webSearchTest": "网页搜索测试", + "today": "今天", + "yesterday": "昨天", + "last7Days": "前 7 天", + "last30Days": "前 30 天", + "earlier": "更早", + "confirmDeleteSelected": "确定要删除选中的对话吗?", + "confirmThisChat": "您确定要删除这些对话吗?", + "ok": "确定", + "askMeAnything": "问我任何问题...", + "uploadFiles": "上传文件", + "welcomeMessage": "今天我能帮您什么?", + "copy": "复制", + "copied": "已复制到剪贴板", + "retry": "重试", + "brokenImage": "图片损坏", + "toolCall": "调用 {name}", + "toolResult": "调用 {name} 结果", + "selectModel": "选择模型", + "close": "关闭", + "selectFromGallery": "从图库选择", + "selectFile": "选择文件", + "uploadFile": "上传文件", + "openBrowser": "打开浏览器", + "codeCopiedToClipboard": "代码已复制到剪贴板", + "thinking": "思考中", + "thinkingEnd": "思考结束", + "tool": "工具", + "userCancelledToolCall": "用户取消了工具调用", + "code": "代码", + "preview": "预览", + "functionCallAuth": "工具调用授权", + "allowFunctionExecution": "是否允许执行以下工具:", + "parameters": "参数: {params}", + "allow": "允许", + "loadContentFailed": "加载内容失败,请重试", + "loadDiagramFailed": "加载图表失败,请重试", + "copiedToClipboard": "已复制到剪贴板", + "chinese": "中文", + "turkish": "土耳其语", + "functionRunning": "正在执行工具...", + "userCancelledToolCall": "工具执行失败", + "thinkingProcess": "思考中", + "thinkingProcessWithDuration": "思考中, 用时", + "thinkingEndWithDuration": "思考完成,用时", + "thinkingEndComplete": "思考完成", + "seconds": "{seconds}秒", + "fieldRequired": "此字段为必填项", + "autoApprove": "自动批准", + "verify": "验证密钥", + "howToGet": "如何获取", + "modelList": "模型列表", + "enableModels": "启用模型", + "disableAllModels": "禁用所有模型", + "saveSuccess": "设置保存成功", + "genTitleModel": "标题生成", + "serverNameTooLong": "服务名称长度不能超过 50 个字符", + "serverType": "服务类型", + "reset": "重置", + "start": "启动", + "stop": "停止", + "search": "搜索", + "newVersionFound": "发现新版本 {version}", + "newVersionAvailable": "发现新版本", + "updateNow": "立即更新", + "updateLater": "稍后更新", + "ignoreThisVersion": "忽略此版本", + "releaseNotes": "更新内容:", + "openUrlFailed": "无法打开链接", + "checkingForUpdates": "正在检查更新...", + "checkUpdate": "检查更新", + "appDescription": "ChatMCP 是一款跨平台的 AI 客户端,致力于让更多人方便地使用 AI。", + "visitWebsite": "站点", + "aboutApp": "关于", + "networkError": "网络连接问题,请检查网络后重试", + "noElementError": "未找到匹配内容,请重试", + "permissionError": "权限不足,请检查设置", + "unknownError": "发生未知错误", + "timeoutError": "请求超时,请稍后重试", + "notFoundError": "未找到请求的资源", + "invalidError": "无效的请求或参数", + "unauthorizedError": "未授权访问,请检查权限", + "minimize": "最小化", + "maximize": "最大化", + "conversationSettings": "对话设置", + "maxMessages": "最大消息数", + "maxMessagesDescription": "限制传递给 LLM 的最大消息数量 (1-1000)", + "maxLoops": "最大循环数", + "maxLoopsDescription": "限制工具调用的最大循环次数,防止无限循环 (1-1000)", + "mcpServers": "MCP 服务器", + "getApiKey": "获取 API 秘钥", + "openingBrowser": "正在打开浏览器", + "confirm": "确认", + "providerName": "提供商名称", + "apiStyle": "API 风格", + "enterProviderName": "输入提供商名称", + "providerNameRequired": "提供商名称为必填项", + "addModel": "添加模型", + "modelName": "模型名称", + "enterModelName": "输入模型名称", + "noApiConfigs": "无可用的 API 配置", + "add": "添加", + "fetch": "获取", + "on": "开启", + "off": "关闭", + "apiUrl": "API 地址", + "selectApiStyle": "请选择 API 风格", + "proxySettings": "代理设置", + "enableProxy": "启用代理", + "enableProxyDescription": "启用代理后,网络请求将通过配置的代理服务器", + "proxyType": "代理类型", + "proxyHost": "代理地址", + "proxyPort": "代理端口", + "proxyUsername": "用户名", + "proxyPassword": "密码", + "enterProxyHost": "请输入代理服务器地址", + "enterProxyPort": "请输入代理端口", + "enterProxyUsername": "请输入用户名(可选)", + "enterProxyPassword": "请输入密码(可选)", + "proxyHostRequired": "代理地址为必填项", + "proxyPortInvalid": "代理端口必须在 1-65535 之间", + "saved": "已保存", + "dataSync": "数据同步", + "syncServerRunning": "同步服务器运行中", + "maintenance": "维护", + "cleanupLogs": "清理旧日志", + "cleanupLogsDescription": "清理日志文件", + "confirmCleanup": "确认清理", + "confirmCleanupMessage": "确定要删除日志文件吗?此操作不可撤销。", + "cleanupSuccess": "旧日志清理完成", + "cleanupFailed": "清理失败", + "syncServerStopped": "同步服务器已停止", + "scanQRToConnect": "其他设备扫描此二维码连接:", + "addressCopied": "地址已复制到剪贴板", + "otherDevicesCanScan": "其他设备可以扫描此二维码快速连接", + "startServer": "启动服务器", + "stopServer": "停止服务器", + "connectToOtherDevices": "连接到其他设备", + "scanQRCode": "扫描二维码连接", + "connectionHistory": "连接历史:", + "connect": "连接", + "manualInputAddress": "或手动输入服务器地址:", + "serverAddress": "服务器地址", + "syncFromServer": "从服务器同步", + "pushToServer": "推送到服务器", + "usageInstructions": "使用说明", + "desktopAsServer": "桌面端作为服务器:", + "desktopStep1": "1. 点击\"启动服务器\"按钮", + "desktopStep2": "2. 显示二维码给手机扫描", + "desktopStep3": "3. 手机扫码后可进行数据同步", + "mobileConnect": "手机端连接:", + "mobileStep1": "1. 点击\"扫描二维码连接\"", + "mobileStep2": "2. 扫描桌面端显示的二维码", + "mobileStep3": "3. 选择同步方向(上传/下载)", + "dataSync": "数据同步", + "uploadDescription": "• 上传:将本设备数据推送到服务器", + "downloadDescription": "• 下载:从服务器获取数据到本设备", + "syncContent": "• 同步内容:聊天记录、设置、MCP配置", + "syncServerStarted": "同步服务器已启动", + "syncServerStartFailed": "启动服务器失败", + "syncServerStopped": "同步服务器已停止", + "syncServerStopFailed": "停止服务器失败", + "scanQRCodeTitle": "扫描二维码", + "flashOn": "开启闪光灯", + "flashOff": "关闭闪光灯", + "aimQRCode": "将二维码对准扫描框", + "scanSyncQRCode": "扫描桌面端显示的同步二维码", + "manualInputAddressButton": "手动输入地址", + "manualInputServerAddress": "手动输入服务器地址", + "enterValidServerAddress": "请输入有效的服务器地址", + "scanSuccessConnectTo": "扫描成功,连接到: {deviceName}", + "scanSuccessAddressFilled": "扫描成功,已填入服务器地址", + "scannerOpenFailed": "打开扫码器失败", + "pleaseInputServerAddress": "请先扫码或输入服务器地址", + "connectingToServer": "正在连接服务器...", + "downloadingData": "正在下载数据...", + "importingData": "正在导入数据...", + "reinitializingData": "正在重新初始化应用数据...", + "dataSyncSuccess": "数据同步成功", + "preparingData": "正在准备数据...", + "uploadingData": "正在上传数据...", + "dataPushSuccess": "数据推送成功", + "syncFailed": "同步失败", + "pushFailed": "推送失败", + "justNow": "刚刚", + "minutesAgo": "{minutes}分钟前", + "hoursAgo": "{hours}小时前", + "daysAgo": "{days}天前", + "serverSelected": "已选择服务器: {deviceName}", + "connectionRecordDeleted": "已删除连接记录", + "viewAllConnections": "查看全部 {count} 个连接", + "clearAllHistory": "清空所有", + "clearAllConnectionHistory": "已清空所有连接历史", + "unknownDevice": "未知设备", + "unknownPlatform": "未知平台", + "inmemory": "内置", + "toggleSidebar": "切换侧边栏", + "deleteChat": "删除聊天", + "selectAll": "全选", + "newChat": "新聊天", + "send": "发送", + "more": "更多", + "noMoreData": "没有更多了" +} diff --git a/lib/llm/base_llm_client.dart b/lib/llm/base_llm_client.dart new file mode 100644 index 0000000..bf49264 --- /dev/null +++ b/lib/llm/base_llm_client.dart @@ -0,0 +1,238 @@ +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:logging/logging.dart'; +import 'model.dart'; +import 'utils.dart'; +import 'package:http/http.dart' as http; +import 'package:http/io_client.dart'; +import 'dart:io'; + +abstract class BaseLLMClient { + static http.Client createHttpClient() { + final generalSetting = ProviderManager.settingsProvider.generalSetting; + + if (generalSetting.enableProxy && generalSetting.proxyHost.isNotEmpty) { + final httpClient = HttpClient(); + + // Build proxy string - map proxy type to correct format + String proxyType; + switch (generalSetting.proxyType.toUpperCase()) { + case 'HTTP': + case 'HTTPS': + proxyType = 'PROXY'; + break; + case 'SOCKS4': + proxyType = 'SOCKS4'; + break; + case 'SOCKS5': + proxyType = 'SOCKS5'; + break; + default: + proxyType = 'PROXY'; + } + + String proxyString; + if (generalSetting.proxyUsername.isNotEmpty && generalSetting.proxyPassword.isNotEmpty) { + proxyString = + '$proxyType ${generalSetting.proxyUsername}:${generalSetting.proxyPassword}@${generalSetting.proxyHost}:${generalSetting.proxyPort}'; + } else { + proxyString = '$proxyType ${generalSetting.proxyHost}:${generalSetting.proxyPort}'; + } + + httpClient.findProxy = (uri) { + Logger.root.info('Using proxy: $proxyString for URL: $uri'); + return proxyString; + }; + + httpClient.badCertificateCallback = (cert, host, port) { + Logger.root.warning('Accepting certificate for proxy target: $host:$port'); + return true; + }; + + return IOClient(httpClient); + } else { + return http.Client(); + } + } + + Future chatCompletion(CompletionRequest request); + + Stream chatStreamCompletion(CompletionRequest request); + + String joinPaths(String first, String second) { + if (first.isEmpty) return second; + if (second.isEmpty) return first; + + final firstWithoutTrailing = first.endsWith('/') ? first.substring(0, first.length - 1) : first; + final secondWithoutLeading = second.startsWith('/') ? second.substring(1) : second; + + return '$firstWithoutTrailing/$secondWithoutLeading'; + } + + String getEndpoint(String url, String path) { + final urlObj = Uri.parse(url); + final newPath = joinPaths(urlObj.path, path); + return urlObj.replace(path: newPath).toString(); + } + + Future> checkToolCall(String model, CompletionRequest request, Map>> toolsResponse) async { + final openaiTools = convertToOpenAITools(toolsResponse); + + try { + final response = await chatCompletion(CompletionRequest(model: model, messages: request.messages, tools: openaiTools)); + + if (!response.needToolCall) { + return {'need_tool_call': false, 'content': response.content}; + } + + // Return tool call details + return { + 'need_tool_call': true, + 'content': response.content, + 'tool_calls': response.toolCalls + ?.map((call) => {'id': call.id, 'name': call.function.name, 'arguments': call.function.parsedArguments}) + .toList(), + }; + } catch (e) { + rethrow; // Re-throw the exception for outer handling + } + } + + Future handleError(dynamic e, String name, String endpoint, String bodyStr) async { + if (e is http.ClientException) { + return LLMException(name: name, endpoint: endpoint, requestBody: bodyStr, originalError: e); + } else if (e is Exception && e.toString().contains('HTTP')) { + // Handle HTTP errors (like "HTTP 400: Bad Request") + final errorMsg = e.toString(); + final statusCodeMatch = RegExp(r'HTTP (\d+)').firstMatch(errorMsg); + final statusCode = statusCodeMatch != null ? int.tryParse(statusCodeMatch.group(1) ?? '') : null; + + return LLMException(name: name, endpoint: endpoint, requestBody: bodyStr, statusCode: statusCode, responseData: errorMsg, originalError: e); + } else { + return LLMException(name: name, endpoint: endpoint, requestBody: bodyStr, originalError: e); + } + } + + String getGenTitleModel() { + final model = ProviderManager.chatModelProvider.currentModel; + final providerSetting = ProviderManager.settingsProvider.getProviderSetting(model.providerId); + return providerSetting.genTitleModel != null && providerSetting.genTitleModel!.isNotEmpty ? providerSetting.genTitleModel! : model.name; + } + + Future genTitle(List messages) async { + if (messages.isEmpty) return "new chat"; + + // 限制内容长度,避免触发内容过滤器 + final conversationText = messages + .map((msg) { + final role = msg.role == MessageRole.user ? "Human" : "Assistant"; + final content = msg.content ?? ''; + // 限制每条消息最多100个字符,避免内容过长 + final truncatedContent = content.length > 100 ? '${content.substring(0, 100)}...' : content; + return "$role: $truncatedContent"; + }) + .join("\n"); + + // 进一步限制总长度 + final finalText = conversationText.length > 500 ? '${conversationText.substring(0, 500)}...' : conversationText; + + try { + final prompt = ChatMessage( + role: MessageRole.user, + content: + """Generate a concise title based on the following conversation content. + +Conversation content: +$finalText + +Please return the result in the following XML format: +Your generated title (max 20 characters) + +Note: Only return the XML format result, the title should be concise and clear.""", + ); + + final response = await chatCompletion(CompletionRequest(model: getGenTitleModel(), messages: [prompt])); + + Logger.root.info('genTitle response: ${response.content}'); + + final content = response.content?.trim() ?? ""; + + // 从 XML 标签中提取标题 + final title = _extractTitleFromXml(content); + return title.isNotEmpty ? title : "New Chat"; + } catch (e, trace) { + Logger.root.severe('生成标题出错: $e, trace: $trace'); + return "New Chat"; + } + } + + /// 从 XML 格式的响应中提取标题 + String _extractTitleFromXml(String xmlContent) { + if (xmlContent.isEmpty) return ""; + + // 尝试匹配 ... 标签 + final titleRegex = RegExp(r'(.*?)', caseSensitive: false, dotAll: true); + final match = titleRegex.firstMatch(xmlContent); + + if (match != null && match.group(1) != null) { + return match.group(1)!.trim(); + } + + // 如果没有找到 XML 标签,尝试查找是否有其他可能的格式 + final lines = xmlContent.split('\n').where((line) => line.trim().isNotEmpty).toList(); + + // 如果只有一行且不包含 XML 标签,可能是纯文本标题 + if (lines.length == 1 && !lines.first.contains('<')) { + return lines.first.trim(); + } + + return ""; + } + + Future> models(); + + /// 将模型设置添加到请求体中,只有大于0的参数才会被设置 + Map addModelSettingsToBody(Map body, ChatSetting? modelSetting) { + if (modelSetting == null) return body; + + if (modelSetting.temperature > 0) { + body['temperature'] = modelSetting.temperature; + } + if (modelSetting.topP > 0) { + body['top_p'] = modelSetting.topP; + } + if (modelSetting.frequencyPenalty > 0) { + body['frequency_penalty'] = modelSetting.frequencyPenalty; + } + if (modelSetting.presencePenalty > 0) { + body['presence_penalty'] = modelSetting.presencePenalty; + } + if (modelSetting.maxTokens != null && modelSetting.maxTokens! > 0) { + body['max_tokens'] = modelSetting.maxTokens!; + } + + return body; + } +} + +class LLMException implements Exception { + final String name; + final String endpoint; + final String requestBody; + final int? statusCode; + final dynamic responseData; + final dynamic originalError; + + LLMException({required this.name, required this.endpoint, required this.requestBody, this.statusCode, this.responseData, this.originalError}); + + @override + String toString() { + return ''' +$name API call failed +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +Endpoint: $endpoint +${statusCode != null ? 'Status code: $statusCode\n' : ''}Request body: $requestBody +${responseData != null ? 'Response data: $responseData\n' : ''}Error message: $originalError +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'''; + } +} diff --git a/lib/llm/claude_client.dart b/lib/llm/claude_client.dart new file mode 100644 index 0000000..1a10b49 --- /dev/null +++ b/lib/llm/claude_client.dart @@ -0,0 +1,287 @@ +import 'package:http/http.dart' as http; +import 'dart:convert'; +import 'base_llm_client.dart'; +import 'model.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/utils/file_content.dart'; + +class ClaudeClient extends BaseLLMClient { + final String apiKey; + final String baseUrl; + final Map _headers; + + ClaudeClient({required this.apiKey, String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'https://api.anthropic.com' : baseUrl, + _headers = {'Content-Type': 'application/json; charset=utf-8', 'x-api-key': apiKey, 'anthropic-version': '2023-06-01'}; + + @override + Future chatCompletion(CompletionRequest request) async { + final httpClient = BaseLLMClient.createHttpClient(); + + final messages = chatMessageToClaudeMessage(request.messages); + + final body = {'model': request.model, 'messages': messages}; + + addModelSettingsToBody(body, request.modelSetting); + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = { + 'function_calling': {'tools': request.tools}, + }; + } + + final endpoint = '$baseUrl/messages'; + + try { + final response = await httpClient.post(Uri.parse(endpoint), headers: _headers, body: jsonEncode(body)); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('Claude response: $responseBody'); + + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final json = jsonDecode(responseBody); + final content = json['content'][0]['text']; + + // Parse tool calls if present + final toolCalls = json['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'], + type: t['type'], + function: FunctionCall(name: t['function']['name'], arguments: t['function']['arguments']), + ), + ) + ?.toList(); + + return LLMResponse(content: content, toolCalls: toolCalls); + } catch (e) { + throw await handleError(e, 'Claude', endpoint, jsonEncode(body)); + } finally { + httpClient.close(); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final messages = chatMessageToClaudeMessage(request.messages); + + final body = {'model': request.model, 'messages': messages, 'stream': true}; + + addModelSettingsToBody(body, request.modelSetting); + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = { + 'function_calling': {'tools': request.tools}, + }; + body['tool_choice'] = {'type': 'any'}; + } + + try { + final request = http.Request('POST', Uri.parse('$baseUrl/messages')); + request.headers.addAll(_headers); + request.body = jsonEncode(body); + + final response = await BaseLLMClient.createHttpClient().send(request); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('Claude response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + await for (final line in stream) { + if (!line.startsWith('data:')) continue; + + final jsonStr = line.substring(5).trim(); + if (jsonStr.isEmpty) continue; + + try { + final event = jsonDecode(jsonStr); + final eventType = event['type']; + + switch (eventType) { + case 'content_block_start': + if (event['content_block'] != null && event['content_block']['text'] != null) { + yield LLMResponse(content: event['content_block']['text']); + } else { + Logger.root.warning('Invalid content_block_start event: $event'); + } + break; + case 'content_block_delta': + final delta = event['delta']; + if (delta == null) { + Logger.root.warning('Invalid content_block_delta event: $event'); + break; + } + + // 直接处理文本内容 + if (delta['text'] != null) { + yield LLMResponse(content: delta['text']); + break; + } + + // 处理特定类型的 delta + if (delta['type'] == 'text_delta' && delta['text'] != null) { + yield LLMResponse(content: delta['text']); + } else if (delta['type'] == 'input_json_delta') { + // Handle tool use delta + // final partialJson = delta['partial_json']; + // You may want to accumulate the JSON and parse it when complete + } + break; + + case 'content_block_stop': + // Handle end of a content block + break; + + case 'message_stop': + // Handle end of message + break; + + case 'error': + final error = event['error']; + throw Exception('Stream error: ${error['message']}'); + + case 'ping': + // Ignore ping events + break; + } + } catch (e) { + Logger.root.warning('Failed to parse chunk: $jsonStr error: $e'); + continue; + } + } + } catch (e) { + throw await handleError(e, 'Claude', '$baseUrl/messages', jsonEncode(body)); + } + } + + @override + Future> checkToolCall(String model, CompletionRequest request, Map>> toolsResponse) async { + // Convert tools to Claude's format + final tools = toolsResponse.entries + .map((entry) { + return entry.value.map((tool) { + final parameters = tool['parameters']; + if (parameters is! Map) { + return { + 'name': tool['name'], + 'description': tool['description'], + 'input_schema': {'type': 'object', 'properties': {}, 'required': []}, + }; + } + + return { + 'name': tool['name'], + 'description': tool['description'], + 'input_schema': {'type': 'object', 'properties': parameters['properties'] ?? {}, 'required': parameters['required'] ?? []}, + }; + }).toList(); + }) + .expand((x) => x) + .toList(); + + final body = {'model': ProviderManager.chatModelProvider.currentModel.name, 'messages': request.messages, 'tools': tools, 'max_tokens': 4096}; + + try { + final response = await http.post(Uri.parse('$baseUrl/messages'), headers: _headers, body: jsonEncode(body)); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final jsonData = jsonDecode(response.body); + + // Check if response contains tool calls in the content array + final contentBlocks = jsonData['content'] as List?; + if (contentBlocks == null || contentBlocks.isEmpty) { + return {'need_tool_call': false, 'content': ''}; + } + + // Look for tool_calls in the response + final toolUseBlocks = contentBlocks.where((block) => block['type'] == 'tool_calls' || block['type'] == 'tool_use'); + + if (toolUseBlocks.isEmpty) { + // Get text content from the first text block + final textBlock = contentBlocks.firstWhere((block) => block['type'] == 'text', orElse: () => {'text': ''}); + return {'need_tool_call': false, 'content': textBlock['text'] ?? ''}; + } + + // Extract tool calls + final toolCalls = toolUseBlocks.map((block) => {'id': block['id'], 'name': block['name'], 'arguments': block['input']}).toList(); + + // Get any accompanying text content + final textBlock = contentBlocks.firstWhere((block) => block['type'] == 'text', orElse: () => {'text': ''}); + + return {'need_tool_call': true, 'content': textBlock['text'] ?? '', 'tool_calls': toolCalls}; + } catch (e) { + throw await handleError(e, 'Claude', '$baseUrl/messages', jsonEncode(body)); + } + } + + @override + Future> models() async { + if (apiKey.isEmpty) { + Logger.root.info('Claude API key not set, skipping model list retrieval'); + return []; + } + + try { + final response = await http.get(Uri.parse('$baseUrl/models'), headers: _headers); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + final models = (data['data'] as List).map((m) => m['id'].toString()).where((id) => id.contains('claude')).toList(); + + return models; + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + return []; + } + } +} + +List> chatMessageToClaudeMessage(List messages) { + return messages.map((message) { + final List> contentParts = []; + + // Add file content (if any) + if (message.files != null) { + for (final file in message.files!) { + if (isImageFile(file.fileType)) { + contentParts.add({ + 'type': 'image', + 'source': {'type': 'base64', 'media_type': file.fileType, 'data': file.fileContent}, + }); + } + if (isTextFile(file.fileType)) { + contentParts.add({'type': 'text', 'text': file.fileContent}); + } + } + } + + // Add text content + if (message.content != null) { + contentParts.add({'type': 'text', 'text': message.content}); + } + + final json = {'role': message.role == MessageRole.user ? 'user' : 'assistant', 'content': contentParts}; + + if (contentParts.length == 1 && message.files == null) { + json['content'] = message.content ?? ''; + } else { + json['content'] = contentParts; + } + + return json; + }).toList(); +} diff --git a/lib/llm/claude_code_client.dart b/lib/llm/claude_code_client.dart new file mode 100644 index 0000000..8ba0e01 --- /dev/null +++ b/lib/llm/claude_code_client.dart @@ -0,0 +1,215 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:logging/logging.dart'; + +import 'base_llm_client.dart'; +import 'model.dart'; + +/// Claude Code client backed by the `claude` CLI. +/// +/// This client shells out to the Claude Code SDK CLI, so it works without +/// directly using Anthropic HTTP APIs. It expects the `claude` binary to be +/// available on PATH (or via a configured absolute path), and that the user +/// has already authenticated per Claude Code SDK docs. +/// +/// Non-goals: +/// - Tool calling is not wired, as Claude Code has its own tool system +/// (Read/Write/Bash). We ignore `tools` in requests. +class ClaudeCodeClient extends BaseLLMClient { + /// Path or name of the Claude Code CLI executable. Defaults to `claude`. + final String executable; + + ClaudeCodeClient({String? executablePath}) : executable = (executablePath == null || executablePath.isEmpty) ? 'claude' : executablePath; + + @override + Future chatCompletion(CompletionRequest request) async { + final prompt = _buildPromptFromMessages(request.messages); + + // Use JSON output for reliable parsing + final args = ['-p', prompt, '--output-format', 'json']; + + try { + final result = await Process.run(executable, args, runInShell: true); + + if (result.exitCode != 0) { + throw Exception( + result.stderr is String && (result.stderr as String).isNotEmpty ? result.stderr : 'Claude Code CLI exited with ${result.exitCode}', + ); + } + + final output = result.stdout is String ? result.stdout as String : utf8.decode((result.stdout as List)); + final content = _parseClaudeCodeJsonOutput(output); + return LLMResponse(content: content); + } catch (e) { + // Surface a structured error via BaseLLMClient.handleError contract + throw await handleError(e, 'Claude Code', executable, jsonEncode({'args': args})); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final prompt = _buildPromptFromMessages(request.messages); + + // Stream JSON lines so we can emit partial updates when possible. + final args = ['-p', prompt, '--output-format', 'stream-json']; + + Process? process; + try { + process = await Process.start(executable, args, runInShell: true); + + final stdoutLines = process.stdout.transform(utf8.decoder).transform(const LineSplitter()); + final stderrBuffer = StringBuffer(); + + // Drain stderr to help debugging on failure + unawaited(process.stderr.transform(utf8.decoder).forEach(stderrBuffer.write)); + + String aggregated = ''; + + await for (final line in stdoutLines) { + // Expecting JSONL objects, one per line + try { + final obj = jsonDecode(line); + final type = obj['type']; + if (type == 'assistant') { + final contentPiece = _extractTextFromAssistantMessage(obj['message']); + if (contentPiece.isNotEmpty) { + aggregated += contentPiece; + yield LLMResponse(content: contentPiece); + } + } else if (type == 'result') { + // Final result line; emit any missing content if stream lacked assistant pieces + final resultText = (obj['result'] ?? '').toString(); + if (aggregated.isEmpty && resultText.isNotEmpty) { + yield LLMResponse(content: resultText); + } + } + } catch (_) { + // If a line isn't valid JSON, ignore it; CLI may print logs in verbose modes + continue; + } + } + + final exitCode = await process.exitCode; + if (exitCode != 0) { + throw Exception(stderrBuffer.isNotEmpty ? stderrBuffer.toString() : 'Claude Code CLI exited with $exitCode'); + } + } catch (e) { + throw await handleError(e, 'Claude Code', executable, jsonEncode({'args': args})); + } finally { + // Ensure process is killed if still alive + if (process != null) { + try { + process.kill(ProcessSignal.sigterm); + } catch (_) {} + } + } + } + + @override + Future> models() async { + // Claude Code CLI does not expose a model listing endpoint. + // Return a common set; users can customize in settings. + return ['claude-3-7-sonnet', 'claude-3-opus', 'claude-3-5-sonnet', 'claude-3-5-haiku']; + } + + String _buildPromptFromMessages(List messages) { + // Keep recent context small to avoid overly long shell args. + const int maxMessages = 12; + final recent = messages.length <= maxMessages ? messages : messages.sublist(messages.length - maxMessages); + + final buffer = StringBuffer(); + for (final m in recent) { + final content = (m.content ?? '').trim(); + if (content.isEmpty) continue; + switch (m.role) { + case MessageRole.system: + buffer.writeln('System: $content'); + break; + case MessageRole.user: + buffer.writeln('User: $content'); + break; + case MessageRole.assistant: + buffer.writeln('Assistant: $content'); + break; + default: + // Ignore tool/function/error/loading in prompt for Claude Code + break; + } + } + return buffer.toString().trim(); + } + + /// Parse JSON output from `claude -p --output-format json`. + /// The CLI typically prints a single JSON object. If multiple JSONL lines + /// are present, prefer the final `result` type; otherwise accumulate + /// assistant messages. + String _parseClaudeCodeJsonOutput(String output) { + output = output.trim(); + if (output.isEmpty) return ''; + + // Try strict JSON first + try { + final obj = jsonDecode(output); + final type = obj is Map ? obj['type'] : null; + if (type == 'result') { + return (obj['result'] ?? '').toString(); + } + if (type == 'assistant') { + return _extractTextFromAssistantMessage(obj['message']); + } + // Some versions might output a flat object with `result` + if (obj is Map && obj.containsKey('result')) { + return (obj['result'] ?? '').toString(); + } + } catch (_) { + // Fall through to JSONL mode + } + + // Fallback: parse line-by-line as JSONL + String aggregated = ''; + for (final line in const LineSplitter().convert(output)) { + final trimmed = line.trim(); + if (trimmed.isEmpty) continue; + try { + final obj = jsonDecode(trimmed); + final type = obj['type']; + if (type == 'assistant') { + aggregated += _extractTextFromAssistantMessage(obj['message']); + } else if (type == 'result') { + if (aggregated.isEmpty) { + aggregated = (obj['result'] ?? '').toString(); + } + } + } catch (_) { + continue; + } + } + return aggregated; + } + + /// Extract plain text from an Anthropic SDK `Message` object + /// produced by Claude Code CLI JSON messages. + String _extractTextFromAssistantMessage(dynamic messageObj) { + if (messageObj == null) return ''; + try { + final content = messageObj['content']; + if (content is List) { + final texts = []; + for (final part in content) { + if (part is Map) { + final type = part['type']; + if (type == 'text' && part['text'] is String) { + texts.add(part['text'] as String); + } + } + } + return texts.join(''); + } + } catch (e) { + Logger.root.fine('Failed to parse assistant message content: $e'); + } + return ''; + } +} diff --git a/lib/llm/copilot_client.dart b/lib/llm/copilot_client.dart new file mode 100644 index 0000000..08deb85 --- /dev/null +++ b/lib/llm/copilot_client.dart @@ -0,0 +1,5 @@ +import 'package:chatmcp/llm/openai_client.dart'; + +class CopilotClient extends OpenAIClient { + CopilotClient({required super.apiKey}) : super(baseUrl: 'https://api.githubcopilot.com'); +} diff --git a/lib/llm/deepseek_client.dart b/lib/llm/deepseek_client.dart new file mode 100644 index 0000000..dd44d28 --- /dev/null +++ b/lib/llm/deepseek_client.dart @@ -0,0 +1,191 @@ +import 'package:http/http.dart' as http; +import 'base_llm_client.dart'; +import 'dart:convert'; +import 'model.dart'; +import 'package:logging/logging.dart'; +import './openai_client.dart'; + +class DeepSeekClient extends BaseLLMClient { + final String apiKey; + final String baseUrl; + final Map _headers; + + DeepSeekClient({required this.apiKey, String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'https://api.deepseek.com' : baseUrl, + _headers = {'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Bearer $apiKey'}; + + @override + Future chatCompletion(CompletionRequest request) async { + final httpClient = BaseLLMClient.createHttpClient(); + + try { + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages)}; + addModelSettingsToBody(body, request.modelSetting); + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = request.tools!; + body['tool_choice'] = 'auto'; + } + + final bodyStr = jsonEncode(body); + + final response = await httpClient.post(Uri.parse("$baseUrl/v1/chat/completions"), headers: _headers, body: bodyStr); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('DeepSeek response: $responseBody'); + + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final jsonData = jsonDecode(responseBody); + final message = jsonData['choices'][0]['message']; + + // Parse tool calls + final toolCalls = message['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'], + type: t['type'], + function: FunctionCall(name: t['function']['name'], arguments: t['function']['arguments']), + ), + ) + ?.toList(); + + return LLMResponse(content: message['content'], toolCalls: toolCalls); + } catch (e) { + throw await handleError(e, 'DeepSeek', '$baseUrl/v1/chat/completions', jsonEncode({})); + } finally { + httpClient.close(); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages), 'stream': true}; + addModelSettingsToBody(body, request.modelSetting); + + try { + final bodyStr = jsonEncode(body); + final request = http.Request('POST', Uri.parse('$baseUrl/chat/completions')); + request.headers.addAll(_headers); + request.body = bodyStr; + Logger.root.info('deepseek request chat stream completion: $bodyStr'); + + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.send(request); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('DeepSeek response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + Logger.root.info('deepseek start stream response'); + bool reasoningContentStart = false; + bool reasoningContentEnd = false; + bool reasoningStyle = false; + + await for (final line in stream) { + if (!line.startsWith('data: ')) continue; + final jsonStr = line.substring(6).trim(); + if (jsonStr.isEmpty || jsonStr == '[DONE]') continue; + + try { + final json = jsonDecode(jsonStr); + + // Check if choices array is empty + if (json['choices'] == null || json['choices'].isEmpty || json['choices'].length < 1) { + continue; + } + + final delta = json['choices'][0]['delta']; + if (delta == null) continue; + + // Parse tool calls + final toolCalls = delta['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'] ?? '', + type: t['type'] ?? '', + function: FunctionCall(name: t['function']?['name'] ?? '', arguments: t['function']?['arguments'] ?? '{}'), + ), + ) + ?.toList(); + + final reasoningContent = delta != null ? (delta['reasoning_content'] ?? '') : ''; + + if (reasoningContent.isNotEmpty) { + reasoningStyle = true; + if (!reasoningContentStart) { + reasoningContentStart = true; + yield LLMResponse(content: '\n\n$reasoningContent', toolCalls: toolCalls); + } else { + yield LLMResponse(content: reasoningContent, toolCalls: toolCalls); + } + } + + if (reasoningStyle) { + final content = delta != null ? (delta['content'] ?? '') : ''; + if (content.isNotEmpty) { + if (!reasoningContentEnd) { + reasoningContentEnd = true; + yield LLMResponse(content: '\n\n$content', toolCalls: toolCalls); + } else { + yield LLMResponse(content: content, toolCalls: toolCalls); + } + } + } else { + // Only yield response when there is content or tool calls + if (delta != null && delta['content'] != null) { + String content = delta != null ? (delta['content'] ?? '') : ''; + if (content.isNotEmpty && content.contains('')) { + content = content.replaceAll('', ''); + } + if (content.isNotEmpty && content.contains('')) { + content = content.replaceAll('', ''); + } + + yield LLMResponse(content: content, toolCalls: toolCalls); + } + } + } catch (e, trace) { + Logger.root.severe('Failed to parse chunk: $jsonStr, error: $e, trace: $trace'); + continue; + } + } + } catch (e, trace) { + Logger.root.severe('DeepSeek stream completion error: $e, trace: $trace'); + throw await handleError(e, 'DeepSeek', '$baseUrl/chat/completions', jsonEncode(body)); + } + } + + @override + Future> models() async { + if (apiKey.isEmpty) { + Logger.root.info('DeepSeek API key not set, skipping model list retrieval'); + return []; + } + + final httpClient = BaseLLMClient.createHttpClient(); + + try { + final response = await httpClient.get(Uri.parse("$baseUrl/v1/models"), headers: _headers); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + final models = (data['data'] as List).map((m) => m['id'].toString()).where((id) => id.contains('deepseek')).toList(); + + return models; + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + return []; + } + } +} diff --git a/lib/llm/foundry_client.dart b/lib/llm/foundry_client.dart new file mode 100644 index 0000000..c61ecd8 --- /dev/null +++ b/lib/llm/foundry_client.dart @@ -0,0 +1,222 @@ +import 'package:chatmcp/utils/toast.dart'; +import 'package:http/http.dart' as http; +import 'base_llm_client.dart'; +import 'dart:convert'; +import 'model.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/utils/file_content.dart'; + +class FoundryClient extends BaseLLMClient { + final String apiKey; + final String baseUrl; + final String apiVersion; + final String modelVersion = '2023-03-15-preview'; + final Map _headers; + + FoundryClient({required this.apiKey, String? apiVersion, String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'https://YOUR_RESOURCE_NAME.openai.azure.com' : baseUrl, + apiVersion = apiVersion ?? 'preview', + _headers = {'Content-Type': 'application/json; charset=utf-8', 'api-key': apiKey}; + + @override + Future chatCompletion(CompletionRequest request) async { + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages)}; + + addModelSettingsToBody(body, request.modelSetting); + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = request.tools!; + body['tool_choice'] = 'auto'; + } + + final bodyStr = jsonEncode(body); + Logger.root.fine('OpenAI request: $bodyStr'); + + final endpoint = apiVersion == "preview" + ? "${getEndpoint(baseUrl, '/openai/v1/chat/completions')}?api-version=$apiVersion" + : "${getEndpoint(baseUrl, '/openai/deployments/${request.model}/chat/completions')}?api-version=$apiVersion"; + + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.post(Uri.parse(endpoint), headers: _headers, body: jsonEncode(body)); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('OpenAI response: $responseBody'); + + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final jsonData = jsonDecode(responseBody); + + final message = jsonData['choices'][0]['message']; + + // Parse tool calls + final toolCalls = message['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'], + type: t['type'], + function: FunctionCall(name: t['function']['name'], arguments: t['function']['arguments']), + ), + ) + ?.toList(); + + return LLMResponse(content: message['content'], toolCalls: toolCalls); + } catch (e) { + throw await handleError(e, 'Foundry', endpoint, bodyStr); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages), 'stream': true}; + + addModelSettingsToBody(body, request.modelSetting); + + Logger.root.fine("debug log:openai stream body: ${jsonEncode(body)}"); + + final endpoint = apiVersion == "preview" + ? "${getEndpoint(baseUrl, '/openai/v1/chat/completions')}?api-version=$apiVersion" + : "${getEndpoint(baseUrl, '/openai/deployments/${request.model}/chat/completions')}?api-version=$apiVersion"; + + try { + final request = http.Request('POST', Uri.parse(endpoint)); + request.headers.addAll(_headers); + request.body = jsonEncode(body); + + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.send(request); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('OpenAI response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + await for (final line in stream) { + if (!line.startsWith('data: ')) continue; + final data = line.substring(6); + if (data.isEmpty || data == '[DONE]') continue; + + try { + final json = jsonDecode(data); + + if (json['choices'] == null || json['choices'].isEmpty) { + continue; + } + + final delta = json['choices'][0]['delta']; + if (delta == null) continue; + + final toolCalls = delta['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'] ?? '', + type: t['type'] ?? '', + function: FunctionCall(name: t['function']?['name'] ?? '', arguments: t['function']?['arguments'] ?? '{}'), + ), + ) + ?.toList(); + + if (delta['content'] != null || toolCalls != null) { + yield LLMResponse(content: delta['content'], toolCalls: toolCalls); + } + } catch (e) { + Logger.root.severe('Failed to parse event data: $data $e'); + continue; + } + } + } catch (e) { + throw await handleError(e, 'Foundry', endpoint, jsonEncode(body)); + } + } + + @override + Future> models() async { + if (apiKey.isEmpty) { + ToastUtils.error('API key not set, skipping model list fetch'); + return []; + } + + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.get(Uri.parse("${getEndpoint(baseUrl, "/openai/deployments")}?api-version=$modelVersion"), headers: _headers); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + + // Filter out models o1-mini and o1-preview, because of unsupported system message + final models = (data['data'] as List) + .where((m) => m['status'] == 'succeeded' && m['model'] != 'o1-mini' && m['model'] != 'o1-preview') + .map((m) => m['id'].toString()) + .toList(); + + return models; + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + throw LLMException( + name: 'Foundry', + endpoint: Uri.parse("${getEndpoint(baseUrl, "/openai/deployments")}?api-version=$modelVersion").toString(), + requestBody: '', + originalError: e, + ); + } + } +} + +List> chatMessageToOpenAIMessage(List messages) { + return messages.map((message) { + final json = {'role': message.role.value}; + + // If there is both text content and files, use array format + if (message.content != null || message.files != null) { + final List> contentParts = []; + + // Add file content + if (message.files != null) { + for (final file in message.files!) { + if (isImageFile(file.fileType)) { + contentParts.add({ + 'type': 'image_url', + 'image_url': {"url": "data:${file.fileType};base64,${file.fileContent}"}, + }); + } + if (isTextFile(file.fileType)) { + contentParts.add({'type': 'text', 'text': file.fileContent}); + } + } + } + + // Add text content + if (message.content != null) { + contentParts.add({'type': 'text', 'text': message.content}); + } + + // If there is only one text content and no files, use simple string format + if (contentParts.length == 1 && message.files == null) { + json['content'] = message.content; + } else { + json['content'] = contentParts; + } + } + + // Add tool call related fields + if (message.role == MessageRole.tool && message.name != null && message.toolCallId != null) { + json['name'] = message.name!; + json['tool_call_id'] = message.toolCallId!; + } + + if (message.toolCalls != null) { + json['tool_calls'] = message.toolCalls; + } + + return json; + }).toList(); +} diff --git a/lib/llm/gemini_client.dart b/lib/llm/gemini_client.dart new file mode 100644 index 0000000..92518f3 --- /dev/null +++ b/lib/llm/gemini_client.dart @@ -0,0 +1,179 @@ +import 'package:http/http.dart' as http; +import 'base_llm_client.dart'; +import 'dart:convert'; +import 'model.dart'; +import 'package:logging/logging.dart'; + +class GeminiClient extends BaseLLMClient { + final String apiKey; + final String baseUrl; + + GeminiClient({required this.apiKey, String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'https://generativelanguage.googleapis.com' : baseUrl; + + @override + Future chatCompletion(CompletionRequest request) async { + final modelName = request.model; + + final body = { + 'contents': chatMessageToGeminiMessage(request.messages), + if (request.modelSetting != null) + 'generationConfig': { + 'temperature': request.modelSetting!.temperature, + 'topP': request.modelSetting!.topP, + if (request.modelSetting!.maxTokens != null) 'maxOutputTokens': request.modelSetting!.maxTokens, + }, + }; + + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.post( + Uri.parse("$baseUrl/models/$modelName:generateContent?key=$apiKey"), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode(body), + ); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('Gemini response: $responseBody'); + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final jsonData = jsonDecode(responseBody); + final candidates = jsonData['candidates'] as List; + if (candidates.isEmpty) { + throw Exception('No response from Gemini API'); + } + + final content = candidates[0]['content']; + final text = content['parts'][0]['text']; + + final usage = TokenUsage.fromGemini(jsonData['usageMetadata'], modelName: jsonData['modelVersion']); + + return LLMResponse(content: text, tokenUsage: usage); + } catch (e) { + throw await handleError(e, 'Gemini', '$baseUrl/models/$modelName:generateContent', jsonEncode(body)); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final modelName = request.model; + + final Map body = { + 'contents': [...chatMessageToGeminiMessage(request.messages)], + }; + + if (request.modelSetting != null) { + body['generationConfig'] = { + 'temperature': request.modelSetting!.temperature, + 'topP': request.modelSetting!.topP, + if (request.modelSetting!.maxTokens != null) 'maxOutputTokens': request.modelSetting!.maxTokens, + }; + } + + try { + final request = http.Request('POST', Uri.parse("$baseUrl/models/$modelName:streamGenerateContent?key=$apiKey&alt=sse")); + request.headers.addAll({'Content-Type': 'application/json'}); + request.body = jsonEncode(body); + + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.send(request); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('Gemini response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + await for (final line in stream) { + if (line.isEmpty || !line.startsWith('data: ')) continue; + + try { + final json = jsonDecode(line.substring(6)); // Remove 'data: ' prefix + + final candidates = json['candidates'] as List; + if (candidates.isEmpty) continue; + + final content = candidates[0]['content']; + final text = content['parts'][0]['text']; + + final usage = TokenUsage.fromGemini(json['usageMetadata'], modelName: json['modelVersion']); + + yield LLMResponse(content: text, tokenUsage: usage); + } catch (e) { + Logger.root.severe('Failed to parse chunk: $line $e'); + continue; + } + } + } catch (e) { + throw await handleError(e, 'Gemini', '$baseUrl/models/$modelName:streamGenerateContent', jsonEncode(body)); + } + } + + @override + Future> models() async { + if (apiKey.isEmpty) { + Logger.root.info('Gemini API key not set, skipping model list fetch'); + return []; + } + + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.get(Uri.parse("$baseUrl/models?key=$apiKey"), headers: {'Content-Type': 'application/json'}); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + final models = (data['models'] as List) + .map((m) => m['name'].toString().replaceAll('models/', '')) + .where((name) => name.startsWith('gemini-')) + .toList(); + + return models; + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + return []; + } + } +} + +List> chatMessageToGeminiMessage(List messages) { + return messages.map((message) { + final parts = >[]; + + // Add text content + if (message.content != null && message.content!.isNotEmpty) { + parts.add({'text': message.content}); + } + + // Add file content + if (message.files != null) { + for (final file in message.files!) { + if (isImageFile(file.fileType)) { + parts.add({ + 'inlineData': {'mimeType': file.fileType, 'data': file.fileContent}, + }); + } + } + } + + // 确保至少有一个part + if (parts.isEmpty) { + parts.add({ + 'text': ' ', // 添加一个空格作为默认文本 + }); + } + + return {'role': message.role == MessageRole.user ? 'user' : 'model', 'parts': parts}; + }).toList(); +} + +bool isImageFile(String mimeType) { + return mimeType.startsWith('image/'); +} diff --git a/lib/llm/llm_factory.dart b/lib/llm/llm_factory.dart new file mode 100644 index 0000000..5938d20 --- /dev/null +++ b/lib/llm/llm_factory.dart @@ -0,0 +1,103 @@ +import 'openai_client.dart'; +import 'claude_client.dart'; +import 'deepseek_client.dart'; +import 'base_llm_client.dart'; +import 'ollama_client.dart'; +import 'gemini_client.dart'; +import 'foundry_client.dart'; +import 'copilot_client.dart'; +import 'claude_code_client.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:logging/logging.dart'; +import 'model.dart' as llm_model; + +enum LLMProvider { openai, claude, ollama, deepseek, gemini, foundry, claudeCode, copilot } + +class LLMFactory { + static BaseLLMClient create(LLMProvider provider, {required String apiKey, required String baseUrl, String? apiVersion}) { + switch (provider) { + case LLMProvider.openai: + return OpenAIClient(apiKey: apiKey, baseUrl: baseUrl); + case LLMProvider.claude: + return ClaudeClient(apiKey: apiKey, baseUrl: baseUrl); + case LLMProvider.claudeCode: + return ClaudeCodeClient(); + case LLMProvider.deepseek: + return DeepSeekClient(apiKey: apiKey, baseUrl: baseUrl); + case LLMProvider.ollama: + return OllamaClient(baseUrl: baseUrl); + case LLMProvider.gemini: + return GeminiClient(apiKey: apiKey, baseUrl: baseUrl); + case LLMProvider.foundry: + return FoundryClient(apiKey: apiKey, baseUrl: baseUrl, apiVersion: apiVersion); + case LLMProvider.copilot: + return CopilotClient(apiKey: apiKey); + } + } +} + +class LLMFactoryHelper { + static final nonChatModelKeywords = {"whisper", "tts", "dall-e", "embedding"}; + + static bool isChatModel(llm_model.Model model) { + return !nonChatModelKeywords.any((keyword) => model.name.contains(keyword)); + } + + static final Map providerMap = { + "openai": LLMProvider.openai, + "claude": LLMProvider.claude, + "claude-code": LLMProvider.claudeCode, + "deepseek": LLMProvider.deepseek, + "ollama": LLMProvider.ollama, + "gemini": LLMProvider.gemini, + "foundry": LLMProvider.foundry, + "copilot": LLMProvider.copilot, + }; + + static String _maskApiKey(String apiKey) { + if (apiKey.isEmpty) return 'empty'; + if (apiKey.length <= 8) return '***'; + return '${apiKey.substring(0, 4)}...${apiKey.substring(apiKey.length - 4)}'; + } + + static void _logApiKeyUsage(String provider, String model, String apiKey) { + final maskedKey = _maskApiKey(apiKey); + Logger.root.info('Using API key for provider: $provider, model: $model, key: $maskedKey'); + } + + static BaseLLMClient createFromModel(llm_model.Model currentModel) { + try { + final setting = ProviderManager.settingsProvider.apiSettings.firstWhere((element) => element.providerId == currentModel.providerId); + + // Check if the provider is enabled (null means enabled, only false means disabled) + final isEnabled = setting.enable ?? true; + if (!isEnabled) { + throw Exception('Provider ${currentModel.providerId} is disabled'); + } + + // Set apiKey and baseUrl + final apiKey = setting.apiKey; + final baseUrl = setting.apiEndpoint; + + _logApiKeyUsage(currentModel.providerId, currentModel.name, apiKey); + + var provider = LLMFactoryHelper.providerMap[currentModel.providerId]; + + provider ??= LLMProvider.values.byName(currentModel.apiStyle); + + // Create LLM client + return LLMFactory.create(provider, apiKey: apiKey, baseUrl: baseUrl); + } catch (e) { + // If no matching provider is found, use default OpenAI + Logger.root.warning('No matching provider found: ${currentModel.providerId}, using default OpenAI configuration'); + + var openAISetting = ProviderManager.settingsProvider.apiSettings.firstWhere( + (element) => element.providerId == "openai", + orElse: () => LLMProviderSetting(apiKey: '', apiEndpoint: '', providerId: 'openai'), + ); + + return OpenAIClient(apiKey: openAISetting.apiKey, baseUrl: openAISetting.apiEndpoint); + } + } +} diff --git a/lib/llm/model.dart b/lib/llm/model.dart new file mode 100644 index 0000000..619836f --- /dev/null +++ b/lib/llm/model.dart @@ -0,0 +1,477 @@ +import 'dart:convert'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:uuid/uuid.dart'; +import 'package:chatmcp/dao/chat_message.dart'; + +// Message role enumeration +enum MessageRole { + system, + user, + assistant, + function, + tool, + error, + loading; + + String get value => name; +} + +class File { + final String name; + final int size; + final String? path; + final String fileType; + final String fileContent; + + File({required this.name, required this.path, required this.size, required this.fileType, this.fileContent = ''}); + + Map toJson() { + return {'name': name, 'path': path, 'size': size, 'fileType': fileType, 'fileContent': fileContent}; + } + + factory File.fromJson(Map json) { + return File(name: json['name'], path: json['path'], size: json['size'], fileType: json['fileType'], fileContent: json['fileContent']); + } +} + +// Message structure +class ChatMessage { + final String messageId; + final String parentMessageId; + final MessageRole role; + final String? content; + final String? name; + final String? mcpServerName; + final String? toolCallId; + final TokenUsage? tokenUsage; + final List>? toolCalls; + final List? files; + List? brotherMessageIds; + List? childMessageIds; + + ChatMessage({ + required this.role, + this.content, + this.name, + this.mcpServerName, + this.toolCallId, + this.tokenUsage, + this.toolCalls, + this.files, + this.brotherMessageIds, + this.childMessageIds, + String? messageId, + String? parentMessageId, + }) : messageId = messageId ?? Uuid().v4(), + parentMessageId = parentMessageId ?? ''; + + Map toJson() { + final json = {'role': role.value, if (content != null) 'content': content}; + + if (role == MessageRole.tool && name != null && toolCallId != null) { + json['name'] = name!; + json['tool_call_id'] = toolCallId!; + } + + if (toolCalls != null) { + json['tool_calls'] = toolCalls; + } + + if (tokenUsage != null) { + json['tokenUsage'] = tokenUsage!.toJson(); + } + + if (mcpServerName != null) { + json['mcpServerName'] = mcpServerName!; + } + + if (files != null) { + json['files'] = files?.map((file) => file.toJson()).toList(); + } + + json['messageId'] = messageId; + json['parentMessageId'] = parentMessageId; + if (brotherMessageIds != null) { + json['brotherMessageIds'] = brotherMessageIds; + } + + if (childMessageIds != null) { + json['childMessageIds'] = childMessageIds; + } + + return json; + } + + factory ChatMessage.fromDb(DbChatMessage dbChatMessage) { + return ChatMessage.fromJson(dbChatMessage.messageId, dbChatMessage.parentMessageId, jsonDecode(dbChatMessage.body)); + } + + factory ChatMessage.fromJson(String messageId, String parentMessageId, Map json) { + // Handle type conversion for toolCalls + List>? toolCalls; + if (json['tool_calls'] != null) { + toolCalls = (json['tool_calls'] as List).map((item) => Map.from(item)).toList(); + } + + List? files; + if (json['files'] != null) { + files = (json['files'] as List).map((item) => File.fromJson(Map.from(item))).toList(); + } + + return ChatMessage( + role: MessageRole.values.firstWhere((e) => e.value == json['role']), + content: json['content'], + name: json['name'], + mcpServerName: json['mcpServerName'], + toolCallId: json['tool_call_id'], + tokenUsage: json['tokenUsage'] != null ? TokenUsage.fromJson(Map.from(json['tokenUsage'])) : null, + toolCalls: toolCalls, + files: files, + messageId: messageId, + parentMessageId: parentMessageId, + ); + } + + @override + String toString() { + return jsonEncode(toJson()); + } + + DbChatMessage toDb(int chatId) { + return DbChatMessage(chatId: chatId, messageId: messageId, parentMessageId: parentMessageId, body: toString()); + } + + ChatMessage copyWith({String? messageId, String? parentMessageId, String? content, MessageRole? role, TokenUsage? tokenUsage}) { + return ChatMessage( + messageId: messageId ?? this.messageId, + parentMessageId: parentMessageId ?? this.parentMessageId, + role: role ?? this.role, + content: content ?? this.content, + tokenUsage: tokenUsage ?? this.tokenUsage, + name: name, + mcpServerName: mcpServerName, + toolCallId: toolCallId, + toolCalls: toolCalls, + files: files, + ); + } +} + +// Add tool call data structure +class ToolCall { + final String id; + final String type; + final FunctionCall function; + + ToolCall({required this.id, required this.type, required this.function}); + + Map toJson() => {'id': id, 'type': type, 'function': function.toJson()}; +} + +class FunctionCall { + final String name; + final String arguments; + + FunctionCall({required this.name, required this.arguments}); + + Map toJson() => {'name': name, 'arguments': arguments}; + + // Parse arguments to Map + Map get parsedArguments => json.decode(arguments) as Map; +} + +// LLM response data structure +class LLMResponse { + final String? content; + final List? toolCalls; + final bool needToolCall; + final TokenUsage? tokenUsage; // Token usage information + + LLMResponse({ + this.content, + this.toolCalls, + this.tokenUsage, + }) : needToolCall = toolCalls != null && toolCalls.isNotEmpty; + + Map toJson() => { + 'content': content, + 'tool_calls': toolCalls?.map((t) => t.toJson()).toList(), + 'need_tool_call': needToolCall, + if (tokenUsage != null) 'token_usage': tokenUsage!.toJson(), + }; + + // Factory method for creating LLMResponse from JSON + factory LLMResponse.fromJson(Map json) { + return LLMResponse( + content: json['content'], + toolCalls: json['tool_calls'] != null + ? (json['tool_calls'] as List) + .map((t) => ToolCall( + id: t['id'], + type: t['type'], + function: FunctionCall( + name: t['function']['name'], + arguments: t['function']['arguments'] + ) + )) + .toList() + : null, + tokenUsage: json['token_usage'] != null + ? TokenUsage.fromJson(json['token_usage']) + : null, + ); + } + + // Create a copy of LLMResponse with optional parameter updates + LLMResponse copyWith({ + String? content, + List? toolCalls, + TokenUsage? tokenUsage, + }) { + return LLMResponse( + content: content ?? this.content, + toolCalls: toolCalls ?? this.toolCalls, + tokenUsage: tokenUsage ?? this.tokenUsage, + ); + } +} + +class TokenUsage { + final int inputTokens; + final int outputTokens; + final int totalTokens; + final int? thoughtTokens; // Optional for models with reasoning tokens + final DateTime timestamp; // When the tokens were counted + final String? modelName; // Which model was used + final double? cost; // Estimated cost based on token usage + final String? requestId; // Unique identifier for the request + + TokenUsage({ + required this.inputTokens, + required this.outputTokens, + required this.totalTokens, + this.thoughtTokens, + DateTime? timestamp, + this.modelName, + this.cost, + this.requestId, + }) : timestamp = timestamp ?? DateTime.now(); + //cost = cost ?? (modelName != null ? _calculateInitialCost(inputTokens, outputTokens, modelName) : null), // for later use + + /* // Calculate initial cost based on model pricing + static double? _calculateInitialCost(int inputTokens, int outputTokens, String modelName) { + final pricing = _getModelPricing(modelName); + if (pricing == null) return null; + + final inputCost = (inputTokens / 1000000) * pricing['input']!; + final outputCost = (outputTokens / 1000000) * pricing['output']!; + return inputCost + outputCost; + }*/ + + Map toJson() { + return { + 'inputTokens': inputTokens, + 'outputTokens': outputTokens, + 'totalTokens': totalTokens, + if (thoughtTokens != null) 'thoughtTokens': thoughtTokens, + 'timestamp': timestamp.toIso8601String(), + if (modelName != null) 'modelName': modelName, + if (cost != null) 'cost': cost, + if (requestId != null) 'requestId': requestId, + }; + } + + factory TokenUsage.fromJson(Map json) { + return TokenUsage( + inputTokens: json['inputTokens'] ?? 0, + outputTokens: json['outputTokens'] ?? 0, + totalTokens: json['totalTokens'] ?? 0, + thoughtTokens: json['thoughtTokens'], + timestamp: json['timestamp'] != null + ? DateTime.parse(json['timestamp']) + : DateTime.now(), + modelName: json['modelName'], + cost: json['cost']?.toDouble(), + requestId: json['requestId'], + ); + } + + factory TokenUsage.fromGemini(Map usage, {String? modelName, double? cost, String? requestId}) { + return TokenUsage( + inputTokens: usage['promptTokenCount'] ?? 0, + outputTokens: usage['candidatesTokenCount'] ?? 0, + totalTokens: usage['totalTokenCount'] ?? 0, + thoughtTokens: usage['thoughtsTokenCount'], + modelName: modelName, + cost: cost, + requestId: requestId, + ); + } + + factory TokenUsage.fromOpenAI(Map usage, {int? timestamp, String? modelName, double? cost, String? requestId}) { + final completionTokensDetails = usage['completion_tokens_details'] as Map?; + + return TokenUsage( + inputTokens: usage['prompt_tokens'] ?? 0, + outputTokens: usage['completion_tokens'] ?? 0, + totalTokens: usage['total_tokens'] ?? 0, + thoughtTokens: completionTokensDetails?['reasoning_tokens'], + timestamp: timestamp != null ? DateTime.fromMillisecondsSinceEpoch(timestamp) : DateTime.now(), + modelName: modelName, + cost: cost, + requestId: requestId, + ); + } + + // Calculate estimated cost based on model pricing + double calculateCost(String modelName) { + final pricing = _getModelPricing(modelName); + if (pricing == null) return 0.0; + + final inputCost = (inputTokens / 1000000) * pricing['input']!; + final outputCost = (outputTokens / 1000000) * pricing['output']!; + return inputCost + outputCost; + } + + // Add tokens from another counter (for conversation totals) + TokenUsage operator +(TokenUsage other) { + return TokenUsage( + inputTokens: inputTokens + other.inputTokens, + outputTokens: outputTokens + other.outputTokens, + totalTokens: totalTokens + other.totalTokens, + thoughtTokens: (thoughtTokens != null || other.thoughtTokens != null) + ? (thoughtTokens ?? 0) + (other.thoughtTokens ?? 0) + : null, + timestamp: timestamp.isAfter(other.timestamp) ? timestamp : other.timestamp, + modelName: modelName ?? other.modelName, + cost: (cost ?? 0.0) + (other.cost ?? 0.0), + ); + } + + // Check if token usage is within limits + bool isWithinLimit(int maxTokens) => totalTokens <= maxTokens; + + // Get efficiency ratio (output/input) + double get efficiency => inputTokens > 0 ? outputTokens / inputTokens : 0.0; + + // Format for display in UI + String get displayString => '$inputTokens→$outputTokens (${totalTokens})'; + + // Copy with additional information + TokenUsage copyWith({ + int? inputTokens, + int? outputTokens, + int? totalTokens, + int? thoughtTokens, + DateTime? timestamp, + String? modelName, + double? cost, + String? requestId, + }) { + return TokenUsage( + inputTokens: inputTokens ?? this.inputTokens, + outputTokens: outputTokens ?? this.outputTokens, + totalTokens: totalTokens ?? this.totalTokens, + thoughtTokens: thoughtTokens ?? this.thoughtTokens, + timestamp: timestamp ?? this.timestamp, + modelName: modelName ?? this.modelName, + cost: cost ?? this.cost, + requestId: requestId ?? this.requestId, + ); + } + + @override + String toString() => jsonEncode(toJson()); + + // Private method to get model pricing (per million tokens) + static Map? _getModelPricing(String modelName) { + // Simplified pricing table - extend as needed + const pricing = { + 'gpt-4': {'input': 30.0, 'output': 60.0}, + 'gpt-4-turbo': {'input': 10.0, 'output': 30.0}, + 'gpt-3.5-turbo': {'input': 0.5, 'output': 1.5}, + 'claude-3-opus': {'input': 15.0, 'output': 75.0}, + 'claude-3-sonnet': {'input': 3.0, 'output': 15.0}, + 'gemini-pro': {'input': 0.5, 'output': 1.5}, + "gemini-2.5-flash": {'input': 0.5, 'output': 1.5} + }; + + return pricing[modelName.toLowerCase()]; + } + + String toMarkdown() { + final buffer = StringBuffer(); + buffer.writeln('**Input Tokens:** $inputTokens'); + buffer.writeln('**Output Tokens:** $outputTokens'); + buffer.writeln('**Total Tokens:** $totalTokens'); + if (thoughtTokens != null) { + buffer.writeln('**Thought Tokens:** $thoughtTokens'); + } + buffer.writeln('**Timestamp:** ${timestamp.toIso8601String()}'); + if (modelName != null) { + buffer.writeln('**Model Name:** $modelName'); + } + if (cost != null) { + buffer.writeln('**Estimated Cost:** \$$cost'); + } + if (requestId != null) { + buffer.writeln('**Request ID:** $requestId'); + } + return buffer.toString(); + } +} + +class Model { + final String name; + final String label; + final String providerId; + final String apiStyle; + final String icon; + final String providerName; + final int priority; + + Model({ + required this.name, + required this.label, + required this.providerId, + required this.icon, + required this.providerName, + required this.apiStyle, + this.priority = 0, + }); + + factory Model.fromJson(Map json) { + return Model( + name: json['name'], + label: json['label'], + providerId: json['provider'], + icon: json['icon'], + providerName: json['providerName'], + apiStyle: json['apiStyle'], + priority: json['priority'] ?? 0, + ); + } + + Map toJson() => { + 'name': name, + 'label': label, + 'provider': providerId, + 'icon': icon, + 'providerName': providerName, + 'apiStyle': apiStyle, + 'priority': priority, + }; + + @override + String toString() => jsonEncode(toJson()); +} + +class CompletionRequest { + final String model; + final List messages; + final List>? tools; + final bool stream; + ChatSetting? modelSetting; + + CompletionRequest({required this.model, required this.messages, this.tools, this.stream = false, this.modelSetting}); +} diff --git a/lib/llm/ollama_client.dart b/lib/llm/ollama_client.dart new file mode 100644 index 0000000..6008f3f --- /dev/null +++ b/lib/llm/ollama_client.dart @@ -0,0 +1,155 @@ +import 'package:http/http.dart' as http; +import 'base_llm_client.dart'; +import 'dart:convert'; +import 'model.dart'; +import 'package:logging/logging.dart'; + +class OllamaClient extends BaseLLMClient { + final String baseUrl; + final Map _headers; + + OllamaClient({String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'http://localhost:11434' : baseUrl, + _headers = {'Content-Type': 'application/json'}; + + @override + Future> models() async { + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.get(Uri.parse("$baseUrl/api/tags"), headers: _headers); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + final modelsList = data['models'] as List; + return modelsList.map((model) => (model['name'] as String)).toList(); + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + return []; + } + } + + @override + Future chatCompletion(CompletionRequest request) async { + final messages = request.messages.map((m) { + final role = m.role == MessageRole.user ? 'user' : 'assistant'; + return {'role': role, 'content': m.content}; + }).toList(); + + final body = {'model': request.model, 'messages': messages, 'stream': false}; + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = request.tools!; + } + + final bodyStr = jsonEncode(body); + + try { + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.post(Uri.parse("$baseUrl/v1/chat/completions"), headers: _headers, body: bodyStr); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('Ollama request: $bodyStr'); + Logger.root.fine('Ollama response: $responseBody'); + + final jsonData = jsonDecode(responseBody); + + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final message = jsonData['choices'][0]['message']; + + // Parse tool calls + final toolCalls = message['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'] ?? '', + type: 'function', + function: FunctionCall(name: t['function']['name'], arguments: jsonEncode(t['function']['arguments'])), + ), + ) + ?.toList(); + + return LLMResponse(content: message['content'] ?? '', toolCalls: toolCalls); + } catch (e) { + throw await handleError(e, 'Ollama', '$baseUrl/v1/chat/completions', bodyStr); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final messages = request.messages.map((m) { + final role = m.role == MessageRole.user ? 'user' : 'assistant'; + return {'role': role, 'content': m.content}; + }).toList(); + + final body = {'model': request.model, 'messages': messages, 'stream': true}; + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = request.tools!; + body['tool_choice'] = 'auto'; + } + + Logger.root.fine('Ollama request: ${jsonEncode(body)}'); + + try { + final request = http.Request('POST', Uri.parse("$baseUrl/v1/chat/completions")); + request.headers.addAll(_headers); + request.body = jsonEncode(body); + + final httpClient = BaseLLMClient.createHttpClient(); + final response = await httpClient.send(request); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('Ollama response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + await for (final line in stream) { + if (!line.startsWith('data: ')) continue; + final jsonStr = line.substring(6).trim(); + if (jsonStr.isEmpty || jsonStr == '[DONE]') continue; + + try { + final json = jsonDecode(jsonStr); + + // 检查 choices 数组是否为空 + if (json['choices'] == null || json['choices'].isEmpty) { + continue; + } + + final delta = json['choices'][0]['delta']; + if (delta == null) continue; + + // Parse tool calls + final toolCalls = delta['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'] ?? '', + type: 'function', + function: FunctionCall(name: t['function']?['name'] ?? '', arguments: jsonEncode(t['function']?['arguments'] ?? {})), + ), + ) + ?.toList(); + + // Only yield when content is not empty or there are tool calls + if (delta['content'] != null || toolCalls != null) { + yield LLMResponse(content: delta['content'], toolCalls: toolCalls); + } + } catch (e) { + Logger.root.severe('Failed to parse stream chunk: $jsonStr $e'); + continue; + } + } + } catch (e) { + throw await handleError(e, 'Ollama', "$baseUrl/v1/chat/completions", jsonEncode(body)); + } + } +} diff --git a/lib/llm/openai_client.dart b/lib/llm/openai_client.dart new file mode 100644 index 0000000..b6f79f1 --- /dev/null +++ b/lib/llm/openai_client.dart @@ -0,0 +1,221 @@ +import 'package:chatmcp/utils/toast.dart'; +import 'package:http/http.dart' as http; +import 'base_llm_client.dart'; +import 'dart:convert'; +import 'model.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/utils/file_content.dart'; + +class OpenAIClient extends BaseLLMClient { + final String apiKey; + final String baseUrl; + final Map _headers; + + OpenAIClient({required this.apiKey, String? baseUrl}) + : baseUrl = (baseUrl == null || baseUrl.isEmpty) ? 'https://api.openai.com/v1' : baseUrl, + _headers = {'Content-Type': 'application/json; charset=utf-8', 'Authorization': 'Bearer $apiKey'}; + + @override + Future chatCompletion(CompletionRequest request) async { + final httpClient = BaseLLMClient.createHttpClient(); + + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages)}; + + addModelSettingsToBody(body, request.modelSetting); + + if (request.tools != null && request.tools!.isNotEmpty) { + body['tools'] = request.tools!; + body['tool_choice'] = 'auto'; + } + + final bodyStr = jsonEncode(body); + Logger.root.fine('OpenAI request: $bodyStr'); + + final endpoint = getEndpoint(baseUrl, "/chat/completions"); + + try { + final response = await httpClient.post(Uri.parse(endpoint), headers: _headers, body: bodyStr); + + final responseBody = utf8.decode(response.bodyBytes); + Logger.root.fine('OpenAI response: $responseBody'); + + if (response.statusCode >= 400) { + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final jsonData = jsonDecode(responseBody); + + final message = jsonData['choices'][0]['message']; + + // Parse tool calls + final toolCalls = message['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'], + type: t['type'], + function: FunctionCall(name: t['function']['name'], arguments: t['function']['arguments']), + ), + ) + ?.toList(); + TokenUsage? tokenUsage; + if (jsonData['usage'] != null) { + tokenUsage = TokenUsage.fromOpenAI(jsonData['usage'], modelName: jsonData['model']); + } + return LLMResponse(content: message['content'], toolCalls: toolCalls, tokenUsage: tokenUsage); + } catch (e) { + throw await handleError(e, 'OpenAI', endpoint, bodyStr); + } finally { + httpClient.close(); + } + } + + @override + Stream chatStreamCompletion(CompletionRequest request) async* { + final httpClient = BaseLLMClient.createHttpClient(); + + final body = {'model': request.model, 'messages': chatMessageToOpenAIMessage(request.messages), 'stream': true}; + + addModelSettingsToBody(body, request.modelSetting); + + Logger.root.fine("debug log:openai stream body: ${jsonEncode(body)}"); + + final endpoint = getEndpoint(baseUrl, "/chat/completions"); + + try { + final httpRequest = http.Request('POST', Uri.parse(endpoint)); + httpRequest.headers.addAll(_headers); + httpRequest.body = jsonEncode(body); + + final response = await httpClient.send(httpRequest); + + if (response.statusCode >= 400) { + final responseBody = await response.stream.bytesToString(); + Logger.root.fine('OpenAI response: $responseBody'); + + throw Exception('HTTP ${response.statusCode}: $responseBody'); + } + + final stream = response.stream.transform(utf8.decoder).transform(const LineSplitter()); + + await for (final line in stream) { + if (!line.startsWith('data: ')) continue; + final data = line.substring(6); + if (data.isEmpty || data == '[DONE]') continue; + + try { + final json = jsonDecode(data); + + if (json['choices'] == null || json['choices'].isEmpty) { + continue; + } + + final delta = json['choices'][0]['delta']; + if (delta == null) continue; + + final toolCalls = delta['tool_calls'] + ?.map( + (t) => ToolCall( + id: t['id'] ?? '', + type: t['type'] ?? '', + function: FunctionCall(name: t['function']?['name'] ?? '', arguments: t['function']?['arguments'] ?? '{}'), + ), + ) + ?.toList(); + + if (delta['content'] != null || toolCalls != null) { + yield LLMResponse(content: delta['content'], toolCalls: toolCalls); + } + + if (json['usage'] != null) { + yield LLMResponse(tokenUsage: TokenUsage.fromOpenAI(json['usage'], modelName: json['model'])); + } + } catch (e) { + Logger.root.severe('Failed to parse event data: $data $e'); + continue; + } + } + } catch (e) { + throw await handleError(e, 'OpenAI', endpoint, jsonEncode(body)); + } finally { + httpClient.close(); + } + } + + @override + Future> models() async { + if (apiKey.isEmpty) { + ToastUtils.error('API key not set, skipping model list fetch'); + return []; + } + + final httpClient = BaseLLMClient.createHttpClient(); + + try { + final response = await httpClient.get(Uri.parse(getEndpoint(baseUrl, "/models")), headers: _headers); + + if (response.statusCode != 200) { + throw Exception('HTTP ${response.statusCode}: ${response.body}'); + } + + final data = jsonDecode(response.body); + final models = (data['data'] as List).map((m) => m['id'].toString()).toList(); + + return models; + } catch (e, trace) { + Logger.root.severe('Failed to get model list: $e, trace: $trace'); + throw LLMException(name: 'OpenAI', endpoint: getEndpoint(baseUrl, "/models"), requestBody: '', originalError: e); + } finally { + httpClient.close(); + } + } +} + +List> chatMessageToOpenAIMessage(List messages) { + return messages.map((message) { + final json = {'role': message.role.value}; + + // If there is both text content and files, use array format + if (message.content != null || message.files != null) { + final List> contentParts = []; + + // Add file content + if (message.files != null) { + for (final file in message.files!) { + if (isImageFile(file.fileType)) { + contentParts.add({ + 'type': 'image_url', + 'image_url': {"url": "data:${file.fileType};base64,${file.fileContent}"}, + }); + } + if (isTextFile(file.fileType)) { + contentParts.add({'type': 'text', 'text': file.fileContent}); + } + } + } + + // Add text content + if (message.content != null) { + contentParts.add({'type': 'text', 'text': message.content}); + } + + // If there is only one text content and no files, use simple string format + if (contentParts.length == 1 && message.files == null) { + json['content'] = message.content; + } else { + json['content'] = contentParts; + } + } + + // Add tool call related fields + if (message.role == MessageRole.tool && message.name != null && message.toolCallId != null) { + json['name'] = message.name!; + json['tool_call_id'] = message.toolCallId!; + } + + if (message.toolCalls != null) { + json['tool_calls'] = message.toolCalls; + } + + return json; + }).toList(); +} diff --git a/lib/llm/prompt.dart b/lib/llm/prompt.dart new file mode 100644 index 0000000..6bb4c80 --- /dev/null +++ b/lib/llm/prompt.dart @@ -0,0 +1,99 @@ +import 'dart:convert'; + +import 'package:chatmcp/provider/provider_manager.dart'; + +class SystemPromptGenerator { + /// Base prompt template without tool instructions + final String baseTemplate = ''' + +You will select appropriate tools and call them to solve user queries + +**CRITICAL CONSTRAINT: You MUST call only ONE tool per response. Never call multiple tools simultaneously.** +'''; + + /// Tool-related template parts + final String toolDefinitionsTemplate = ''' + +**Tool Definitions:** +Here are the functions available, described in JSONSchema format: + +{{ TOOL DEFINITIONS IN JSON SCHEMA }} +'''; + + final String toolUsageTemplate = ''' + + +TOOL USE + +You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use. + +# Tool Use Formatting + +Tool use is formatted using XML-style tags. The tool name is enclosed in opening and closing tags, and parameters must be provided in JSON format. Here's the structure: + + +{ + "parameter1_name": "value1", + "parameter2_name": "value2" +} + + +For example: + + +{ + "path": "src/main.js" +} + + +Always adhere to this format for the tool use to ensure proper parsing and execution. +'''; + + /// Default user system prompt + final String defaultUserSystemPrompt = 'You are an intelligent assistant capable of using tools to solve user queries effectively.'; + + /// Default tool configuration + final String defaultToolConfig = 'No additional configuration is required.'; + + /// Generate system prompt + /// + /// [tools] - JSON tool definitions + /// [userSystemPrompt] - Optional user system prompt + /// [toolConfig] - Optional tool configuration information + String generatePrompt({required List> tools}) { + // Start with base template + + var userPrompt = ProviderManager.settingsProvider.generalSetting.systemPrompt; + + var language = ProviderManager.settingsProvider.generalSetting.locale; + + var prompt = "$userPrompt\n$baseTemplate"; + if (language.isNotEmpty) { + prompt += "\n\nLanguage: $language"; + } + + // Only add tool-related sections if tools are available + if (tools.isNotEmpty) { + // Convert tools JSON to formatted string + final toolsJsonSchema = const JsonEncoder.withIndent(' ').convert(tools); + + // Add tool definitions section + prompt += toolDefinitionsTemplate.replaceAll('{{ TOOL DEFINITIONS IN JSON SCHEMA }}', toolsJsonSchema); + + // Add tool usage instructions + prompt += toolUsageTemplate; + } + + return prompt; + } + + /// Generate system prompt + /// + /// [tools] - List of available tools + /// Returns a concise, action-oriented system prompt + String generateToolPrompt(List> tools) { + final promptGenerator = SystemPromptGenerator(); + var systemPrompt = promptGenerator.generatePrompt(tools: tools); + return systemPrompt; + } +} diff --git a/lib/llm/utils.dart b/lib/llm/utils.dart new file mode 100644 index 0000000..f6edd24 --- /dev/null +++ b/lib/llm/utils.dart @@ -0,0 +1,23 @@ +List> convertToOpenAITools(Map>> toolsByClient) { + List> allTools = []; + + // Merge tool lists from all clients + for (var tools in toolsByClient.values) { + final openAITools = tools + .map( + (tool) => { + 'type': 'function', + 'function': { + 'name': tool['name'].toString(), + 'description': tool['description'].toString(), + 'parameters': Map.from(tool['inputSchema']), + }, + }, + ) + .toList(); + + allTools.addAll(openAITools); + } + + return allTools; +} diff --git a/lib/logger.dart b/lib/logger.dart new file mode 100644 index 0000000..a34e390 --- /dev/null +++ b/lib/logger.dart @@ -0,0 +1,89 @@ +import 'package:logging/logging.dart'; +import 'package:flutter/widgets.dart'; +import 'file_logger.dart'; + +// Define color codes +const ansiReset = '\x1B[0m'; +const ansiRed = '\x1B[31m'; +const ansiGreen = '\x1B[32m'; +const ansiYellow = '\x1B[33m'; +const ansiBlue = '\x1B[34m'; +const ansiMagenta = '\x1B[35m'; +const ansiGray = '\x1B[37m'; + +// Get color for log level +String getLevelColor(Level level) { + switch (level.name) { + case 'SEVERE': + return ansiRed; + case 'WARNING': + return ansiYellow; + case 'INFO': + return ansiBlue; + case 'CONFIG': + return ansiMagenta; + case 'FINE': + case 'FINER': + case 'FINEST': + return ansiGreen; + default: + return ansiGray; + } +} + +void initializeLogger() async { + // Initialize file logger + await FileLogger.initLogFile(); + + Logger.root.level = Level.ALL; + Logger.root.onRecord.listen((record) { + // Get caller location info + String? caller; + + // Use StackTrace.current to ensure stack trace is always available + final stackTrace = record.stackTrace ?? StackTrace.current; + final frames = stackTrace.toString().split('\n'); + + if (frames.length > 1) { + // Parse the first matching stack frame + final callerFrame = frames.firstWhere( + (frame) => + !frame.contains('log.dart') && + !frame.contains('logger.dart') && + !frame.contains('logger_mixin.dart') && + !frame.contains('main.dart') && + !frame.contains('dart:async') && + !frame.contains('dart:io') && + frame.contains('package:chatmcp/'), + orElse: () => frames.firstWhere((frame) => frame.contains('package:chatmcp/'), orElse: () => frames[0]), + ); + + // Extract filename and line number + final match = RegExp(r'\((.+?):(\d+)(?::\d+)\)').firstMatch(callerFrame); + if (match != null) { + final file = match.group(1); + final line = match.group(2); + caller = '$file:$line'; + } else { + final flutterMatch = RegExp(r'#\d+\s+.*\s+\((.+?):(\d+)(?::\d+)?\)').firstMatch(callerFrame); + if (flutterMatch != null) { + final file = flutterMatch.group(1); + final line = flutterMatch.group(2); + caller = '$file:$line'; + } + } + } + + final levelColor = getLevelColor(record.level); + final logMessage = '${record.level.name}: ${caller ?? 'unknown'}: ${record.message}'; + + // In development mode, print colored logs to console + assert(() { + debugPrint('$levelColor$logMessage$ansiReset'); + return true; + }()); + + // In release mode, write to file + FileLogger.writeToFile(logMessage); + }); +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..9ea5cdf --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,116 @@ +import 'package:chatmcp/dao/init_db.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:window_manager/window_manager.dart' as wm; +import './logger.dart'; +import './page/layout/layout.dart'; +import './provider/provider_manager.dart'; +import 'package:logging/logging.dart'; +import 'utils/platform.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'utils/init.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:bot_toast/bot_toast.dart'; + +final GlobalKey _scaffoldMessengerKey = GlobalKey(); + +// Add global navigator key +final GlobalKey navigatorKey = GlobalKey(); + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + initializeLogger(); + + await initNonWeb(); + + if (kIsDesktop) { + await wm.windowManager.ensureInitialized(); + + final wm.WindowOptions windowOptions = wm.WindowOptions( + size: Size(1200, 800), + minimumSize: Size(400, 600), + center: true, + backgroundColor: Colors.transparent, + skipTaskbar: false, + titleBarStyle: wm.TitleBarStyle.hidden, + windowButtonVisibility: true, + alwaysOnTop: false, + fullScreen: false, + ); + + await wm.windowManager.waitUntilReadyToShow(windowOptions, () async { + try { + await wm.windowManager.show(); + await wm.windowManager.focus(); + // Add a small delay to ensure window is properly initialized + await Future.delayed(const Duration(milliseconds: 100)); + } catch (e) { + Logger.root.warning('Window initialization error: $e'); + } + }); + } + + try { + await Future.wait([ProviderManager.init(), initDb()]); + + var app = MyApp(); + + runApp(MultiProvider(providers: [...ProviderManager.providers], child: app)); + } catch (e, stackTrace) { + Logger.root.severe('Main error: $e\nStack trace:\n$stackTrace'); + } +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + // Get default font for current platform + String getPlatformFontFamily() { + if (kIsWindows) { + return 'Microsoft YaHei'; // Microsoft YaHei font + } + return ''; // Use Flutter default font for other platforms + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, settings, child) { + return MaterialApp( + debugShowCheckedModeBanner: false, + scaffoldMessengerKey: _scaffoldMessengerKey, + navigatorKey: navigatorKey, + title: 'ChatMcp', + theme: ThemeData(useMaterial3: true, brightness: Brightness.light, fontFamily: getPlatformFontFamily()), + darkTheme: ThemeData(useMaterial3: true, brightness: Brightness.dark, fontFamily: getPlatformFontFamily()), + themeMode: _getThemeMode(settings.generalSetting.theme), + home: LayoutPage(), + locale: Locale(settings.generalSetting.locale), + builder: BotToastInit(), //1.调用BotToastInit + navigatorObservers: [BotToastNavigatorObserver()], //2.注册路由观察者 + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('en'), Locale('zh'), Locale('tr'), Locale('de')], + ); + }, + ); + } + + ThemeMode _getThemeMode(String theme) { + switch (theme) { + case 'light': + return ThemeMode.light; + case 'dark': + return ThemeMode.dark; + case 'system': + default: + return ThemeMode.system; + } + } +} diff --git a/lib/mcp/client/mcp_client_interface.dart b/lib/mcp/client/mcp_client_interface.dart new file mode 100644 index 0000000..0e65fa4 --- /dev/null +++ b/lib/mcp/client/mcp_client_interface.dart @@ -0,0 +1,14 @@ +import '../models/json_rpc_message.dart'; +import '../models/server.dart'; + +abstract class McpClient { + ServerConfig get serverConfig; + + Future initialize(); + Future dispose(); + Future sendMessage(JSONRPCMessage message); + Future sendInitialize(); + Future sendPing(); + Future sendToolList(); + Future sendToolCall({required String name, required Map arguments, String? id}); +} diff --git a/lib/mcp/inmemory/client.dart b/lib/mcp/inmemory/client.dart new file mode 100644 index 0000000..cf2f022 --- /dev/null +++ b/lib/mcp/inmemory/client.dart @@ -0,0 +1,48 @@ +import 'package:chatmcp/mcp/models/json_rpc_message.dart'; +import 'package:chatmcp/mcp/models/server.dart'; +import 'package:logging/logging.dart'; + +import '../client/mcp_client_interface.dart'; +import 'memory_server.dart'; + +class InMemoryClient implements McpClient { + final MemoryServer server; + + InMemoryClient({required this.server}); + + @override + Future initialize() async {} + + @override + Future dispose() async {} + + @override + Future sendInitialize() async { + Logger.root.fine('InMemoryClient sendInitialize'); + return sendMessage(JSONRPCMessage(id: 'init-1', method: 'initialize')); + } + + @override + Future sendMessage(JSONRPCMessage message) async { + final result = server.onmessage(message); + return result; + } + + @override + Future sendPing() async { + return sendMessage(JSONRPCMessage(id: 'ping-1', method: 'ping')); + } + + @override + Future sendToolCall({required String name, required Map arguments, String? id}) async { + return sendMessage(JSONRPCMessage(id: id, method: 'tools/call', params: {'name': name, 'arguments': arguments})); + } + + @override + Future sendToolList() async { + return sendMessage(JSONRPCMessage(id: 'tool-list-1', method: 'tools/list')); + } + + @override + ServerConfig get serverConfig => throw UnimplementedError(); +} diff --git a/lib/mcp/inmemory/memory_server.dart b/lib/mcp/inmemory/memory_server.dart new file mode 100644 index 0000000..47cfee5 --- /dev/null +++ b/lib/mcp/inmemory/memory_server.dart @@ -0,0 +1,95 @@ +import 'package:chatmcp/mcp/models/json_rpc_message.dart'; +import 'package:logging/logging.dart'; + +enum ToolInputType { string, integer, boolean, object } + +class Property { + String name; + ToolInputType type; + + Property({required this.name, required this.type}); + + Map toJson() { + return {'name': name, 'type': type.name}; + } +} + +class ToolInput { + String type; + String description; + List properties; + List required; + + ToolInput({required this.type, required this.description, required this.properties, required this.required}); + + Map toJson() { + return {'type': type, 'description': description, 'properties': properties.map((property) => property.toJson()).toList()}; + } +} + +class Tool { + String name; + String description; + ToolInput inputSchema; + + Tool({required this.name, required this.description, required this.inputSchema}); + + Map toJson() { + return {'name': name, 'description': description, 'inputSchema': inputSchema.toJson()}; + } +} + +abstract class MemoryServer { + String name; + + List tools; + + MemoryServer({required this.name, List? tools}) : tools = tools ?? []; + + JSONRPCMessage onmessage(JSONRPCMessage message) { + var result = {}; + switch (message.method) { + case 'initialize': + result = { + 'protocolVersion': '1.0', + 'serverInfo': {'name': name, 'version': '1.0.0'}, + 'capabilities': { + 'prompts': {'listChanged': true}, + 'resources': {'listChanged': true, 'subscribe': true}, + 'tools': {'listChanged': true}, + }, + }; + case 'ping': + result = {}; // 空对象 + case 'resources/list': + result = {'resources': []}; + case 'resources/read': + result = {'contents': []}; + case 'resources/subscribe': + case 'resources/unsubscribe': + result = {}; // 成功时返回空对象 + case 'prompts/list': + result = {'prompts': []}; + case 'prompts/get': + result = {'messages': []}; + case 'tools/list': + result = {'tools': tools.map((tool) => tool.toJson()).toList()}; + case 'tools/call': + Logger.root.fine('tools/call message: ${message.toJson()}'); + result = {"content": onToolCall(message)}; + case 'logging/setLevel': + result = {}; + case 'completion/complete': + result = {'completion': {}}; + default: + result = {'code': -32601, 'message': 'Method not found: ${message.method}'}; + } + return JSONRPCMessage(id: message.id, jsonrpc: '2.0', method: message.method, result: result); + } + + void addTool(Tool tool) { + tools.add(tool); + } + + Map onToolCall(JSONRPCMessage message); +} diff --git a/lib/mcp/inmemory/server.dart b/lib/mcp/inmemory/server.dart new file mode 100644 index 0000000..05198e8 --- /dev/null +++ b/lib/mcp/inmemory/server.dart @@ -0,0 +1,163 @@ +import 'package:chatmcp/mcp/models/json_rpc_message.dart'; +import 'package:flutter/material.dart'; + +// define JSON-RPC response class +class JsonRpcResponse { + final String jsonrpc; + final dynamic result; + final Map? error; + final dynamic id; + + JsonRpcResponse({required this.jsonrpc, this.result, this.error, required this.id}); + + factory JsonRpcResponse.fromJson(Map json) { + return JsonRpcResponse( + jsonrpc: json['jsonrpc'] ?? '2.0', + id: json['id'], + result: json['result'], + error: json['error'] != null ? Map.from(json['error']) : null, + ); + } + + Map toJson() { + final Map data = {'jsonrpc': jsonrpc, 'id': id}; + // according to JSON-RPC specification, result and error are mutually exclusive + if (error != null) { + data['error'] = error; + } else { + // even if result is null or empty map, it should be included (if error does not exist) + data['result'] = result; + } + return data; + } +} + +// function to handle request +JsonRpcResponse handleRequest(JSONRPCMessage request) { + dynamic result; + Map? error; + + try { + switch (request.method) { + case 'initialize': + result = { + 'protocolVersion': '1.0', + 'serverInfo': {'name': 'mock-server-dart', 'version': '1.0.0'}, + 'capabilities': { + 'prompts': {'listChanged': true}, + 'resources': {'listChanged': true, 'subscribe': true}, + 'tools': {'listChanged': true}, + }, + }; + break; + case 'ping': + result = {}; // empty object + break; + case 'resources/list': + result = { + 'resources': [ + {'name': 'test-resource', 'uri': 'test://resource'}, + ], + }; + break; + case 'resources/read': + // in actual implementation, should get URI from request.params + // final uri = request.params?['uri']; + // if (uri == null) throw ArgumentError('Missing parameter: uri'); + // ... read content according to uri ... + result = { + 'contents': [ + { + 'text': 'test content', + 'uri': 'test://resource', // use mock URI + }, + ], + }; + break; + case 'resources/subscribe': + case 'resources/unsubscribe': + // in actual implementation, should handle subscribe/unsubscribe logic + // final uri = request.params?['uri']; + // if (uri == null) throw ArgumentError('Missing parameter: uri'); + result = {}; // return empty object when successful + break; + case 'prompts/list': + result = { + 'prompts': [ + {'name': 'test-prompt'}, + ], + }; + break; + case 'prompts/get': + // in actual implementation, should get prompt name/ID from request.params + // final promptName = request.params?['name']; + result = { + 'messages': [ + { + 'role': 'assistant', + 'content': {'type': 'text', 'text': 'test message'}, + }, + ], + }; + break; + case 'tools/list': + result = { + 'tools': [ + { + 'name': 'test-tool', + 'inputSchema': { + 'type': 'object', + // 'properties': { ... } // can add schema definition + }, + // 'description': 'A test tool' // optional description + }, + ], + }; + break; + case 'tools/call': + // in actual implementation, should get tool name and input from request.params + // final toolName = request.params?['tool']; + // final input = request.params?['input']; + // if (toolName == null) throw ArgumentError('Missing parameter: tool'); + // ... execute tool call ... + result = { + 'content': [ + {'type': 'text', 'text': 'tool result'}, + ], + }; + break; + case 'logging/setLevel': + // in actual implementation, should get log level from request.params + // final level = request.params?['level']; + // if (level == null) throw ArgumentError('Missing parameter: level'); + result = {}; // return empty object when successful + break; + case 'completion/complete': + // in actual implementation, should get completion info from request.params + // final context = request.params?['context']; + result = { + 'completion': { + 'values': ['test completion'], + }, + }; + break; + default: + error = { + 'code': -32601, // Method not found + 'message': 'Method not found: ${request.method}', + }; + } + } catch (e, stackTrace) { + // catch any exception in the process and format it as JSON-RPC error + debugPrint('Error handling request: $e'); + debugPrint('Stack trace:\n$stackTrace'); + error = { + 'code': -32603, // Internal error + 'message': 'Internal server error: ${e.toString()}', + // 'data': stackTrace.toString(), // optional: include debug info + }; + result = null; // ensure result is null when error occurs + } + + return JsonRpcResponse(jsonrpc: '2.0', id: request.id, result: result, error: error); +} diff --git a/lib/mcp/inmemory_server/artifact_instructions.dart b/lib/mcp/inmemory_server/artifact_instructions.dart new file mode 100644 index 0000000..673699d --- /dev/null +++ b/lib/mcp/inmemory_server/artifact_instructions.dart @@ -0,0 +1,391 @@ +import 'package:logging/logging.dart'; + +import '../inmemory/memory_server.dart'; +import '../models/json_rpc_message.dart'; + +class ArtifactServer extends MemoryServer { + ArtifactServer() : super(name: 'artifact-instructions') { + addTool( + Tool( + name: 'get_artifact_instructions', + description: + 'Only call this function when you need instructions for a specific artifact type, and call it only once per type. ' + 'This tool provides guidance on creating and referencing artifacts, including code, documents, HTML, SVG, Mermaid diagrams, or React components. ' + 'Do not call this function repeatedly if instructions or definitions for the requested artifact type are already available in the current context. ' + 'Specify the desired artifact category through the type parameter: code, documents, html, svg, mermaid, or react. ' + 'After obtaining the instructions, use them appropriately and avoid duplicate calls for the same type.', + inputSchema: ToolInput( + type: 'object', + description: 'Get the artifact instructions', + properties: [Property(name: 'type', type: ToolInputType.string)], + required: ['type'], + ), + ), + ); + } + + @override + Map onToolCall(JSONRPCMessage message) { + String name = message.params?['name']; + Map arguments = message.params?['arguments']; + Logger.root.fine('memory_server onToolCall name: $name arguments: $arguments'); + switch (name) { + case 'get_artifact_instructions': + return {'result': artifactPrompt}; + default: + return {'result': 'unknown tool'}; + } + } +} + +String artifactPrompt = ''' + +The assistant can create and reference artifacts during conversations. Artifacts are for substantial, self-contained content that users might modify or reuse, displayed in a separate UI window for clarity. + +# Good artifacts are... +- Substantial content (>15 lines) +- Content that the user is likely to modify, iterate on, or take ownership of +- Self-contained, complex content that can be understood on its own, without context from the conversation +- Content intended for eventual use outside the conversation (e.g., reports, emails, presentations) +- Content likely to be referenced or reused multiple times + +# Don't use artifacts for... +- Simple, informational, or short content, such as brief code snippets, mathematical equations, or small examples +- Primarily explanatory, instructional, or illustrative content, such as examples provided to clarify a concept +- Suggestions, commentary, or feedback on existing artifacts +- Conversational or explanatory content that doesn't represent a standalone piece of work +- Content that is dependent on the current conversational context to be useful +- Content that is unlikely to be modified or iterated upon by the user +- Request from users that appears to be a one-off question + +# Usage notes +- One artifact per message unless specifically requested +- Prefer in-line content (don't use artifacts) when possible. Unnecessary use of artifacts can be jarring for users. +- If a user asks the assistant to "draw an SVG" or "make a website," the assistant does not need to explain that it doesn't have these capabilities. Creating the code and placing it within the appropriate artifact will fulfill the user's intentions. +- If asked to generate an image, the assistant can offer an SVG instead. The assistant isn't very proficient at making SVG images but should engage with the task positively. Self-deprecating humor about its abilities can make it an entertaining experience for users. +- The assistant errs on the side of simplicity and avoids overusing artifacts for content that can be effectively presented within the conversation. + + + When collaborating with the user on creating content that falls into compatible categories, the assistant should follow these steps: + + 2. Wrap the content in opening and closing `` tags. + 3. Assign an identifier to the `identifier` attribute of the opening `` tag. For updates, reuse the prior identifier. For new artifacts, the identifier should be descriptive and relevant to the content, using kebab-case (e.g., "example-code-snippet"). This identifier will be used consistently throughout the artifact's lifecycle, even when updating or iterating on the artifact. + 4. Include a `title` attribute in the `` tag to provide a brief title or description of the content. + 5. Add a `type` attribute to the opening `` tag to specify the type of content the artifact represents. Assign one of the following values to the `type` attribute: + - Code: "application/vnd.ant.code" + - Use for code snippets or scripts in any programming language. + - Include the language name as the value of the `language` attribute (e.g., `language="python"`). + - Do not use triple backticks when putting code in an artifact. + - Documents: "text/markdown" + - Plain text, Markdown, or other formatted text documents + - HTML: "text/html" + - The user interface can render single file HTML pages placed within the artifact tags. HTML, JS, and CSS should be in a single file when using the `text/html` type. + - Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so `placeholder` + - The only place external scripts can be imported from is https://cdnjs.cloudflare.com + - It is inappropriate to use "text/html" when sharing snippets, code samples & example HTML or CSS code, as it would be rendered as a webpage and the source code would be obscured. The assistant should instead use "application/vnd.ant.code" defined above. + - If the assistant is unable to follow the above requirements for any reason, use "application/vnd.ant.code" type for the artifact instead, which will not attempt to render the webpage. + - SVG: "image/svg+xml" + - The user interface will render the Scalable Vector Graphics (SVG) image within the artifact tags. + - The assistant should specify the viewbox of the SVG rather than defining a width/height + - Mermaid Diagrams: "application/vnd.ant.mermaid" + - The user interface will render Mermaid diagrams placed within the artifact tags. + - Do not put Mermaid code in a code block when using artifacts. + - React Components: "application/vnd.ant.react" + - Use this for displaying either: React elements, e.g. `Hello World!`, React pure functional components, e.g. `() => Hello World!`, React functional components with Hooks, or React component classes + - When creating a React component, ensure it has no required props (or provide default values for all props) and use a default export. + - Use Tailwind classes for styling. DO NOT USE ARBITRARY VALUES (e.g. `h-[600px]`). + - Base React is available to be imported. To use hooks, first import it at the top of the artifact, e.g. `import { useState } from "react"` + - The lucide-react@0.263.1 library is available to be imported. e.g. `import { Camera } from "lucide-react"` & `` + - The recharts charting library is available to be imported, e.g. `import { LineChart, XAxis, ... } from "recharts"` & ` ...` + - The assistant can use prebuilt components from the `shadcn/ui` library after it is imported: `import { Alert, AlertDescription, AlertTitle, AlertDialog, AlertDialogAction } from '@/components/ui/alert';`. If using components from the shadcn/ui library, the assistant mentions this to the user and offers to help them install the components if necessary. + - NO OTHER LIBRARIES (e.g. zod, hookform) ARE INSTALLED OR ABLE TO BE IMPORTED. + - Images from the web are not allowed, but you can use placeholder images by specifying the width and height like so `placeholder` + - If you are unable to follow the above requirements for any reason, use "application/vnd.ant.code" type for the artifact instead, which will not attempt to render the component. + 6. Include the complete and updated content of the artifact, without any truncation or minimization. Don't use "// rest of the code remains the same...". + 7. If unsure whether the content qualifies as an artifact, if an artifact should be updated, or which type to assign to an artifact, err on the side of not creating an artifact. + + +Here are some examples of correct usage of artifacts by other AI assistants: + + + + This example demonstrates how to create a new artifact and reference it in the response. + + + + Can you help me create a Python script to calculate the factorial of a number? + + + Sure! Here's a Python script that calculates the factorial of a number: + + + def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n - 1) + + ... + + + + + +This example shows how to update an existing artifact and reference it in the response. + + + + Thanks for the factorial script! Can you modify it to handle invalid input gracefully? + + + Good point! It's important to handle invalid input to prevent errors. I'll update the script to include input validation. + + + def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n - 1) + + while True: + try: + num = int(input("Enter a non-negative integer: ")) + if num < 0: + raise ValueError + break + except ValueError: + print("Invalid input. Please enter a non-negative integer.") + + ... + + + + + +This example shows how to create an SVG artifact and reference it in the response. + + + + Can you draw a simple blue circle in SVG? + + + I'll create a simple blue circle for you using SVG. + + + + + + + + Here's a simple SVG image of a blue circle, as requested. The circle is centered at coordinates (50, 50) with a radius of 40 pixels, and it's filled with the color blue. + + ... + + + + + + This example demonstrates how to create a Mermaid artifact for a simple flow chart. + + + + Can you create a simple flow chart showing the process of making tea using Mermaid? + + + Sure! Here's a simple flow chart depicting the process of making tea using Mermaid syntax: + + + graph TD + A[Start] --> B{Water boiled?} + B -->|Yes| C[Add tea leaves to cup] + B -->|No| D[Boil water] + D --> B + C --> E[Pour boiling water into cup] + E --> F[Steep tea for desired time] + F --> G[Remove tea leaves] + G --> H[Add milk or sugar, if desired] + H --> I[Enjoy your tea!] + I --> J[End] + + + This flow chart uses Mermaid syntax to visualize the steps involved in making a cup of tea. + + ... + + + + +This example demonstrates the assistant's preference to update existing artifacts, rather than create new ones. + + + + I'm teaching a beginner's programming course, and I want to include some interactive examples for the students to try out. Do you have any suggestions for simple programs that could help them understand basic concepts? + + + Teaching a beginner's programming course is a great opportunity to introduce students to fundamental concepts through interactive examples. One idea that comes to mind is building upon the factorial calculator we discussed earlier. + + + def factorial(n): + if n == 0: + return 1 + else: + return n * factorial(n - 1) + + def main(): + print("Welcome to the Factorial Calculator!") + print("Enter a non-negative integer to calculate its factorial.") + print("Enter 'q' to quit the program.") + + while True: + user_input = input("Enter a number (or 'q' to quit): ") + + if user_input == 'q': + print("Thank you for using the Factorial Calculator. Goodbye!") + break + + try: + num = int(user_input) + if num < 0: + raise ValueError + result = factorial(num) + print(f"The factorial of {num} is {result}") + except ValueError: + print("Invalid input. Please enter a non-negative integer or 'q' to quit.") + + if __name__ == "__main__": + main() + + + I've updated it to make it even more suitable as a learning example for your students. Here are the key changes: + + 1. Separated the factorial calculation logic into its own function, `factorial()`. This demonstrates the concept of function definition and recursion. + + ... + + + + + + This example demonstrates how to create a React component artifact for a metrics dashboard. + + + + Can you create a React component for a metrics dashboard? + + + Absolutely! Here's a React component that implements a basic metrics dashboard: + + + import React, { useState, useEffect } from 'react'; + import { BarChart, Bar, XAxis, YAxis, ResponsiveContainer } from 'recharts'; + import { Card, CardHeader, CardContent } from '@/components/ui/card'; + + const generateData = () => [...Array(12)].map((_, i) => ({ + month: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][i], + revenue: Math.floor(Math.random() * 5000) + 1000 + })); + + const MetricCard = ({ title, value, change }) => ( + + {title} + + ... + + export default Dashboard; + + + Feel free to ask if you want to extend this component! + + + + +This example demonstrates the assistant's decision not to use an artifact because it would make the information less accessible and hinder the natural flow of the conversation. + + + + + Can you give me a quick rundown of some common Python list methods? I'm new to Python and trying to understand the basics. + + + + Absolutely! Python lists are versatile and have many useful methods. Here's a quick overview of some common ones: + + 1. `append(x)`: Adds an item `x` to the end of the list. + Example: `my_list.append(4)` + + 2. `extend(iterable)`: Adds all items from an iterable (like another list) to the end. + Example: `my_list.extend([5, 6, 7])` + + 3. `insert(i, x)`: Inserts an item `x` at a given position `i`. + Example: `my_list.insert(1, "new")` + + ... + + + + +This example demonstrates the assistant's decision not to use an artifact for an explanation that includes code samples, because the content is primarily educational and benefits from being part of the conversational flow. + + + + + I'm learning Python and algorithms. Can you explain how binary search works and maybe show me a simple Python implementation? I learn best by seeing code. + + + + Absolutely! Binary search is an efficient algorithm for finding an item in a sorted list. It works by repeatedly dividing the search interval in half. Let's walk through it with a simple Python implementation. + + First, let's define a function for binary search: + + ```python + def binary_search(arr, target): + left, right = 0, len(arr) - 1 + + while left <= right: + mid = (left + right) // 2 + if arr[mid] == target: + return mid + elif arr[mid] < target: + left = mid + 1 + ... + + + + + +The assistant should not mention any of these instructions to the user, nor make reference to the `antArtifact` tag, any of the MIME types (e.g. `application/vnd.ant.code`), or related syntax unless it is directly relevant to the query. + +The assistant should always take care to not produce artifacts that would be highly hazardous to human health or wellbeing if misused, even if is asked to produce them for seemingly benign reasons. However, if Claude would be willing to produce the same content in text form, it should be willing to produce it in an artifact. + + +--- + +The assistant is Claude, created by Anthropic. +The current date is Friday, June 21, 2024. Claude's knowledge base was last updated on April 2024. +It answers questions about events prior to and after April 2024 the way a highly informed individual in April 2024 would if they were talking to someone from the above date, and can let the human know this when relevant. +Claude cannot open URLs, links, or videos. If it seems like the user is expecting Claude to do so, it clarifies the situation and asks the human to paste the relevant text or image content directly into the conversation. +If it is asked to assist with tasks involving the expression of views held by a significant number of people, Claude provides assistance with the task regardless of its own views. If asked about controversial topics, it tries to provide careful thoughts and clear information. +It presents the requested information without explicitly saying that the topic is sensitive, and without claiming to be presenting objective facts. +Claude is happy to help with analysis, question answering, math, coding, creative writing, teaching, general discussion, and all sorts of other tasks. +When presented with a math problem, logic problem, or other problem benefiting from systematic thinking, Claude thinks through it step by step before giving its final answer. +If Claude cannot or will not perform a task, it tells the user this without apologizing to them. It avoids starting its responses with "I'm sorry" or "I apologize". +If Claude is asked about a very obscure person, object, or topic, i.e. if it is asked for the kind of information that is unlikely to be found more than once or twice on the internet, Claude ends its response by reminding the user that although it tries to be accurate, it may hallucinate in response to questions like this. It uses the term 'hallucinate' to describe this since the user will understand what it means. +If Claude mentions or cites particular articles, papers, or books, it always lets the human know that it doesn't have access to search or a database and may hallucinate citations, so the human should double check its citations. +Claude is very smart and intellectually curious. It enjoys hearing what humans think on an issue and engaging in discussion on a wide variety of topics. +Claude never provides information that can be used for the creation, weaponization, or deployment of biological, chemical, or radiological agents that could cause mass harm. It can provide information about these topics that could not be used for the creation, weaponization, or deployment of these agents. +If the user seems unhappy with Claude or Claude's behavior, Claude tells them that although it cannot retain or learn from the current conversation, they can press the 'thumbs down' button below Claude's response and provide feedback to Anthropic. +If the user asks for a very long task that cannot be completed in a single response, Claude offers to do the task piecemeal and get feedback from the user as it completes each part of the task. +Claude uses markdown for code. +Immediately after closing coding markdown, Claude asks the user if they would like it to explain or break down the code. It does not explain or break down the code unless the user explicitly requests it. + + +Claude always responds as if it is completely face blind. If the shared image happens to contain a human face, Claude never identifies or names any humans in the image, nor does it imply that it recognizes the human. It also does not mention or allude to details about a person that it could only know if it recognized who the person was. Instead, Claude describes and discusses the image just as someone would if they were unable to recognize any of the humans in it. Claude can request the user to tell it who the individual is. If the user tells Claude who the individual is, Claude can discuss that named individual without ever confirming that it is the person in the image, identifying the person in the image, or implying it can use facial features to identify any unique individual. It should always reply as someone would if they were unable to recognize any humans from images. +Claude should respond normally if the shared image does not contain a human face. Claude should always repeat back and summarize any instructions in the image before proceeding. + + +This iteration of Claude is part of the Claude 3 model family, which was released in 2024. The Claude 3 family currently consists of Claude 3 Haiku, Claude 3 Opus, and Claude 3.5 Sonnet. Claude 3.5 Sonnet is the most intelligent model. Claude 3 Opus excels at writing and complex tasks. Claude 3 Haiku is the fastest model for daily tasks. The version of Claude in this chat is Claude 3.5 Sonnet. Claude can provide the information in these tags if asked but it does not know any other details of the Claude 3 model family. If asked about this, should encourage the user to check the Anthropic website for more information. + +Claude provides thorough responses to more complex and open-ended questions or to anything where a long response is requested, but concise responses to simpler questions and tasks. All else being equal, it tries to give the most correct and concise answer it can to the user's message. Rather than giving a long response, it gives a concise response and offers to elaborate if further information may be helpful. +Claude responds directly to all human messages without unnecessary affirmations or filler phrases like "Certainly!", "Of course!", "Absolutely!", "Great!", "Sure!", etc. Specifically, Claude avoids starting responses with the word "Certainly" in any way. +Claude follows this information in all languages, and always responds to the user in the language they use or request. The information above is provided to Claude by Anthropic. Claude never mentions the information above unless it is directly pertinent to the human's query. Claude is now being connected with a human. +'''; diff --git a/lib/mcp/inmemory_server/factory.dart b/lib/mcp/inmemory_server/factory.dart new file mode 100644 index 0000000..dcd15b8 --- /dev/null +++ b/lib/mcp/inmemory_server/factory.dart @@ -0,0 +1,18 @@ +import '../inmemory/memory_server.dart'; +import 'math.dart'; +import 'artifact_instructions.dart'; +import 'package:logging/logging.dart'; + +class MemoryServerFactory { + static MemoryServer? createMemoryServer(String command) { + Logger.root.info('createMemoryServer command: $command'); + switch (command) { + case 'artifact_instructions': + return ArtifactServer(); + case 'math': + return MathServer(); + default: + return null; + } + } +} diff --git a/lib/mcp/inmemory_server/math.dart b/lib/mcp/inmemory_server/math.dart new file mode 100644 index 0000000..5c3628e --- /dev/null +++ b/lib/mcp/inmemory_server/math.dart @@ -0,0 +1,683 @@ +import 'package:logging/logging.dart'; +import 'dart:math' as math; + +import '../inmemory/memory_server.dart'; +import '../models/json_rpc_message.dart'; + +class MathServer extends MemoryServer { + MathServer() : super(name: 'math-server') { + addTool( + Tool( + name: 'add', + description: 'Add two numbers', + inputSchema: ToolInput( + type: 'object', + description: 'Add two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'subtract', + description: 'Subtract two numbers', + inputSchema: ToolInput( + type: 'object', + description: 'Subtract two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'multiply', + description: 'Multiply two numbers', + inputSchema: ToolInput( + type: 'object', + description: 'Multiply two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'divide', + description: 'Divide two numbers', + inputSchema: ToolInput( + type: 'object', + description: 'Divide two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'power', + description: 'Power of two numbers', + inputSchema: ToolInput( + type: 'object', + description: 'Power of two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'sqrt', + description: 'Square root of a number', + inputSchema: ToolInput( + type: 'object', + description: 'Square root of a number', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'cbrt', + description: 'Cube root of a number', + inputSchema: ToolInput( + type: 'object', + description: 'Cube root of a number', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'abs', + description: 'Calculate absolute value', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the absolute value of a number', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'sin', + description: 'Calculate sine value', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the sine of an angle (input in radians)', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'cos', + description: 'Calculate cosine value', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the cosine of an angle (input in radians)', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'tan', + description: 'Calculate tangent value', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the tangent of an angle (input in radians)', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'log', + description: 'Calculate logarithm', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the logarithm with specific base, defaults to natural logarithm', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'base', type: ToolInputType.integer), + ], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'max', + description: 'Find maximum value', + inputSchema: ToolInput( + type: 'object', + description: 'Return the maximum of two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'min', + description: 'Find minimum value', + inputSchema: ToolInput( + type: 'object', + description: 'Return the minimum of two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'round', + description: 'Round to nearest integer', + inputSchema: ToolInput( + type: 'object', + description: 'Round a number to the nearest integer', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'ceil', + description: 'Round up to the nearest integer', + inputSchema: ToolInput( + type: 'object', + description: 'Round a number up to the nearest integer', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'floor', + description: 'Round down to the nearest integer', + inputSchema: ToolInput( + type: 'object', + description: 'Round a number down to the nearest integer', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + + addTool( + Tool( + name: 'mod', + description: 'Modulo operation', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the remainder of division of two numbers', + properties: [ + Property(name: 'a', type: ToolInputType.integer), + Property(name: 'b', type: ToolInputType.integer), + ], + required: ['a', 'b'], + ), + ), + ); + + addTool( + Tool( + name: 'factorial', + description: 'Calculate factorial', + inputSchema: ToolInput( + type: 'object', + description: 'Calculate the factorial of a non-negative integer', + properties: [Property(name: 'a', type: ToolInputType.integer)], + required: ['a'], + ), + ), + ); + } + + @override + Map onToolCall(JSONRPCMessage message) { + try { + String name = message.params?['name']; + + Map? arguments = message.params?['arguments']; + if (arguments == null) { + return {'error': 'Arguments cannot be empty'}; + } + + Logger.root.fine('memory_server onToolCall name: $name arguments: $arguments'); + + // Execute operations based on tool name + switch (name) { + case 'add': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + return {'result': add(a, b)}; + case 'subtract': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + return {'result': subtract(a, b)}; + case 'multiply': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + return {'result': multiply(a, b)}; + case 'divide': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + if (b == 0) { + return {'error': 'Division by zero is not allowed'}; + } + return {'result': divide(a, b)}; + case 'power': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + try { + return {'result': power(a, b)}; + } catch (e) { + return {'error': 'Power operation error: $e'}; + } + case 'sqrt': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + if (a < 0) { + return {'error': 'Cannot compute square root of negative number'}; + } + return {'result': sqrt(a)}; + case 'cbrt': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': cbrt(a)}; + case 'abs': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': abs(a)}; + case 'sin': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': sin(a)}; + case 'cos': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': cos(a)}; + case 'tan': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + // Check for singularities in the tan function + if ((a % (math.pi / 2)).abs() < 1e-10 && (a % math.pi).abs() > 1e-10) { + return {'error': 'Tangent is undefined at π/2 + nπ'}; + } + return {'result': tan(a)}; + case 'log': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + if (a <= 0) { + return {'error': 'Logarithm requires a positive number'}; + } + + if (arguments.containsKey('base')) { + var base = castToNumber(arguments['base']); + if (base == null) { + return {'error': 'Base parameter must be a valid number'}; + } + if (base <= 0 || base == 1) { + return {'error': 'Logarithm base must be positive and not equal to 1'}; + } + return {'result': logWithBase(a, base)}; + } else { + return {'result': log(a)}; + } + case 'max': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + return {'result': max(a, b)}; + case 'min': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + return {'result': min(a, b)}; + case 'round': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': round(a)}; + case 'ceil': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': ceil(a)}; + case 'floor': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + return {'result': floor(a)}; + case 'mod': + if (!_validateRequiredArgs(arguments, ['a', 'b'])) { + return {'error': 'Missing required parameters: a, b'}; + } + var a = castToNumber(arguments['a']); + var b = castToNumber(arguments['b']); + if (a == null || b == null) { + return {'error': 'Parameters must be valid numbers'}; + } + if (b == 0) { + return {'error': 'Modulo by zero is not allowed'}; + } + return {'result': mod(a, b)}; + case 'factorial': + if (!_validateRequiredArgs(arguments, ['a'])) { + return {'error': 'Missing required parameter: a'}; + } + var a = castToNumber(arguments['a']); + if (a == null) { + return {'error': 'Parameter must be a valid number'}; + } + if (a < 0) { + return {'error': 'Factorial cannot be applied to negative numbers'}; + } + if (a > 20) { + return {'error': 'Factorial too large, please use a number less than or equal to 20'}; + } + try { + return {'result': factorial(a)}; + } catch (e) { + return {'error': 'Factorial calculation error: $e'}; + } + default: + return {'error': 'Unknown tool: $name'}; + } + } catch (e, stackTrace) { + Logger.root.severe('MathServer error: $e\n$stackTrace'); + return {'error': 'Error occurred during calculation: $e'}; + } + } + + // 验证必要参数是否存在 + bool _validateRequiredArgs(Map args, List requiredArgs) { + for (var arg in requiredArgs) { + if (!args.containsKey(arg) || args[arg] == null) { + return false; + } + } + return true; + } + + int add(num a, num b) { + return a.toInt() + b.toInt(); + } + + int subtract(num a, num b) { + return a.toInt() - b.toInt(); + } + + int multiply(num a, num b) { + return a.toInt() * b.toInt(); + } + + double divide(num a, num b) { + if (b == 0) { + throw ArgumentError('Division by zero is not allowed'); + } + return a / b; + } + + int power(num a, num b) { + if (b < 0) { + throw ArgumentError('Negative exponents are not supported in this implementation'); + } + return math.pow(a, b).toInt(); + } + + double sqrt(num a) { + if (a < 0) { + throw ArgumentError('Cannot compute square root of negative number'); + } + return math.sqrt(a); + } + + double cbrt(num a) { + return math.pow(a.abs(), 1 / 3).toDouble() * (a < 0 ? -1 : 1); + } + + int abs(num a) { + return a.abs().toInt(); + } + + double sin(num a) { + return math.sin(a); + } + + double cos(num a) { + return math.cos(a); + } + + double tan(num a) { + // Check for singularities in the tan function + if ((a % (math.pi / 2)).abs() < 1e-10 && (a % math.pi).abs() > 1e-10) { + throw ArgumentError('Tangent is undefined at π/2 + nπ'); + } + return math.tan(a); + } + + double log(num a) { + if (a <= 0) { + throw ArgumentError('Logarithm requires a positive number'); + } + return math.log(a); + } + + double logWithBase(num a, num base) { + if (a <= 0) { + throw ArgumentError('Logarithm requires a positive number'); + } + if (base <= 0 || base == 1) { + throw ArgumentError('Logarithm base must be positive and not equal to 1'); + } + return math.log(a) / math.log(base); + } + + num max(num a, num b) { + return math.max(a, b); + } + + num min(num a, num b) { + return math.min(a, b); + } + + int round(num a) { + return a.round(); + } + + int ceil(num a) { + return a.ceil(); + } + + int floor(num a) { + return a.floor(); + } + + int mod(num a, num b) { + if (b == 0) { + throw ArgumentError('Modulo by zero is not allowed'); + } + return a.toInt() % b.toInt(); + } + + int factorial(num a) { + if (a < 0) { + throw ArgumentError('Factorial cannot be applied to negative numbers'); + } + if (a > 20) { + throw ArgumentError('Factorial too large, please use a number less than or equal to 20'); + } + if (a <= 1) { + return 1; + } + return a.toInt() * factorial(a - 1); + } +} + +int? castToNumber(dynamic value) { + if (value == null) { + return null; + } + + if (value is int) { + return value; + } + + if (value is double) { + return value.toInt(); + } + + if (value is String) { + if (value.trim().isEmpty) { + return null; + } + + try { + var parsed = num.tryParse(value); + if (parsed == null) { + return null; + } + return parsed.toInt(); + } catch (_) { + return null; + } + } + + return null; +} diff --git a/lib/mcp/mcp.dart b/lib/mcp/mcp.dart new file mode 100644 index 0000000..f0ee765 --- /dev/null +++ b/lib/mcp/mcp.dart @@ -0,0 +1,156 @@ +import 'package:logging/logging.dart'; +import '../utils/toast.dart'; +import './models/server.dart'; +import './client/mcp_client_interface.dart'; +import './stdio/stdio_client.dart'; +import './sse/sse_client.dart'; +import './streamable/streamable_client.dart'; +import 'inmemory/client.dart'; +import 'inmemory_server/factory.dart'; + +Future initializeMcpServer(Map mcpServerConfig) async { + // Get server configuration + final serverConfig = ServerConfig.fromJson(mcpServerConfig); + + // Create appropriate client based on configuration + McpClient mcpClient; + + // 首先检查类型字段 + if (serverConfig.type.isNotEmpty) { + switch (serverConfig.type) { + case 'sse': + mcpClient = SSEClient(serverConfig: serverConfig); + break; + case 'streamable': + mcpClient = StreamableClient(serverConfig: serverConfig); + break; + case 'stdio': + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return null; + } + break; + case 'inmemory': + final memoryServer = MemoryServerFactory.createMemoryServer(serverConfig.command); + if (memoryServer == null) { + Logger.root.severe('Failed to create memory server'); + + ToastUtils.error('Memory server creation failed'); + + return null; + } + mcpClient = InMemoryClient(server: memoryServer); + break; + default: + // 降级为基于命令的逻辑 + if (serverConfig.command.startsWith('http')) { + mcpClient = SSEClient(serverConfig: serverConfig); + } else { + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient in fallback: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return null; + } + } + } + } else { + // 降级为原来的逻辑 + if (serverConfig.command.startsWith('http')) { + mcpClient = SSEClient(serverConfig: serverConfig); + } else { + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient in legacy fallback: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return null; + } + } + } + + try { + await mcpClient.initialize(); + final initResponse = await mcpClient.sendInitialize(); + Logger.root.info('Initialization response: $initResponse'); + + final toolListResponse = await mcpClient.sendToolList(); + Logger.root.info('Tool list response: $toolListResponse'); + + return mcpClient; + } catch (e) { + Logger.root.severe('Failed to initialize MCP server: $e'); + + // 显示错误 toast 通知 + ToastUtils.error('MCP Error: ${e.toString()}'); + + return null; + } +} + +Future verifyMcpServer(Map mcpServerConfig) async { + final serverConfig = ServerConfig.fromJson(mcpServerConfig); + + McpClient mcpClient; + + if (serverConfig.type.isNotEmpty) { + switch (serverConfig.type) { + case 'sse': + mcpClient = SSEClient(serverConfig: serverConfig); + break; + case 'streamable': + mcpClient = StreamableClient(serverConfig: serverConfig); + break; + case 'stdio': + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient for verification: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return false; + } + break; + default: + // 降级为基于命令的逻辑 + if (serverConfig.command.startsWith('http')) { + mcpClient = SSEClient(serverConfig: serverConfig); + } else { + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient in verify fallback: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return false; + } + } + } + } else { + // 降级为原来的逻辑 + if (serverConfig.command.startsWith('http')) { + mcpClient = SSEClient(serverConfig: serverConfig); + } else { + try { + mcpClient = StdioClient(serverConfig: serverConfig); + } catch (e) { + Logger.root.severe('Failed to create StdioClient in verify legacy fallback: $e'); + ToastUtils.error('StdioClient creation failed: ${e.toString()}'); + return false; + } + } + } + + try { + await mcpClient.sendInitialize(); + return true; + } catch (e) { + Logger.root.warning('Failed to verify MCP server: $e'); + + ToastUtils.warn('MCP server verification failed: ${e.toString()}'); + + return false; + } +} diff --git a/lib/mcp/models/json_rpc_message.dart b/lib/mcp/models/json_rpc_message.dart new file mode 100644 index 0000000..e1c2f11 --- /dev/null +++ b/lib/mcp/models/json_rpc_message.dart @@ -0,0 +1,40 @@ +import 'dart:convert'; + +class JSONRPCMessage { + final String? id; + final String jsonrpc; + final String? method; // Method is not required for all messages + final Map? params; + final dynamic result; + final dynamic error; + + JSONRPCMessage({this.id, this.jsonrpc = '2.0', this.method, this.params, this.result, this.error}); + + factory JSONRPCMessage.fromJson(Map json) { + return JSONRPCMessage( + id: json['id']?.toString(), + jsonrpc: json['jsonrpc']?.toString() ?? '2.0', + method: json['method']?.toString(), + params: json['params'] as Map?, + result: json['result'], + error: json['error'], + ); + } + + Map toJson() { + final Map json = {'jsonrpc': jsonrpc}; + + if (method != null) json['method'] = method; + if (id != null) json['id'] = id; + if (params != null) json['params'] = params; + if (result != null) json['result'] = result; + if (error != null) json['error'] = error; + + return json; + } + + @override + String toString() { + return jsonEncode(toJson()); + } +} diff --git a/lib/mcp/models/server.dart b/lib/mcp/models/server.dart new file mode 100644 index 0000000..984dfe8 --- /dev/null +++ b/lib/mcp/models/server.dart @@ -0,0 +1,155 @@ +class OAuth { + final bool enabled; + final String clientId; + final String? clientSecret; + final String authorizationUrl; + final String tokenUrl; + final String scope; + final String redirectUri; + final String? refreshToken; + final String? accessToken; + final DateTime? tokenExpiry; + + const OAuth({ + required this.enabled, + required this.clientId, + this.clientSecret, + required this.authorizationUrl, + required this.tokenUrl, + required this.scope, + required this.redirectUri, + this.refreshToken, + this.accessToken, + this.tokenExpiry, + }); + + factory OAuth.fromJson(Map json) { + return OAuth( + enabled: json['enabled'] as bool? ?? false, + clientId: json['client_id'] as String? ?? '', + clientSecret: json['client_secret'] as String?, + authorizationUrl: json['authorization_url'] as String? ?? '', + tokenUrl: json['token_url'] as String? ?? '', + scope: json['scope'] as String? ?? '', + redirectUri: json['redirect_uri'] as String? ?? '', + refreshToken: json['refresh_token'] as String?, + accessToken: json['access_token'] as String?, + tokenExpiry: json['token_expiry'] != null + ? DateTime.parse(json['token_expiry'] as String) + : null, + ); + } + + Map toJson() { + return { + 'enabled': enabled, + 'client_id': clientId, + if (clientSecret != null) 'client_secret': clientSecret, + 'authorization_url': authorizationUrl, + 'token_url': tokenUrl, + 'scope': scope, + 'redirect_uri': redirectUri, + if (refreshToken != null) 'refresh_token': refreshToken, + if (accessToken != null) 'access_token': accessToken, + if (tokenExpiry != null) 'token_expiry': tokenExpiry!.toIso8601String(), + }; + } + + OAuth copyWith({ + bool? enabled, + String? clientId, + String? clientSecret, + String? authorizationUrl, + String? tokenUrl, + String? scope, + String? redirectUri, + String? refreshToken, + String? accessToken, + DateTime? tokenExpiry, + }) { + return OAuth( + enabled: enabled ?? this.enabled, + clientId: clientId ?? this.clientId, + clientSecret: clientSecret ?? this.clientSecret, + authorizationUrl: authorizationUrl ?? this.authorizationUrl, + tokenUrl: tokenUrl ?? this.tokenUrl, + scope: scope ?? this.scope, + redirectUri: redirectUri ?? this.redirectUri, + refreshToken: refreshToken ?? this.refreshToken, + accessToken: accessToken ?? this.accessToken, + tokenExpiry: tokenExpiry ?? this.tokenExpiry, + ); + } + + bool get isTokenValid { + if (accessToken == null) return false; + if (tokenExpiry == null) return true; // No expiry means token doesn't expire + return DateTime.now().isBefore(tokenExpiry!); + } + + bool get needsRefresh { + if (accessToken == null) return true; + if (tokenExpiry == null) return false; + // Refresh if token expires in less than 5 minutes + return DateTime.now().isAfter(tokenExpiry!.subtract(const Duration(minutes: 5))); + } +} + +class ServerConfig { + final String command; + final List args; + final Map env; + final String author; + final String type; + final OAuth? oauth; + + const ServerConfig({ + required this.command, + required this.args, + this.env = const {}, + this.author = '', + this.type = '', + this.oauth, + }); + + // Create ServerConfig from JSON Map + factory ServerConfig.fromJson(Map json) { + return ServerConfig( + command: json['command'] as String, + args: ((json['args'] ?? []) as List).cast(), + env: ((json['env'] ?? {}) as Map?)?.cast() ?? const {}, + type: json['type'] as String? ?? '', + oauth: json['oauth'] != null ? OAuth.fromJson(json['oauth'] as Map) : null, + ); + } + + // Convert ServerConfig to JSON Map + Map toJson() { + return { + 'command': command, + 'args': args, + 'env': env, + 'author': author, + 'type': type, + if (oauth != null) 'oauth': oauth!.toJson(), + }; + } + + ServerConfig copyWith({ + String? command, + List? args, + Map? env, + String? author, + String? type, + OAuth? oauth, + }) { + return ServerConfig( + command: command ?? this.command, + args: args ?? this.args, + env: env ?? this.env, + author: author ?? this.author, + type: type ?? this.type, + oauth: oauth ?? this.oauth, + ); + } +} diff --git a/lib/mcp/models/tool.dart b/lib/mcp/models/tool.dart new file mode 100644 index 0000000..7913bf2 --- /dev/null +++ b/lib/mcp/models/tool.dart @@ -0,0 +1,51 @@ +class ToolResponse { + final List tools; + + ToolResponse({required this.tools}); + + factory ToolResponse.fromJson(Map json) { + var toolsList = json['tools'] as List; + List tools = toolsList.map((t) => Tool.fromJson(t)).toList(); + return ToolResponse(tools: tools); + } +} + +class Tool { + final String name; + final String description; + final InputSchema inputSchema; + + Tool({required this.name, required this.description, required this.inputSchema}); + + factory Tool.fromJson(Map json) { + return Tool(name: json['name'], description: json['description'], inputSchema: InputSchema.fromJson(json['inputSchema'])); + } +} + +class InputSchema { + final String type; + final Map? properties; + final List? required; + + InputSchema({required this.type, this.properties, this.required}); + + factory InputSchema.fromJson(Map json) { + Map? props; + if (json['properties'] != null) { + props = Map.fromEntries((json['properties'] as Map).entries.map((e) => MapEntry(e.key, Property.fromJson(e.value)))); + } + + return InputSchema(type: json['type'], properties: props, required: json['required'] != null ? List.from(json['required']) : null); + } +} + +class Property { + final String type; + final String? description; + + Property({required this.type, this.description}); + + factory Property.fromJson(Map json) { + return Property(type: json['type'], description: json['description']); + } +} diff --git a/lib/mcp/sse/sse_client.dart b/lib/mcp/sse/sse_client.dart new file mode 100644 index 0000000..7823f9b --- /dev/null +++ b/lib/mcp/sse/sse_client.dart @@ -0,0 +1,393 @@ +import 'package:chatmcp/mcp/stdio/stdio_client.dart'; +import 'package:synchronized/synchronized.dart'; +import 'package:eventflux/eventflux.dart'; + +import '../client/mcp_client_interface.dart'; +import '../models/json_rpc_message.dart'; +import '../models/server.dart'; +import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; +import 'dart:convert'; +import 'dart:async'; + +// 连接状态枚举 +enum ConnectionState { disconnected, connecting, waitingForEndpoint, connected, reconnecting } + +class SSEClient implements McpClient { + final ServerConfig _serverConfig; + final _pendingRequests = >{}; + final _processStateController = StreamController.broadcast(); + Stream get processStateStream => _processStateController.stream; + + late final EventFlux _eventFlux; + final _writeLock = Lock(); + String? _messageEndpoint; + bool _isEndpointConfirmed = false; + Completer _endpointConfirmedCompleter = Completer(); + + bool _isConnecting = false; + bool _disposed = false; + static const int _maxReconnectAttempts = 5; + static const Duration _initialReconnectDelay = Duration(seconds: 1); + static const Duration _endpointTimeout = Duration(seconds: 10); + Timer? _endpointTimer; + + ConnectionState _connectionState = ConnectionState.disconnected; + + /// Gets headers including OAuth Bearer token if available + Map get _headers { + final headers = { + 'Content-Type': 'application/json; charset=utf-8', + 'Accept': 'application/json; charset=utf-8' + }; + + // Add OAuth Bearer token if available and valid + if (_serverConfig.oauth != null && + _serverConfig.oauth!.enabled && + _serverConfig.oauth!.accessToken != null && + _serverConfig.oauth!.isTokenValid) { + headers['Authorization'] = 'Bearer ${_serverConfig.oauth!.accessToken}'; + } + + return headers; + } + + SSEClient({required ServerConfig serverConfig}) : _serverConfig = serverConfig { + _eventFlux = EventFlux.spawn(); + } + + @override + ServerConfig get serverConfig => _serverConfig; + + void _handleMessage(JSONRPCMessage message) { + if (message.id != null && _pendingRequests.containsKey(message.id)) { + final completer = _pendingRequests.remove(message.id); + completer?.complete(message); + } + if (message.method == 'ping') { + Logger.root.info('Received ping message, sending pong response'); + final pongMessage = JSONRPCMessage.fromJson({'id': message.id, 'jsonrpc': message.jsonrpc, 'result': {}}); + Logger.root.info('Sending pong response: $pongMessage'); + _sendHttpPost(pongMessage.toJson()); + } + } + + @override + Future initialize() async { + await _connect(); + } + + Future _connect() async { + if (_isConnecting || _disposed) return; + + _isConnecting = true; + _connectionState = ConnectionState.connecting; + _isEndpointConfirmed = false; + + try { + Logger.root.info('开始建立SSE连接: ${serverConfig.command}'); + _processStateController.add(const ProcessState.starting()); + + // 重置endpoint确认状态 + _endpointTimer?.cancel(); + _endpointTimer = null; + + // 创建新的completer + _endpointConfirmedCompleter = Completer(); + + String connectionUrl = serverConfig.command; + Logger.root.info('建立SSE连接到: $connectionUrl'); + _connectionState = ConnectionState.waitingForEndpoint; + + // 设置endpoint超时定时器 + _endpointTimer = Timer(_endpointTimeout, () { + if (!_endpointConfirmedCompleter.isCompleted) { + _endpointConfirmedCompleter.completeError('Endpoint confirmation timeout'); + } + }); + + _eventFlux.connect( + EventFluxConnectionType.get, + connectionUrl, + header: _headers, + autoReconnect: true, + reconnectConfig: ReconnectConfig( + mode: ReconnectMode.exponential, + interval: _initialReconnectDelay, + maxAttempts: _maxReconnectAttempts, + onReconnect: () { + Logger.root.info('SSE连接正在重连'); + _connectionState = ConnectionState.reconnecting; + }, + ), + onSuccessCallback: (response) { + response?.stream?.listen((event) { + Logger.root.fine('收到SSE事件: ${event.event}, ID: ${event.id}, 数据长度: ${event.data.length}字节'); + _handleSSEEvent(event); + }); + }, + onError: (error) { + Logger.root.severe('SSE连接错误: $error'); + _connectionState = ConnectionState.disconnected; + _processStateController.add(ProcessState.error(error, StackTrace.current)); + }, + onConnectionClose: () { + Logger.root.info('SSE连接关闭'); + _connectionState = ConnectionState.disconnected; + _processStateController.add(const ProcessState.exited(0)); + }, + tag: 'MCP-SSE', + ); + + // 等待endpoint确认 + try { + await _endpointConfirmedCompleter.future.timeout(_endpointTimeout); + Logger.root.info('SSE连接已确认并获取到有效endpoint'); + _connectionState = ConnectionState.connected; + } catch (e) { + Logger.root.severe('等待endpoint确认超时: $e'); + throw Exception('Failed to confirm endpoint: $e'); + } + } catch (e, stack) { + Logger.root.severe('SSE连接失败: $e\n$stack'); + _connectionState = ConnectionState.disconnected; + _processStateController.add(ProcessState.error(e, stack)); + } finally { + _isConnecting = false; + } + } + + void _handleSSEEvent(EventFluxData event) { + final eventType = event.event; + final data = event.data; + + Logger.root.info('event: $eventType, data: $data'); + + if (eventType == 'endpoint') { + _handleEndpointEvent(data); + } else { + try { + final jsonData = jsonDecode(data); + final message = JSONRPCMessage.fromJson(jsonData); + _handleMessage(message); + } catch (e, stack) { + Logger.root.severe('handle message failed: $e\n$stack'); + } + } + } + + void _handleEndpointEvent(String data) { + try { + final uri = Uri.parse(serverConfig.command); + + data = data.trim(); + String rawEndpoint = data.startsWith("http") ? data : uri.resolve(data).toString(); + + final parsedUri = Uri.parse(rawEndpoint); + if (!parsedUri.hasScheme || !parsedUri.hasAuthority) { + Logger.root.severe('invalid endpoint: $rawEndpoint'); + return; + } + + // 构建标准化的endpoint URL + final Map queryParams = Map.from(parsedUri.queryParameters); + + uri.queryParameters.forEach((key, value) { + queryParams[key] = value; + }); + + Logger.root.info('parsedUri host: ${parsedUri.host}, path: ${parsedUri.path}, query: ${parsedUri.query}'); + + final normalizedUri = Uri( + scheme: parsedUri.scheme, + host: parsedUri.host, + port: parsedUri.port, + path: parsedUri.path, + queryParameters: queryParams, + ); + + _messageEndpoint = normalizedUri.toString(); + _isEndpointConfirmed = true; + + Logger.root.info('endpoint: $_messageEndpoint'); + _processStateController.add(const ProcessState.running()); + + // 完成endpoint确认 + if (!_endpointConfirmedCompleter.isCompleted) { + _endpointConfirmedCompleter.complete(); + } + _endpointTimer?.cancel(); + } catch (e) { + Logger.root.severe('handle endpoint event failed: $e'); + if (!_endpointConfirmedCompleter.isCompleted) { + _endpointConfirmedCompleter.completeError(e); + } + } + } + + Future _ensureValidConnection() async { + if (_connectionState != ConnectionState.connected || !_isEndpointConfirmed) { + Logger.root.info('connection state is not valid, try to reconnect'); + await _connect(); + } + } + + @override + Future dispose() async { + _disposed = true; + _endpointTimer?.cancel(); + _endpointTimer = null; + + // 断开SSE连接 + await _eventFlux.disconnect(); + + await _processStateController.close(); + _messageEndpoint = null; + } + + Future _sendHttpPost(Map data) async { + if (_messageEndpoint == null) { + throw StateError('message endpoint is not initialized'); + } + + await _writeLock.synchronized(() async { + try { + await _ensureValidConnection(); + + final response = await http.post(Uri.parse(_messageEndpoint!), headers: _headers, body: jsonEncode(data)); + + if (response.statusCode >= 400) { + final errorBody = response.body; + throw Exception('HTTP POST ERROR: ${response.statusCode} - $errorBody'); + } + } catch (e) { + Logger.root.severe('HTTP POST failed: $e'); + rethrow; + } + }); + } + + @override + Future sendMessage(JSONRPCMessage message) async { + if (message.id == null) { + throw ArgumentError('message must have an id'); + } + + final completer = Completer(); + _pendingRequests[message.id!] = completer; + + try { + Logger.root.info('send message: ${message.id} - ${message.method}'); + await _sendHttpPost(message.toJson()); + + return await completer.future.timeout( + const Duration(seconds: 60 * 5), + onTimeout: () { + _pendingRequests.remove(message.id); + throw TimeoutException('请求超时: ${message.id}'); + }, + ); + } catch (e) { + _pendingRequests.remove(message.id); + rethrow; + } + } + + @override + Future sendInitialize() async { + // 确保连接已经建立 + if (_messageEndpoint == null) { + Logger.root.warning('try to initialize but message endpoint is not established, wait for endpoint to be established...'); + // 等待一段时间以确保SSE连接已建立并获取到端点 + int attempts = 0; + const maxAttempts = 30; // 增加到30次尝试 + const delay = Duration(milliseconds: 500); + + while (_messageEndpoint == null && attempts < maxAttempts) { + await Future.delayed(delay); + attempts++; + Logger.root.info('wait for message endpoint to be established: attempt $attempts/$maxAttempts'); + + // 如果连接已关闭或出错,尝试重新连接 + if (_disposed) { + Logger.root.warning('SSE connection may be closed, try to reconnect'); + await _connect(); + } + } + + if (_messageEndpoint == null) { + Logger.root.severe('message endpoint is not established after ${maxAttempts * delay.inMilliseconds / 1000} seconds'); + throw StateError('message endpoint is not established, cannot complete initialization'); + } + } + + Logger.root.info('开始发送初始化请求到 $_messageEndpoint'); + + // 发送初始化请求 + final initMessage = JSONRPCMessage( + id: 'init-1', + method: 'initialize', + params: { + 'protocolVersion': '2024-11-05', + 'capabilities': { + 'roots': {'listChanged': true}, + 'sampling': {}, + }, + 'clientInfo': {'name': 'DartMCPClient', 'version': '1.0.0'}, + }, + ); + + Logger.root.info('初始化请求内容: ${jsonEncode(initMessage.toJson())}'); + + try { + final initResponse = await sendMessage(initMessage); + Logger.root.info('initialize response: $initResponse'); + + // 等待一小段时间确保服务器已处理初始化请求 + await Future.delayed(const Duration(milliseconds: 100)); + + // 发送初始化完成通知 + Logger.root.info('send initialize completed notification'); + await _sendNotification('notifications/initialized', {}); + + return initResponse; + } catch (e, stack) { + Logger.root.severe('initialize failed: $e\n$stack'); + rethrow; + } + } + + @override + Future sendPing() async { + final message = JSONRPCMessage(id: 'ping-1', method: 'ping'); + return sendMessage(message); + } + + @override + Future sendToolList() async { + final message = JSONRPCMessage(id: 'tool-list-1', method: 'tools/list'); + return sendMessage(message); + } + + @override + Future sendToolCall({required String name, required Map arguments, String? id}) async { + final message = JSONRPCMessage( + method: 'tools/call', + params: { + 'name': name, + 'arguments': arguments, + '_meta': {'progressToken': 0}, + }, + id: id ?? 'tool-call-${DateTime.now().millisecondsSinceEpoch}', + ); + + return sendMessage(message); + } + + // 添加一个实用方法来发送符合格式的通知 + Future _sendNotification(String method, Map params) async { + final notification = JSONRPCMessage(method: method, params: params); + + await _sendHttpPost(notification.toJson()); + } +} diff --git a/lib/mcp/stdio/stdio_client.dart b/lib/mcp/stdio/stdio_client.dart new file mode 100644 index 0000000..16904ab --- /dev/null +++ b/lib/mcp/stdio/stdio_client.dart @@ -0,0 +1,234 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:logging/logging.dart'; +import 'package:synchronized/synchronized.dart'; +import '../models/json_rpc_message.dart'; +import '../models/server.dart'; +import '../../utils/process.dart'; +import '../client/mcp_client_interface.dart'; + +class StdioClient implements McpClient { + @override + final ServerConfig serverConfig; + late final Process process; + final _writeLock = Lock(); + final _pendingRequests = >{}; + final List stdErrCallback; + final List stdOutCallback; + + // Add StreamController + final _processStateController = StreamController.broadcast(); + + // Provide public Stream + Stream get processStateStream => _processStateController.stream; + + StdioClient({required this.serverConfig, this.stdErrCallback = const [], this.stdOutCallback = const []}); + + void _handleMessage(JSONRPCMessage message) { + if (message.id != null && _pendingRequests.containsKey(message.id)) { + final completer = _pendingRequests.remove(message.id); + completer?.complete(message); + } + } + + Future _setupProcess() async { + try { + Logger.root.info('Starting process: ${serverConfig.command} ${serverConfig.args.join(" ")}'); + + _processStateController.add(const ProcessState.starting()); + + final args = serverConfig.args.map((arg) { + String processed = arg; + if ((processed.startsWith('"') && processed.endsWith('"')) || (processed.startsWith("'") && processed.endsWith("'"))) { + if (processed.length >= 2) { + processed = processed.substring(1, processed.length - 1); + } + } + return processed; + }).toList(); + + process = await startProcess(serverConfig.command, args, serverConfig.env); + + Logger.root.info('Process startup status: PID=${process.pid}'); + + // Use utf8 decoder + final stdoutStream = process.stdout.transform(utf8.decoder).transform(const LineSplitter()); + + stdoutStream.listen( + (String line) { + try { + for (final callback in stdOutCallback) { + callback(line); + } + final data = jsonDecode(line); + final message = JSONRPCMessage.fromJson(data); + _handleMessage(message); + } catch (e, stack) { + Logger.root.severe('Failed to parse server output: $e\n$stack'); + } + }, + onError: (error) { + Logger.root.severe('stdout error: $error'); + for (final callback in stdErrCallback) { + callback(error.toString()); + } + }, + onDone: () { + Logger.root.info('stdout stream closed'); + }, + ); + + process.stderr + .transform(utf8.decoder) + .listen( + (String text) { + Logger.root.warning('Server error output: $text'); + for (final callback in stdErrCallback) { + callback(text); + } + }, + onError: (error) { + Logger.root.severe('stderr error: $error'); + for (final callback in stdErrCallback) { + callback(error.toString()); + } + }, + ); + + // Listen for process exit + process.exitCode.then((code) { + Logger.root.info('Process exited with code: $code'); + _processStateController.add(ProcessState.exited(code)); + }); + + _processStateController.add(const ProcessState.running()); + } catch (e, stackTrace) { + Logger.root.severe('Failed to start process: $e\nStackTrace: $stackTrace'); + _processStateController.add(ProcessState.error(e, stackTrace)); + rethrow; // 重新抛出异常以便上层处理 + } + } + + Future write(List data) async { + try { + await _writeLock.synchronized(() async { + final String jsonStr = utf8.decode(data); + process.stdin.writeln(utf8.decode(data)); + await process.stdin.flush(); + Logger.root.info('Data written: $jsonStr'); + }); + } catch (e) { + Logger.root.severe('Failed to write data: $e'); + rethrow; + } + } + + // Add initialize method + @override + Future initialize() async { + await _setupProcess(); + } + + // Modify dispose method + @override + Future dispose() async { + await _processStateController.close(); + process.kill(); + } + + @override + Future sendMessage(JSONRPCMessage message) async { + if (message.id == null) { + throw ArgumentError('Message must have an id'); + } + + final completer = Completer(); + _pendingRequests[message.id!] = completer; + + try { + await write(utf8.encode(jsonEncode(message.toJson()))); + return await completer.future.timeout( + const Duration(seconds: 60 * 60), + onTimeout: () { + _pendingRequests.remove(message.id); + throw TimeoutException('Request timed out: ${message.id}'); + }, + ); + } catch (e) { + _pendingRequests.remove(message.id); + rethrow; + } + } + + @override + Future sendInitialize() async { + // Step 1: Send initialization request + final initMessage = JSONRPCMessage( + id: 'init-1', + method: 'initialize', + params: { + 'protocolVersion': '2024-11-05', + 'capabilities': { + 'roots': {'listChanged': true}, + 'sampling': {}, + }, + 'clientInfo': {'name': 'DartMCPClient', 'version': '1.0.0'}, + }, + ); + + final initResponse = await sendMessage(initMessage); + Logger.root.info('Initialization request response: $initResponse'); + + // Step 2: Send initialization complete notification (no response needed) + final notifyMessage = JSONRPCMessage(method: 'notifications/initialized', params: {}); + + await write(utf8.encode(jsonEncode(notifyMessage.toJson()))); + return initResponse; + } + + @override + Future sendPing() async { + final message = JSONRPCMessage(id: 'ping-1', method: 'ping'); + return sendMessage(message); + } + + @override + Future sendToolList() async { + final message = JSONRPCMessage(id: 'tool-list-1', method: 'tools/list'); + return sendMessage(message); + } + + @override + Future sendToolCall({required String name, required Map arguments, String? id}) async { + final message = JSONRPCMessage( + method: 'tools/call', + params: { + 'name': name, + 'arguments': arguments, + '_meta': {'progressToken': 0}, + }, + id: id ?? 'tool-call-${DateTime.now().millisecondsSinceEpoch}', + ); + + return sendMessage(message); + } +} + +// Add process state enum +enum ProcessStateType { starting, running, error, exited } + +// Add process state class +class ProcessState { + final ProcessStateType type; + final dynamic error; + final StackTrace? stackTrace; + final int? exitCode; + + const ProcessState._(this.type, {this.error, this.stackTrace, this.exitCode}); + + const ProcessState.starting() : this._(ProcessStateType.starting); + const ProcessState.running() : this._(ProcessStateType.running); + const ProcessState.error(dynamic err, StackTrace stack) : this._(ProcessStateType.error, error: err, stackTrace: stack); + const ProcessState.exited(int code) : this._(ProcessStateType.exited, exitCode: code); +} diff --git a/lib/mcp/streamable/streamable_client.dart b/lib/mcp/streamable/streamable_client.dart new file mode 100644 index 0000000..af09a42 --- /dev/null +++ b/lib/mcp/streamable/streamable_client.dart @@ -0,0 +1,525 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; +import '../models/json_rpc_message.dart'; +import '../models/server.dart'; +import '../client/mcp_client_interface.dart'; + +/// 自定义错误类,用于Streamable HTTP连接错误 +class StreamableHTTPError extends Error { + final int? code; + final String message; + + StreamableHTTPError(this.code, this.message); + + @override + String toString() => 'Streamable HTTP error: $message'; +} + +/// 未授权错误 +class UnauthorizedError extends Error { + final String message; + + UnauthorizedError([this.message = "Unauthorized"]); + + @override + String toString() => 'Unauthorized error: $message'; +} + +/// 重连选项配置 +class StreamableHTTPReconnectionOptions { + /// 初始重连延迟(毫秒) + final int initialReconnectionDelay; + + /// 最大重连延迟(毫秒) + final int maxReconnectionDelay; + + /// 重连延迟增长因子 + final double reconnectionDelayGrowFactor; + + /// 最大重试次数 + final int maxRetries; + + const StreamableHTTPReconnectionOptions({ + this.initialReconnectionDelay = 1000, + this.maxReconnectionDelay = 30000, + this.reconnectionDelayGrowFactor = 1.5, + this.maxRetries = 2, + }); +} + +/// SSE连接选项 +class StartSSEOptions { + /// 恢复令牌,用于继续被中断的长时间运行的请求 + final String? resumptionToken; + + /// 当恢复令牌改变时调用的回调 + final Function(String)? onResumptionToken; + + /// 覆盖与重播消息关联的消息ID + final String? replayMessageId; + + StartSSEOptions({this.resumptionToken, this.onResumptionToken, this.replayMessageId}); +} + +/// Streamable HTTP客户端实现 +class StreamableClient implements McpClient { + @override + final ServerConfig serverConfig; + + /// HTTP客户端 + final http.Client _httpClient = http.Client(); + + /// 服务器URL + late final String _url; + + /// 会话ID + String? _sessionId; + + /// 用于中止请求的控制器 + StreamController? _abortController; + + /// 重连选项 + final StreamableHTTPReconnectionOptions _reconnectionOptions; + + /// 已尝试的重连次数 + int _reconnectionAttempts = 0; + + /// 消息处理回调 + Function(JSONRPCMessage)? onMessage; + + /// 错误处理回调 + Function(Object)? onError; + + /// 关闭连接回调 + Function()? onClose; + + StreamableClient({required this.serverConfig, StreamableHTTPReconnectionOptions? reconnectionOptions}) + : _reconnectionOptions = reconnectionOptions ?? const StreamableHTTPReconnectionOptions() { + if (serverConfig.command.startsWith('http')) { + _url = serverConfig.command; + } else { + throw ArgumentError('URL is required for StreamableClient'); + } + } + + /// 获取通用HTTP头 + Future> _commonHeaders() async { + final headers = {'Accept': 'application/json, text/event-stream', 'Content-Type': 'application/json'}; + + if (_sessionId != null) { + headers['mcp-session-id'] = _sessionId!; + } + + // Add OAuth Bearer token if available and valid + if (serverConfig.oauth != null && + serverConfig.oauth!.enabled && + serverConfig.oauth!.accessToken != null && + serverConfig.oauth!.isTokenValid) { + headers['Authorization'] = 'Bearer ${serverConfig.oauth!.accessToken}'; + } + + return headers; + } + + /// 启动或授权SSE连接 + Future _startOrAuthSse(StartSSEOptions options) async { + try { + final headers = await _commonHeaders(); + + // 添加Last-Event-ID头,如果有恢复令牌 + if (options.resumptionToken != null) { + headers['Last-Event-ID'] = options.resumptionToken!; + } + + // 设置接受SSE流 + headers['Accept'] = 'text/event-stream'; + + final request = http.Request('GET', Uri.parse(_url)); + request.headers.addAll(headers); + + final response = await _httpClient.send(request); + + if (!response.statusCode.toString().startsWith('2')) { + if (response.statusCode == 401) { + // 授权失败处理 + throw UnauthorizedError(); + } + + throw StreamableHTTPError(response.statusCode, 'Failed to connect to SSE stream: ${response.reasonPhrase}'); + } + + // 处理会话ID + final responseHeaders = response.headers; + if (responseHeaders.containsKey('mcp-session-id')) { + final sessionIdValue = responseHeaders['mcp-session-id']; + if (sessionIdValue != null) { + _sessionId = sessionIdValue; + } + } + + // 处理SSE流 + _handleSseStream(response.stream, options); + } catch (error) { + onError?.call(error); + rethrow; + } + } + + /// 计划重连 + void _scheduleReconnection(StartSSEOptions options, int attemptIndex) { + if (attemptIndex >= _reconnectionOptions.maxRetries) { + onError?.call(Exception('Maximum reconnection attempts reached')); + return; + } + + final delay = _calculateReconnectionDelay(attemptIndex); + + Future.delayed(Duration(milliseconds: delay), () { + if (_abortController == null || _abortController!.isClosed) { + return; // 已关闭,不再重连 + } + + // 尝试重连 + _startOrAuthSse(options).catchError((error) { + _reconnectionAttempts++; + _scheduleReconnection(options, attemptIndex + 1); + }); + }); + } + + /// 计算重连延迟 + int _calculateReconnectionDelay(int attemptIndex) { + final delay = _reconnectionOptions.initialReconnectionDelay * _reconnectionOptions.reconnectionDelayGrowFactor.pow(attemptIndex); + + return delay.clamp(_reconnectionOptions.initialReconnectionDelay.toDouble(), _reconnectionOptions.maxReconnectionDelay.toDouble()).toInt(); + } + + /// 处理SSE流 + void _handleSseStream(Stream> stream, StartSSEOptions options) { + final onResumptionToken = options.onResumptionToken; + final replayMessageId = options.replayMessageId; + String? lastEventId; + + // 确保流是可以多次监听的广播流 + final broadcastStream = stream.isBroadcast ? stream : stream.asBroadcastStream(); + + // 解码UTF-8并拆分为行 + final lineStream = broadcastStream.transform(utf8.decoder).transform(const LineSplitter()); + + // SSE处理变量 + String? eventName; + String data = ''; + String id = ''; + + // 订阅处理 + final subscription = lineStream.listen( + (line) { + if (line.isEmpty) { + // 空行表示事件结束 + if (data.isNotEmpty) { + // 处理事件 + if (id.isNotEmpty) { + lastEventId = id; + onResumptionToken?.call(id); + } + + if (eventName == null || eventName == 'message') { + try { + final parsed = jsonDecode(data); + final message = JSONRPCMessage.fromJson(parsed); + + // 如果需要替换消息ID + if (replayMessageId != null && message.id != null) { + // 由于无法直接访问私有字段,我们创建一个新的消息对象 + final newMessage = JSONRPCMessage( + id: replayMessageId, + method: message.method, + params: message.params, + result: message.result, + error: message.error, + ); + onMessage?.call(newMessage); + } else { + onMessage?.call(message); + } + } catch (error) { + onError?.call(error); + } + } + } + + // 重置事件数据 + eventName = null; + data = ''; + id = ''; + } else if (line.startsWith('event:')) { + eventName = line.substring(6).trim(); + } else if (line.startsWith('data:')) { + data += line.substring(5).trim(); + } else if (line.startsWith('id:')) { + id = line.substring(3).trim(); + } + }, + onError: (error) { + onError?.call(error); + + // 尝试重连 + if (_abortController != null && !_abortController!.isClosed) { + if (lastEventId != null) { + try { + _scheduleReconnection( + StartSSEOptions(resumptionToken: lastEventId, onResumptionToken: onResumptionToken, replayMessageId: replayMessageId), + 0, + ); + } catch (reconnectError) { + onError?.call(Exception('Failed to reconnect: $reconnectError')); + } + } + } + }, + onDone: () { + // 如果流正常关闭,也尝试重连 + if (_abortController != null && !_abortController!.isClosed) { + if (lastEventId != null) { + try { + _scheduleReconnection( + StartSSEOptions(resumptionToken: lastEventId, onResumptionToken: onResumptionToken, replayMessageId: replayMessageId), + 0, + ); + } catch (reconnectError) { + onError?.call(Exception('Failed to reconnect: $reconnectError')); + } + } + } + }, + cancelOnError: false, + ); + + // 当中止控制器关闭时,取消订阅 + if (_abortController != null && !_abortController!.isClosed) { + // 由于_abortController现在是广播流,无需担心多次监听 + _abortController!.stream.listen((_) { + subscription.cancel(); + }); + } + } + + /// 启动客户端连接 + @override + Future initialize() async { + if (_abortController != null) { + throw Exception('StreamableClient already started!'); + } + + // 使用广播流控制器以支持多次监听 + _abortController = StreamController.broadcast(); + } + + /// 关闭客户端连接 + @override + Future dispose() async { + _abortController?.add(true); + await _abortController?.close(); + _abortController = null; + _httpClient.close(); + onClose?.call(); + } + + /// 发送消息到服务器 + @override + Future sendMessage(JSONRPCMessage message) async { + try { + final headers = await _commonHeaders(); + final completer = Completer(); + + final response = await _httpClient.post(Uri.parse(_url), headers: headers, body: jsonEncode(message.toJson())); + + // 处理会话ID + final sessionIdValue = response.headers['mcp-session-id']; + if (sessionIdValue != null && sessionIdValue.isNotEmpty) { + _sessionId = sessionIdValue; + } + + if (!response.statusCode.toString().startsWith('2')) { + if (response.statusCode == 401) { + // 授权失败处理 + throw UnauthorizedError(); + } + + throw StreamableHTTPError(response.statusCode, 'Error POSTing to endpoint (HTTP ${response.statusCode}): ${response.body}'); + } + + // 如果响应是202 Accepted,没有主体需要处理 + if (response.statusCode == 202) { + // 如果是initialized通知,我们启动SSE流 + if (message.method == 'notifications/initialized') { + _startOrAuthSse(StartSSEOptions()).catchError((error) { + onError?.call(error); + }); + } + + // 创建一个默认的成功响应 + final successResponse = JSONRPCMessage( + id: message.id, + method: '', // 添加空字符串作为默认method值 + result: {'success': true}, + ); + + return successResponse; + } + + // 检查响应类型 + final contentType = response.headers['content-type']; + + if (message.id != null) { + if (contentType?.contains('text/event-stream') == true) { + // 为请求处理SSE流响应 + // 创建响应体的字节流的一次性副本,确保类型为List而不是Uint8List + final responseBodyBytes = response.bodyBytes; + // 将Uint8List显式转换为List类型的Stream + final responseBodyStream = Stream>.value(responseBodyBytes); + + // 注册一个临时处理函数 + final oldOnMessage = onMessage; + + // 使用函数声明而不是变量赋值 + void completerOnMessage(JSONRPCMessage responseMessage) { + if (responseMessage.id == message.id && !completer.isCompleted) { + completer.complete(responseMessage); + } + // 同时调用原始消息处理器 + oldOnMessage?.call(responseMessage); + } + + onMessage = completerOnMessage; + + // 处理SSE流 + _handleSseStream(responseBodyStream, StartSSEOptions()); + + // 设置超时 + return completer.future + .timeout( + const Duration(seconds: 30), + onTimeout: () { + // 恢复原始消息处理器 + onMessage = oldOnMessage; + throw TimeoutException('Request timed out: ${message.id}'); + }, + ) + .whenComplete(() { + // 请求完成后恢复原始消息处理器 + onMessage = oldOnMessage; + }); + } else if (contentType?.contains('application/json') == true) { + // 对于非流式服务器,我们可能会得到直接的JSON响应 + final data = jsonDecode(response.body); + + if (data is List) { + for (final item in data) { + final msg = JSONRPCMessage.fromJson(item); + if (msg.id == message.id) { + return msg; + } + } + } else { + return JSONRPCMessage.fromJson(data); + } + } + } + + throw StreamableHTTPError(-1, 'Unexpected response or content type: $contentType'); + } catch (error) { + onError?.call(error); + rethrow; + } + } + + @override + Future sendInitialize() async { + // 发送初始化请求 + final initMessage = JSONRPCMessage( + id: 'init-1', + method: 'initialize', + params: { + 'protocolVersion': '2024-11-05', + 'capabilities': { + 'roots': {'listChanged': true}, + 'sampling': {}, + }, + 'clientInfo': {'name': 'DartMCPStreamableClient', 'version': '1.0.0'}, + }, + ); + + final initResponse = await sendMessage(initMessage); + Logger.root.info('Initialization request response: $initResponse'); + + // 发送初始化完成通知 + final notifyMessage = JSONRPCMessage(method: 'notifications/initialized', params: {}); + + await sendMessage(notifyMessage); + return initResponse; + } + + @override + Future sendPing() async { + final message = JSONRPCMessage(id: 'ping-1', method: 'ping'); + return sendMessage(message); + } + + @override + Future sendToolList() async { + final message = JSONRPCMessage(id: 'tool-list-1', method: 'tools/list'); + return sendMessage(message); + } + + @override + Future sendToolCall({required String name, required Map arguments, String? id}) async { + final message = JSONRPCMessage( + method: 'tools/call', + params: { + 'name': name, + 'arguments': arguments, + '_meta': {'progressToken': 0}, + }, + id: id ?? 'tool-call-${DateTime.now().millisecondsSinceEpoch}', + ); + + return sendMessage(message); + } + + /// 终止当前会话 + Future terminateSession() async { + if (_sessionId == null) { + return; // 没有会话需要终止 + } + + try { + final headers = await _commonHeaders(); + + final response = await _httpClient.delete(Uri.parse(_url), headers: headers); + + // 我们特别处理405作为有效响应 + if (!response.statusCode.toString().startsWith('2') && response.statusCode != 405) { + throw StreamableHTTPError(response.statusCode, 'Failed to terminate session: ${response.reasonPhrase}'); + } + + _sessionId = null; + } catch (error) { + onError?.call(error); + rethrow; + } + } +} + +// 用于num类型的pow方法扩展 +extension NumExtension on num { + double pow(int exponent) { + double result = 1.0; + for (int i = 0; i < exponent; i++) { + result *= this; + } + return result; + } +} diff --git a/lib/page/layout/chat_page/chat_code_preview.dart b/lib/page/layout/chat_page/chat_code_preview.dart new file mode 100644 index 0000000..68d9039 --- /dev/null +++ b/lib/page/layout/chat_page/chat_code_preview.dart @@ -0,0 +1,300 @@ +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/widgets/markdown/widgets/html_view.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_highlight/themes/github.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:flutter/foundation.dart'; +import 'package:chatmcp/utils/event_bus.dart'; +import 'package:chatmcp/widgets/markdown/markit_widget.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter_highlight/flutter_highlight.dart'; + +class ChatCodePreview extends StatefulWidget { + final CodePreviewEvent codePreviewEvent; + const ChatCodePreview({super.key, required this.codePreviewEvent}); + + @override + State createState() => _ChatCodePreviewState(); +} + +class _ChatCodePreviewState extends State { + final double _height = 300; // 默认高度 + InAppWebViewController? controller; + bool _hasError = false; + int _retryCount = 0; + static const int maxRetries = 3; + + Key _webViewKey = UniqueKey(); + + bool _showCode = true; + + bool _supportPreview = false; + + @override + void initState() { + super.initState(); + } + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } + + void _handleError() { + if (_retryCount < maxRetries) { + _retryCount++; + _resetWebView(); + } else { + setState(() => _hasError = true); + } + } + + void _resetWebView() { + controller?.dispose(); + controller = null; + setState(() => _webViewKey = UniqueKey()); + } + + CodePreviewEvent? get codePreviewEvent => ProviderManager.chatProvider.artifactEvent; + + Widget _buildToolBar() { + var t = AppLocalizations.of(context)!; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: AppColors.getToolbarBackgroundColor(context), + borderRadius: const BorderRadius.vertical(top: Radius.circular(8)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + IconButton( + style: IconButton.styleFrom( + iconSize: 16, + padding: const EdgeInsets.all(0), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + onPressed: () { + if (kIsMobile) { + Navigator.pop(context); + return; + } + setState(() { + ProviderManager.chatProvider.clearArtifactEvent(); + }); + }, + icon: const Icon(Icons.close), + ), + const SizedBox(width: 4), + // copy button + TextButton( + onPressed: () { + Clipboard.setData(ClipboardData(text: widget.codePreviewEvent.textContent)); + }, + style: IconButton.styleFrom( + iconSize: 16, + padding: const EdgeInsets.all(0), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: Text(t.copy, style: TextStyle(fontSize: 9, height: 1, color: AppColors.getInactiveTextColor(context))), + ), + const SizedBox(width: 4), + TextButton( + style: TextButton.styleFrom( + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + backgroundColor: _showCode ? AppColors.getCodeTabActiveColor(context) : AppColors.getCodeTabInactiveColor(context), + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + ), + onPressed: () { + setState(() { + _showCode = true; + }); + }, + child: Text( + t.code, + style: TextStyle( + fontSize: 9, + height: 1, + color: _showCode ? Theme.of(context).primaryColor : AppColors.getInactiveTextColor(context), + ), + ), + ), + if (_supportPreview) ...[ + const SizedBox(width: 4), + TextButton( + style: TextButton.styleFrom( + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + backgroundColor: AppColors.getTextButtonColor(context), + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), + ), + onPressed: () { + setState(() { + _showCode = false; + }); + }, + child: Text( + t.preview, + style: TextStyle( + fontSize: 9, + height: 1, + color: !_showCode ? Theme.of(context).primaryColor : AppColors.getInactiveTextColor(context), + ), + ), + ), + ], + ], + ), + const Spacer(), + Text( + widget.codePreviewEvent.attributes['type']?.isEmpty ?? true ? 'text' : widget.codePreviewEvent.attributes['type']!, + style: TextStyle(color: AppColors.getCodeLanguageTextColor(context), fontSize: 10, fontWeight: FontWeight.w500), + ), + ], + ), + ); + } + + Widget _buildSandboxWebView({required int sandboxServerPort}) { + var t = AppLocalizations.of(context)!; + return InAppWebView( + key: _webViewKey, + initialSettings: InAppWebViewSettings(javaScriptEnabled: true, transparentBackground: true, isInspectable: kDebugMode), + initialUrlRequest: URLRequest(url: WebUri('http://localhost:$sandboxServerPort'), headers: {'Content-Type': 'text/html; charset=UTF-8'}), + onLoadStop: (controller, url) async { + await Future.delayed(const Duration(milliseconds: 1000)); + // 注入并执行 JavaScript 代码 + await controller.evaluateJavascript(source: '''updateCode("${Uri.encodeComponent(codePreviewEvent?.textContent ?? '')}")'''); + }, + onCreateWindow: (controller, request) => Future.value(false), + onReceivedError: (controller, request, error) { + debugPrint('Error on received error: ${error.description}'); + _handleError(); + }, + ); + } + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + if (_hasError) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text(t.loadContentFailed), + const SizedBox(height: 8), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: AppColors.getToolbarBackgroundColor(context)), + onPressed: () { + setState(() { + _hasError = false; + _retryCount = 0; + }); + _resetWebView(); + }, + child: Text(t.retry), + ), + ], + ), + ); + } + + String language = widget.codePreviewEvent.attributes['type'] ?? ''; + if (language.contains("react")) { + language = "react"; + _supportPreview = true; + } else if (language.contains("vue")) { + language = "vue"; + } else if (language.contains("html")) { + language = "html"; + _supportPreview = true; + } else if (language.contains("css")) { + language = "css"; + } else if (language.contains("js")) { + language = "javascript"; + } else if (language.contains("ts")) { + language = "typescript"; + } else if (language.contains("python")) { + language = "python"; + } else if (language.contains("java")) { + language = "java"; + } else if (language.contains("c")) { + language = "c"; + } + + final sandboxServerPort = ProviderManager.settingsProvider.sandboxServerPort; + + if (!_supportPreview) { + return Container( + decoration: BoxDecoration( + border: Border.all(color: AppColors.getCodePreviewBorderColor(context)), + borderRadius: BorderRadius.circular(8), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildToolBar(), + Expanded( + child: language == "text/markdown" + ? Markit(data: codePreviewEvent?.textContent ?? '') + : SizedBox( + width: double.infinity, + child: HighlightView( + codePreviewEvent?.textContent ?? '', + language: language, + theme: githubTheme, + padding: const EdgeInsets.all(8), + ), + ), + ), + ], + ), + ); + } + + return Container( + decoration: BoxDecoration( + border: Border.all(color: AppColors.getCodePreviewBorderColor(context)), + borderRadius: BorderRadius.circular(8), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildToolBar(), + Expanded( + child: !_showCode + ? (language == "html" + ? HtmlView(html: codePreviewEvent?.textContent ?? '') + : _buildSandboxWebView(sandboxServerPort: sandboxServerPort)) + : SingleChildScrollView( + child: SizedBox( + width: double.infinity, + child: HighlightView( + codePreviewEvent?.textContent ?? '', + language: language, + theme: githubTheme, + padding: const EdgeInsets.all(8), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/page/layout/chat_page/chat_loading.dart b/lib/page/layout/chat_page/chat_loading.dart new file mode 100644 index 0000000..9c69d3f --- /dev/null +++ b/lib/page/layout/chat_page/chat_loading.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/utils/color.dart'; + +class ChatLoading extends StatefulWidget { + const ChatLoading({super.key}); + + @override + State createState() => _ChatLoadingState(); +} + +class _ChatLoadingState extends State with SingleTickerProviderStateMixin { + late final AnimationController _controller; + late final Animation _animation; + + @override + void initState() { + super.initState(); + _controller = AnimationController(duration: const Duration(milliseconds: 1000), vsync: this)..repeat(reverse: true); + + _animation = Tween(begin: 8.0, end: 16.0).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut)); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 20, + child: AnimatedBuilder( + animation: _animation, + builder: (context, child) { + return Padding( + padding: const EdgeInsets.only(left: 8, bottom: 8), + child: Align( + alignment: Alignment.centerLeft, + child: Container( + width: _animation.value, + height: _animation.value, + decoration: BoxDecoration(color: AppColors.getChatLoadingColor(context), shape: BoxShape.circle), + ), + ), + ); + }, + ), + ); + } +} diff --git a/lib/page/layout/chat_page/chat_message.dart b/lib/page/layout/chat_page/chat_message.dart new file mode 100644 index 0000000..84f8b8d --- /dev/null +++ b/lib/page/layout/chat_page/chat_message.dart @@ -0,0 +1,498 @@ +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'dart:convert'; +import 'package:chatmcp/widgets/collapsible_section.dart'; +import 'package:chatmcp/widgets/markdown/markit_widget.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'dart:io' as io; +import 'package:chatmcp/utils/color.dart'; +import 'chat_message_action.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'chat_loading.dart'; + +/// Document attachment component is used to display the file attachment in the chat message. +/// +/// - [path] The path of the file +/// - [name] The name of the file +/// - [fileType] The type of the file +class FileAttachment extends StatelessWidget { + final String path; + final String name; + final String fileType; + + const FileAttachment({super.key, required this.path, required this.name, required this.fileType}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6), + decoration: BoxDecoration(color: AppColors.getFileAttachmentBackgroundColor(context), borderRadius: BorderRadius.circular(16)), + child: fileType.startsWith('image') ? _buildImagePreview(context) : _buildFilePreview(), + ); + } + + Widget _buildImagePreview(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return ConstrainedBox( + constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.6, maxHeight: 300), + child: ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.file( + io.File(path), + fit: BoxFit.contain, + errorBuilder: (context, error, stackTrace) { + return Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration(color: AppColors.getFileAttachmentBackgroundColor(context), borderRadius: BorderRadius.circular(8)), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.broken_image, color: AppColors.getImageErrorIconColor(context), size: 32), + Text(l10n.brokenImage), + ], + ), + ); + }, + ), + ), + ); + } + + Widget _buildFilePreview() { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.attach_file, size: 16), + const SizedBox(width: 4), + Flexible( + child: Text(name, style: const TextStyle(fontSize: 12), overflow: TextOverflow.ellipsis, maxLines: 1), + ), + ], + ); + } +} + +/// Message long press menu is used to display the long press menu in the chat message. +/// +/// - [message] The message +/// - [onRetry] The function to retry the message +class MessageLongPressMenu extends StatelessWidget { + final ChatMessage message; + final Function(ChatMessage) onRetry; + + const MessageLongPressMenu({super.key, required this.message, required this.onRetry}); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + leading: const Icon(Icons.copy_outlined), + title: Text(l10n.copy), + onTap: () { + Clipboard.setData(ClipboardData(text: message.content ?? '')); + Navigator.pop(context); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l10n.copied), duration: const Duration(seconds: 2))); + }, + ), + if (message.role != MessageRole.user) + ListTile( + leading: const Icon(Icons.refresh), + title: Text(l10n.retry), + onTap: () { + Navigator.pop(context); + onRetry(message); + }, + ), + ], + ); + } +} + +/// Chat UI message is used to display the chat message in the chat page. +/// +/// - [messages] The list of messages +/// - [onRetry] The function to retry the message +/// - [onSwitch] The function to switch the message +class ChatUIMessage extends StatelessWidget { + final List messages; + final Function(ChatMessage) onRetry; + final Function(String messageId) onSwitch; + + const ChatUIMessage({super.key, required this.messages, required this.onRetry, required this.onSwitch}); + + List _filterMessages(List messages) { + if (messages.length <= 1) return messages; + return messages.where((m) => m.role != MessageRole.assistant || (m.role == MessageRole.assistant && m.content != '')).toList(); + } + + BubblePosition _getMessagePosition(int index, int total) { + if (total == 1) return BubblePosition.single; + if (index == 0) return BubblePosition.first; + if (index == total - 1) return BubblePosition.last; + return BubblePosition.middle; + } + + Widget _buildMessageGroup(BuildContext context, List messages, bool isUser) { + final filteredMessages = _filterMessages(messages); + if (filteredMessages.isEmpty) return const SizedBox(); + + if (filteredMessages.length == 1) { + return ChatMessageContent( + key: ValueKey(filteredMessages[0].messageId), + message: filteredMessages[0], + onRetry: onRetry, + position: BubblePosition.single, + ); + } + + return Container( + decoration: BoxDecoration(color: AppColors.getMessageBubbleBackgroundColor(context, isUser), borderRadius: BorderRadius.circular(16)), + child: Column( + crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start, + children: List.generate( + filteredMessages.length, + (index) => Padding( + padding: EdgeInsets.only(bottom: index == filteredMessages.length - 1 ? 0 : 1), + child: ChatMessageContent( + key: ValueKey(filteredMessages[index].messageId), + message: filteredMessages[index], + onRetry: onRetry, + position: _getMessagePosition(index, filteredMessages.length), + useTransparentBackground: true, + ), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + if (messages.isEmpty) return const SizedBox(); + + final firstMsg = messages.first; + final isUser = firstMsg.role == MessageRole.user; + + return Consumer( + builder: (context, settings, child) { + final showAssistantAvatar = settings.generalSetting.showAssistantAvatar; + final showUserAvatar = settings.generalSetting.showUserAvatar; + + return Container( + margin: const EdgeInsets.symmetric(vertical: 6.0), + child: Row( + mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isUser && showAssistantAvatar) ...[SizedBox(width: 40, child: ChatAvatar(isUser: false)), const SizedBox(width: 8)], + Flexible( + child: Column( + crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start, + children: [ + _buildMessageGroup(context, messages, isUser), + if (messages.last.role != MessageRole.loading) + MessageActions(messages: messages, onRetry: onRetry, onSwitch: onSwitch, isUser: isUser), + ], + ), + ), + if (isUser && showUserAvatar) ...[const SizedBox(width: 8), SizedBox(width: 40, child: ChatAvatar(isUser: true))], + ], + ), + ); + }, + ); + } +} + +/// Chat message content is used to display the chat message content in the chat message. +/// +/// - [message] The message +/// - [onRetry] The function to retry the message +/// - [position] The position of the message +/// - [useTransparentBackground] Whether to use transparent background +class ChatMessageContent extends StatelessWidget { + final ChatMessage message; + final Function(ChatMessage) onRetry; + final BubblePosition position; + final bool useTransparentBackground; + + const ChatMessageContent({ + super.key, + required this.message, + required this.onRetry, + this.position = BubblePosition.single, + this.useTransparentBackground = false, + }); + + Widget _buildMessage(BuildContext context) { + final messages = []; + + if (message.role == MessageRole.loading) { + messages.add(const ChatLoading()); + } + + if (message.files != null && message.files!.isNotEmpty) { + messages.add( + Container( + margin: const EdgeInsets.fromLTRB(0, 8, 0, 8), + child: Wrap( + spacing: 8, + runSpacing: 8, + children: message.files!.map((file) => FileAttachment(path: file.path!, name: file.name, fileType: file.fileType)).toList(), + ), + ), + ); + } + final bubbleKey = message.messageId; + if ((message.role == MessageRole.user || message.role == MessageRole.assistant) && message.content != null) { + messages.add( + MessageBubble( + key: ValueKey('${bubbleKey}_content'), + message: message, + position: position, + useTransparentBackground: useTransparentBackground, + ), + ); + } + + if (message.toolCalls != null && message.toolCalls!.isNotEmpty) { + messages.add( + MessageBubble( + key: ValueKey('${bubbleKey}_tool_calls'), + message: message, + position: position, + useTransparentBackground: useTransparentBackground, + ), + ); + } + + if (message.role == MessageRole.tool && message.toolCallId != null) { + messages.add( + MessageBubble( + key: ValueKey('${bubbleKey}_tool_result'), + message: message, + position: position, + useTransparentBackground: useTransparentBackground, + ), + ); + } + + return Column(crossAxisAlignment: message.role == MessageRole.user ? CrossAxisAlignment.end : CrossAxisAlignment.start, children: messages); + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onLongPress: () { + showModalBottomSheet( + context: context, + builder: (context) => MessageLongPressMenu(message: message, onRetry: onRetry), + ); + }, + child: _buildMessage(context), + ); + } +} + +/// Bubble position is used to determine the position of the bubble in the chat message. +/// +/// - [first] The first bubble +/// - [middle] The middle bubble +/// - [last] The last bubble +/// - [single] The single bubble +enum BubblePosition { first, middle, last, single } + +/// Message bubble is used to display the message bubble in the chat message. +/// +/// - [message] The message +/// - [position] The position of the message +/// - [useTransparentBackground] Whether to use transparent background +class MessageBubble extends StatelessWidget { + final ChatMessage message; + final BubblePosition position; + final bool useTransparentBackground; + + const MessageBubble({super.key, required this.message, this.position = BubblePosition.single, this.useTransparentBackground = false}); + + BorderRadius _getBorderRadius() { + const double radius = 16.0; + + switch (position) { + case BubblePosition.first: + return const BorderRadius.only(topLeft: Radius.circular(radius), topRight: Radius.circular(radius)); + case BubblePosition.middle: + return BorderRadius.zero; + case BubblePosition.last: + return const BorderRadius.only(bottomLeft: Radius.circular(radius), bottomRight: Radius.circular(radius)); + case BubblePosition.single: + return const BorderRadius.all(Radius.circular(radius)); + } + } + + EdgeInsets _getMargin() { + switch (position) { + case BubblePosition.first: + return EdgeInsets.zero; + case BubblePosition.middle: + return EdgeInsets.zero; + case BubblePosition.last: + return const EdgeInsets.only(bottom: 8); + case BubblePosition.single: + return const EdgeInsets.only(bottom: 8); + } + } + + EdgeInsets _getPadding() { + const double horizontal = 16.0; + const double verticalNormal = 10.0; + + switch (position) { + case BubblePosition.first: + return const EdgeInsets.only(left: horizontal, right: horizontal, top: verticalNormal, bottom: 0); + case BubblePosition.middle: + return const EdgeInsets.symmetric(horizontal: horizontal, vertical: 0); + case BubblePosition.last: + return const EdgeInsets.only(left: horizontal, right: horizontal, top: 0, bottom: verticalNormal); + case BubblePosition.single: + return const EdgeInsets.symmetric(horizontal: horizontal, vertical: verticalNormal); + } + } + + @override + Widget build(BuildContext context) { + Widget child = const Text(''); + if (message.content != null) { + if (message.role == MessageRole.user) { + child = Markit(data: (message.content!).trim()); + } else { + child = Markit(data: (message.content!).trim()); + if (message.tokenUsage != null) { + child = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + child, + const SizedBox(height: 4), + ExpansionTile( + title: const Text('Token Usage', style: TextStyle(fontSize: 12)), + controlAffinity: ListTileControlAffinity.leading, + children: [ListTile(title: Markit(data: message.tokenUsage!.toMarkdown()))], + ), + ], + ); + } + } + } + return Container( + margin: _getMargin(), + padding: _getPadding(), + decoration: BoxDecoration( + color: useTransparentBackground ? Colors.transparent : AppColors.getMessageBubbleBackgroundColor(context, message.role == MessageRole.user), + borderRadius: _getBorderRadius(), + ), + child: child + ); + } +} + +/// Tool call widget is used to display the tool call in the chat message. +/// +/// - [message] The message +class ToolCallWidget extends StatelessWidget { + final ChatMessage message; + + const ToolCallWidget({super.key, required this.message}); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Container( + margin: const EdgeInsets.symmetric(vertical: 8.0), + child: CollapsibleSection( + initiallyExpanded: false, + title: Text( + l10n.toolCall(message.toolCalls![0]['function']['name']), + style: TextStyle(fontSize: 12, color: AppColors.getToolCallTextColor(), fontStyle: FontStyle.italic), + ), + content: Markit( + data: (message.toolCalls?.isNotEmpty ?? false) + ? [ + '```json', + const JsonEncoder.withIndent(' ').convert({ + "name": message.toolCalls![0]['function']['name'], + "arguments": json.decode(message.toolCalls![0]['function']['arguments']), + }), + '```', + ].join('\n') + : '', + ), + ), + ); + } +} + +/// Tool result widget is used to display the tool result in the chat message. +/// +/// - [message] The message +class ToolResultWidget extends StatelessWidget { + final ChatMessage message; + + const ToolResultWidget({super.key, required this.message}); + + Widget _buildContent(BuildContext context) { + return SelectableText(message.content ?? ''); + } + + Widget _buildFactory(BuildContext context) { + switch (message.toolCallId) { + case 'call_web_search': + return Markit(data: message.content ?? ''); + case 'call_generate_image': + try { + final jsonData = json.decode(message.content ?? ''); + return Markit(data: "```json\n${const JsonEncoder.withIndent(' ').convert(jsonData)}\n```"); + } catch (e) { + return Markit(data: "```\n${message.content}\n```"); + } + default: + return _buildContent(context); + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Container( + margin: const EdgeInsets.symmetric(vertical: 8.0), + child: CollapsibleSection( + initiallyExpanded: false, + title: Text( + l10n.toolResult(message.toolCallId!.replaceFirst('call_', '')), + style: TextStyle(fontSize: 12, color: AppColors.getToolCallTextColor(), fontStyle: FontStyle.italic), + ), + content: _buildFactory(context), + ), + ); + } +} + +/// Chat avatar is used to display the chat avatar in the chat message. +/// +/// - [isUser] Whether the avatar is for the user +class ChatAvatar extends StatelessWidget { + final bool isUser; + + const ChatAvatar({super.key, required this.isUser}); + + @override + Widget build(BuildContext context) { + return CircleAvatar( + backgroundColor: AppColors.getChatAvatarBackgroundColor(), + child: Icon(isUser ? Icons.person : Icons.android, color: AppColors.getChatAvatarIconColor()), + ); + } +} diff --git a/lib/page/layout/chat_page/chat_message_action.dart b/lib/page/layout/chat_page/chat_message_action.dart new file mode 100644 index 0000000..c1220be --- /dev/null +++ b/lib/page/layout/chat_page/chat_message_action.dart @@ -0,0 +1,89 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:flutter/services.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +class MessageActions extends StatelessWidget { + final List messages; + final Function(ChatMessage) onRetry; + final Function(String messageId) onSwitch; + final bool isUser; + + const MessageActions({super.key, required this.messages, required this.onRetry, required this.onSwitch, this.isUser = false}); + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + return Padding( + padding: const EdgeInsets.only(left: 8, top: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + // Copy button - available for both user and assistant messages + IconButton( + iconSize: 14, + padding: const EdgeInsets.symmetric(horizontal: 4), + constraints: const BoxConstraints(minWidth: 20, minHeight: 20), + icon: const Icon(Icons.copy_outlined), + onPressed: () { + Clipboard.setData(ClipboardData(text: messages.map((m) => m.content ?? '').join('\n'))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.copiedToClipboard), duration: const Duration(seconds: 2))); + }, + ), + // Retry button - only for assistant messages + if (!isUser) + IconButton( + iconSize: 14, + padding: const EdgeInsets.symmetric(horizontal: 4), + constraints: const BoxConstraints(minWidth: 20, minHeight: 20), + icon: const Icon(Icons.refresh), + onPressed: () { + onRetry(messages.last); + }, + tooltip: t.retry, + ), + // Branch switch - only for assistant messages + if (!isUser && messages.first.brotherMessageIds != null && messages.first.brotherMessageIds!.isNotEmpty) _buildBranchSwitchWidget(messages), + ], + ), + ); + } + + Widget _buildBranchSwitchWidget(List messages) { + int index = messages.first.brotherMessageIds!.indexOf(messages.first.messageId) + 1; + int length = messages.first.brotherMessageIds!.length; + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + iconSize: 14, + padding: const EdgeInsets.symmetric(horizontal: 4), + constraints: const BoxConstraints(minWidth: 20, minHeight: 20), + icon: Icon(Icons.arrow_back_ios, size: 12, color: index == 1 ? AppColors.getMessageBranchDisabledColor() : null), + onPressed: index == 1 + ? null + : () { + onSwitch(messages.first.brotherMessageIds![index - 2]); + }, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Text('$index/$length', style: TextStyle(fontSize: 12, color: AppColors.getMessageBranchIndicatorTextColor())), + ), + IconButton( + iconSize: 14, + padding: const EdgeInsets.symmetric(horizontal: 4), + constraints: const BoxConstraints(minWidth: 20, minHeight: 20), + icon: Icon(Icons.arrow_forward_ios, size: 12, color: index == length ? AppColors.getMessageBranchDisabledColor() : null), + onPressed: index == length + ? null + : () { + onSwitch(messages.first.brotherMessageIds![index]); + }, + ), + ], + ); + } +} diff --git a/lib/page/layout/chat_page/chat_message_list.dart b/lib/page/layout/chat_page/chat_message_list.dart new file mode 100644 index 0000000..98900db --- /dev/null +++ b/lib/page/layout/chat_page/chat_message_list.dart @@ -0,0 +1,165 @@ +import 'package:chatmcp/utils/stream.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:flutter/rendering.dart'; +import 'chat_message.dart'; +import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; + +/// Message list is used to display the list of messages in the chat page. +/// +/// - [messages] The list of messages to display. +/// - [onRetry] The function to retry the message. +/// - [onSwitch] The function to switch the message to the another message. +class MessageList extends StatefulWidget { + final List messages; + final Function(ChatMessage) onRetry; + final Function(String messageId) onSwitch; + const MessageList({super.key, required this.messages, required this.onRetry, required this.onSwitch}); + + @override + State createState() => _MessageListState(); +} + +class _MessageListState extends State { + final ScrollController _scrollController = ScrollController(); + late final Stream _scrollDirectionChangedStream = asStream(_scrollController, () { + return _scrollController.position.userScrollDirection; + }).distinct(); + + bool _stickToBottom = true; + late final double endScroll = _scrollController.position.minScrollExtent; + + bool _isScrolledToBottom({double threshold = 1.0}) { + if (!_scrollController.hasClients) return true; + final currentScroll = _scrollController.offset; + // Allow 1 pixel of error + return (endScroll - currentScroll).abs() <= threshold; + } + + Future _scrollToBottom({bool withDelay = true}) async { + if (_isScrolledToBottom()) { + return; + } + if (_scrollController.hasClients) { + await _scrollController.animateTo( + _scrollController.position.minScrollExtent, + duration: const Duration(milliseconds: 800), + curve: Curves.easeInOutCubic, + ); + } + setState(() { + _stickToBottom = true; + }); + } + + @override + void didUpdateWidget(MessageList oldWidget) { + super.didUpdateWidget(oldWidget); + if (_stickToBottom) { + _scrollToBottom(withDelay: false); + } + if (_userAddedMessage(oldWidget)) { + _scrollToBottom(); + } + } + + bool _userAddedMessage(MessageList oldWidget) { + var currentUserMessages = widget.messages.where((msg) => msg.role == MessageRole.user).toList(); + var oldUserMessages = oldWidget.messages.where((msg) => msg.role == MessageRole.user).toList(); + return currentUserMessages.length != oldUserMessages.length; + } + + @override + void initState() { + super.initState(); + + _scrollController.addListener(() { + final direction = _scrollController.position.userScrollDirection; + if (direction != ScrollDirection.idle && _isScrolledToBottom()) { + setState(() { + _stickToBottom = true; + }); + } + }); + + _scrollDirectionChangedStream.listen((direction) { + if (direction == ScrollDirection.reverse) { + setState(() { + _stickToBottom = false; + }); + } + }); + + _scrollToBottom(); + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return KeyboardVisibilityBuilder( + builder: (context, isKeyboardVisible) { + if (isKeyboardVisible) { + _scrollToBottom(); + } + + // Group messages + List> groupedMessages = []; + List currentGroup = []; + + for (var msg in widget.messages.reversed) { + if (msg.role == MessageRole.user) { + if (currentGroup.isNotEmpty) { + groupedMessages.add(currentGroup); + currentGroup = []; + } + currentGroup.add(msg); + groupedMessages.add(currentGroup); + currentGroup = []; + } else { + currentGroup.insert(0, msg); + } + } + + if (currentGroup.isNotEmpty) { + groupedMessages.add(currentGroup); + } + + return Stack( + children: [ + ListView.builder( + reverse: true, + controller: _scrollController, + padding: const EdgeInsets.all(16.0), + itemCount: groupedMessages.length, + // physics: const ClampingScrollPhysics(), // Disable elastic effect + itemBuilder: (context, index) { + final group = groupedMessages[index]; + + return ChatUIMessage(key: ValueKey(group.first.messageId), messages: group, onRetry: widget.onRetry, onSwitch: widget.onSwitch); + }, + ), + // if (!_isScrolledToBottom()) + // Positioned( + // bottom: 10, + // left: 0, + // right: 0, + // child: Center( + // child: ScrollDownButton( + // onPressed: () { + // _stickToBottom = true; + // _scrollToBottom(withDelay: false); + // }, + // ), + // ), + // ), + ], + ); + }, + ); + } +} diff --git a/lib/page/layout/chat_page/chat_message_to_image.dart b/lib/page/layout/chat_page/chat_message_to_image.dart new file mode 100644 index 0000000..0182c0c --- /dev/null +++ b/lib/page/layout/chat_page/chat_message_to_image.dart @@ -0,0 +1,292 @@ +import 'package:flutter/material.dart'; +import 'dart:io' as io; +import 'package:chatmcp/llm/model.dart'; +import 'chat_message.dart'; +import 'chat_message_action.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:share_plus/share_plus.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:screenshot/screenshot.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; + +class ListViewToImageScreen extends StatefulWidget { + final List messages; + const ListViewToImageScreen({super.key, required this.messages}); + + @override + _ListViewToImageScreenState createState() => _ListViewToImageScreenState(); +} + +class _ListViewToImageScreenState extends State { + final ScrollController _scrollController = ScrollController(); + final screenshotController = ScreenshotController(); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text('Share Chat Image'), + leading: IconButton(icon: Icon(Icons.close), onPressed: () => Navigator.pop(context)), + actions: [IconButton(icon: Icon(Icons.camera), onPressed: _captureListViewAsImage)], + ), + body: ScrollConfiguration( + behavior: ScrollConfiguration.of(context).copyWith( + scrollbars: false, // 完全禁用滚动条 + ), + child: SingleChildScrollView(controller: _scrollController, child: _buildMessage()), + ), + ); + } + + Widget _buildMessage() { + List> groupedMessages = []; + List currentGroup = []; + + for (var msg in widget.messages) { + if (msg.role == MessageRole.user) { + if (currentGroup.isNotEmpty) { + groupedMessages.add(currentGroup); + currentGroup = []; + } + currentGroup.add(msg); + groupedMessages.add(currentGroup); + currentGroup = []; + } else { + currentGroup.add(msg); + } + } + + if (currentGroup.isNotEmpty) { + groupedMessages.add(currentGroup); + } + + // 直接使用屏幕宽度,避免LayoutBuilder约束问题 + final screenWidth = MediaQuery.of(context).size.width; + final horizontalPadding = screenWidth * 0.05; // 使用5%作为padding + + return SizedBox( + width: screenWidth, + child: Padding( + padding: EdgeInsets.symmetric(horizontal: horizontalPadding, vertical: 20), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (ProviderManager.chatProvider.activeChat?.title != null) ...[ + Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Row( + children: [ + Expanded( + child: Text(ProviderManager.chatProvider.activeChat!.title, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + ), + Text("by ChatMcp", style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)), + ], + ), + ), + const Divider(height: 1), + const SizedBox(height: 16), + ], + ...groupedMessages.map((group) { + return ScreenshotChatUIMessage( + messages: group, + availableWidth: screenWidth - (horizontalPadding * 2), + onRetry: (ChatMessage message) {}, + onSwitch: (String messageId) {}, + ); + }), + ], + ), + ), + ); + } + + Future _captureListViewAsImage() async { + try { + final screenWidth = MediaQuery.of(context).size.width; + final theme = Theme.of(context); + + // 调试信息 + Logger.root.info('Screen width: $screenWidth'); + + // 创建一个离屏widget来渲染完整内容 + final renderWidget = Screenshot( + controller: screenshotController, + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + devicePixelRatio: 2.0, // 降低pixelRatio,避免过度缩放 + // 强制设置屏幕尺寸,确保宽度不变 + size: Size(screenWidth, double.infinity), + ), + child: Theme( + data: theme, + child: Material( + color: theme.scaffoldBackgroundColor, + child: SizedBox(width: screenWidth, child: _buildMessage()), + ), + ), + ), + ); + + // 使用Overlay将widget临时添加到屏幕外 + final overlayEntry = OverlayEntry( + builder: (context) => Positioned( + left: -screenWidth - 100, // 确保完全在屏幕外 + top: 0, + child: SizedBox(width: screenWidth, child: renderWidget), + ), + ); + + Overlay.of(context).insert(overlayEntry); + + // 等待widget完全渲染 + await Future.delayed(const Duration(milliseconds: 800)); + + // 捕获图像 + final image = await screenshotController.capture( + pixelRatio: 2.0, // 保持一致的pixelRatio + ); + + // 移除临时widget + overlayEntry.remove(); + + if (image == null) { + Logger.root.severe('截图失败: 无法获取图片'); + return; + } + + if (kIsDesktop) { + final path = await FilePicker.platform.saveFile( + dialogTitle: ProviderManager.chatProvider.activeChat?.title ?? 'Save chat image', + fileName: 'ChatMcp-${ProviderManager.chatProvider.activeChat?.title ?? DateTime.now().millisecondsSinceEpoch}.jpg', + type: FileType.custom, + allowedExtensions: ['jpg'], + ); + if (path != null) { + await io.File(path).writeAsBytes(image); + } + } + + if (kIsMobile) { + final title = ProviderManager.chatProvider.activeChat?.title ?? 'Chat Image'; + final safeTitle = title.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').replaceAll(RegExp(r'\s+'), '_'); + + final tempDir = await getTemporaryDirectory(); + final tempFile = io.File('${tempDir.path}/ChatMcp_${safeTitle}_${DateTime.now().millisecondsSinceEpoch}.jpg'); + await tempFile.writeAsBytes(image); + + await SharePlus.instance.share(ShareParams(files: [XFile(tempFile.path)], subject: "ChatMcp $title")); + } + + if (mounted) { + Navigator.of(context).pop(); + } + } catch (e) { + Logger.root.severe('截图失败: $e'); + } + } +} + +// 专门用于截图的消息组件,避免Flexible导致的宽度压缩 +class ScreenshotChatUIMessage extends StatelessWidget { + final List messages; + final double availableWidth; + final Function(ChatMessage) onRetry; + final Function(String messageId) onSwitch; + + const ScreenshotChatUIMessage({super.key, required this.messages, required this.availableWidth, required this.onRetry, required this.onSwitch}); + + List _filterMessages(List messages) { + if (messages.length <= 1) return messages; + return messages.where((m) => m.role != MessageRole.assistant || (m.role == MessageRole.assistant && m.content != '')).toList(); + } + + BubblePosition _getMessagePosition(int index, int total) { + if (total == 1) return BubblePosition.single; + if (index == 0) return BubblePosition.first; + if (index == total - 1) return BubblePosition.last; + return BubblePosition.middle; + } + + Widget _buildMessageGroup(BuildContext context, List messages, bool isUser) { + final filteredMessages = _filterMessages(messages); + + if (filteredMessages.isEmpty) return const SizedBox(); + + if (filteredMessages.length == 1) { + return ChatMessageContent(message: filteredMessages[0], onRetry: onRetry, position: BubblePosition.single); + } + + return Container( + decoration: BoxDecoration(color: AppColors.getMessageBubbleBackgroundColor(context, isUser), borderRadius: BorderRadius.circular(16)), + child: Column( + crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start, + children: List.generate( + filteredMessages.length, + (index) => Padding( + padding: EdgeInsets.only(bottom: index == filteredMessages.length - 1 ? 0 : 1), + child: ChatMessageContent( + message: filteredMessages[index], + onRetry: onRetry, + position: _getMessagePosition(index, filteredMessages.length), + useTransparentBackground: true, + ), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + if (messages.isEmpty) return const SizedBox(); + + final firstMsg = messages.first; + final isUser = firstMsg.role == MessageRole.user; + + return Consumer( + builder: (context, settings, child) { + final showAssistantAvatar = settings.generalSetting.showAssistantAvatar; + final showUserAvatar = settings.generalSetting.showUserAvatar; + + // 计算头像占用的宽度 + double avatarWidth = 0; + if ((!isUser && showAssistantAvatar) || (isUser && showUserAvatar)) { + avatarWidth = 48; // 40px avatar + 8px spacing + } + + // 为消息内容保留固定宽度 + final messageWidth = availableWidth - avatarWidth; + + return Container( + margin: const EdgeInsets.symmetric(vertical: 6.0), + child: Row( + mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!isUser && showAssistantAvatar) ...[SizedBox(width: 40, child: ChatAvatar(isUser: false)), const SizedBox(width: 8)], + // 使用Container代替Flexible,固定宽度 + SizedBox( + width: messageWidth, + child: Column( + crossAxisAlignment: isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start, + children: [ + _buildMessageGroup(context, messages, isUser), + if (kIsDesktop && messages.last.role != MessageRole.loading && !isUser) + MessageActions(messages: messages, onRetry: onRetry, onSwitch: onSwitch), + ], + ), + ), + if (isUser && showUserAvatar) ...[const SizedBox(width: 8), SizedBox(width: 40, child: ChatAvatar(isUser: true))], + ], + ), + ); + }, + ); + } +} diff --git a/lib/page/layout/chat_page/chat_page.dart b/lib/page/layout/chat_page/chat_page.dart new file mode 100644 index 0000000..60b3e73 --- /dev/null +++ b/lib/page/layout/chat_page/chat_page.dart @@ -0,0 +1,1173 @@ +import 'dart:typed_data'; + +import 'package:chatmcp/llm/prompt.dart'; +import 'package:chatmcp/utils/platform.dart' hide File; +import 'package:flutter/material.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:chatmcp/llm/llm_factory.dart'; +import 'package:chatmcp/llm/base_llm_client.dart'; +import 'package:logging/logging.dart'; +import 'package:file_picker/file_picker.dart'; +import 'input_area.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/utils/file_content.dart'; +import 'package:chatmcp/dao/chat.dart'; +import 'package:uuid/uuid.dart'; +import 'chat_message_list.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'chat_message_to_image.dart'; +import 'package:chatmcp/utils/event_bus.dart'; +import 'chat_code_preview.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'dart:convert'; +import 'package:chatmcp/mcp/models/json_rpc_message.dart'; +import 'dart:async'; + +class ChatPage extends StatefulWidget { + const ChatPage({super.key}); + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + Chat? _chat; + List _messages = []; + bool _isComposing = false; // Indicates if the user is currently composing a message + BaseLLMClient? _llmClient; + String _currentResponse = ''; + bool _isLoading = false; // Indicates if the chat is currently loading or processing a response + String _parentMessageId = ''; // Parent message ID + bool _isCancelled = false; // Indicates if the current operation has been cancelled by the user + bool _isWaiting = false; // Indicates if the system is waiting for a response from the LLM + + // GlobalKey for InputArea to access focus methods + final GlobalKey _inputAreaKey = GlobalKey(); + + // Stores image bytes of the widget for sharing functionality + Uint8List? bytes; + + bool mobile = kIsMobile; + + final List _runFunctionEvents = []; + bool _isRunningFunction = false; + + num _currentLoop = 0; + + // https://stackoverflow.com/questions/51791501/how-to-debounce-textfield-onchange-in-dart + Timer? _debounce; + static const int _chatPageDebounceTime = 100; + + @override + void initState() { + super.initState(); + _initializeState(); + on(_handleShare); + + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_isMobile() != mobile) { + setState(() { + mobile = _isMobile(); + }); + } + if (!mobile && showModalCodePreview) { + setState(() { + Navigator.pop(context); + showModalCodePreview = false; + }); + } + }); + } + + @override + void dispose() { + _debounce?.cancel(); + _removeListeners(); + super.dispose(); + } + + // Initializes state and sets up related methods + void _initializeState() { + _initializeLLMClient(); + _addListeners(); + _initializeHistoryMessages(); + on(_onRunFunction); + } + + Future _onRunFunction(RunFunctionEvent event) async { + setState(() { + _runFunctionEvents.add(event); + }); + + if (!_isLoading) { + _handleSubmitted(SubmitData("", [])); + } + } + + Future _showFunctionApprovalDialog(RunFunctionEvent event) async { + // Determines which MCP server's tool the function belongs to + final clientName = _findClientName(ProviderManager.mcpServerProvider.tools, event.name); + if (clientName == null) return false; + + final serverConfig = await ProviderManager.mcpServerProvider.loadServersAll(); + final servers = serverConfig['mcpServers'] as Map? ?? {}; + + if (servers.containsKey(clientName)) { + final config = servers[clientName] as Map? ?? {}; + final autoApprove = config['auto_approve'] as bool? ?? false; + + // Skips authorization dialog if auto-approve is enabled in server config + if (autoApprove) { + return true; + } + } + + // Verifies component is still mounted before showing dialog + if (!mounted) return false; + + // Displays authorization dialog for function execution + var t = AppLocalizations.of(context)!; + return await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) { + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text(t.functionCallAuth), + content: SingleChildScrollView( + child: ListBody(children: [Text(t.allowFunctionExecution), SizedBox(height: 8), Text(event.name), SizedBox(height: 8)]), + ), + actions: [ + TextButton( + child: Text(t.cancel), + onPressed: () { + setState(() { + _runFunctionEvents.clear(); + }); + Navigator.of(context).pop(false); + }, + ), + TextButton( + child: Text(t.allow), + onPressed: () { + Navigator.of(context).pop(true); + }, + ), + ], + ); + }, + ) ?? + false; + } + + void _addListeners() { + ProviderManager.chatModelProvider.addListener(_initializeLLMClient); + ProviderManager.chatProvider.addListener(_onChatProviderChanged); + } + + void _removeListeners() { + ProviderManager.chatModelProvider.removeListener(_initializeLLMClient); + ProviderManager.chatProvider.removeListener(_onChatProviderChanged); + } + + void _initializeLLMClient() { + _llmClient = LLMFactoryHelper.createFromModel(ProviderManager.chatModelProvider.currentModel); + setState(() {}); + } + + void _onChatProviderChanged() { + _initializeHistoryMessages(); + if (_isMobile() && ProviderManager.chatProvider.showCodePreview && ProviderManager.chatProvider.artifactEvent != null) { + _showMobileCodePreview(); + } else { + setState(() { + _showCodePreview = ProviderManager.chatProvider.showCodePreview; + }); + } + } + + bool _showCodePreview = false; + + List _allMessages = []; + + Future> _getHistoryTreeMessages() async { + final activeChat = ProviderManager.chatProvider.activeChat; + if (activeChat == null) return []; + + Map> messageMap = {}; + + final messages = await activeChat.getChatMessages(); + + for (var message in messages) { + if (message.role == MessageRole.user) { + continue; + } + if (messageMap[message.parentMessageId] == null) { + messageMap[message.parentMessageId] = []; + } + + messageMap[message.parentMessageId]?.add(message.messageId); + } + + for (var message in messages) { + final brotherIds = messageMap[message.messageId] ?? []; + + if (brotherIds.length > 1) { + int index = messages.indexWhere((m) => m.messageId == message.messageId); + if (index != -1) { + messages[index].childMessageIds ??= brotherIds; + } + + for (var brotherId in brotherIds) { + final index = messages.indexWhere((m) => m.messageId == brotherId); + if (index != -1) { + messages[index].brotherMessageIds ??= brotherIds; + } + } + } + } + + setState(() { + _allMessages = messages; + }); + + if (messages.isEmpty) { + return []; + } + + final lastMessage = messages.last; + return _getTreeMessages(lastMessage.messageId, messages); + } + + List _getTreeMessages(String messageId, List messages) { + final lastMessage = messages.firstWhere((m) => m.messageId == messageId); + List treeMessages = []; + + ChatMessage? currentMessage = lastMessage; + while (currentMessage != null) { + if (currentMessage.role != MessageRole.user) { + final childMessageIds = currentMessage.childMessageIds; + if (childMessageIds != null && childMessageIds.isNotEmpty) { + for (var childId in childMessageIds.reversed) { + final childMessage = messages.firstWhere( + (m) => m.messageId == childId, + orElse: () => ChatMessage(content: '', role: MessageRole.user), + ); + if (treeMessages.any((m) => m.messageId == childMessage.messageId)) { + continue; + } + treeMessages.insert(0, childMessage); + } + } + } + + treeMessages.insert(0, currentMessage); + + final parentId = currentMessage.parentMessageId; + if (parentId.isEmpty) break; + + currentMessage = messages.firstWhere( + (m) => m.messageId == parentId, + orElse: () => ChatMessage(messageId: '', content: '', role: MessageRole.user, parentMessageId: ''), + ); + + if (currentMessage.messageId.isEmpty) break; + } + + ChatMessage? nextMessage = messages + .where((m) => m.role == MessageRole.user) + .firstWhere( + (m) => m.parentMessageId == lastMessage.messageId, + orElse: () => ChatMessage(messageId: '', content: '', role: MessageRole.user), + ); + + while (nextMessage != null && nextMessage.messageId.isNotEmpty) { + if (!treeMessages.any((m) => m.messageId == nextMessage!.messageId)) { + treeMessages.add(nextMessage); + } + final childMessageIds = nextMessage.childMessageIds; + if (childMessageIds != null && childMessageIds.isNotEmpty) { + for (var childId in childMessageIds) { + final childMessage = messages.firstWhere( + (m) => m.messageId == childId, + orElse: () => ChatMessage(messageId: '', content: '', role: MessageRole.user), + ); + if (treeMessages.any((m) => m.messageId == childMessage.messageId)) { + continue; + } + treeMessages.add(childMessage); + } + } + + nextMessage = messages.firstWhere( + (m) => m.parentMessageId == nextMessage!.messageId, + orElse: () => ChatMessage(messageId: '', content: '', role: MessageRole.user), + ); + } + + return treeMessages; + } + + // Message processing related methods + Future _initializeHistoryMessages() async { + final activeChat = ProviderManager.chatProvider.activeChat; + if (activeChat == null && _messages.isEmpty) { + setState(() { + _messages = []; + _chat = null; + _parentMessageId = ''; + }); + _resetState(); + // Auto focus input on desktop when creating new chat + if (!kIsMobile) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _inputAreaKey.currentState?.requestFocus(); + }); + } + return; + } + if (_chat?.id != activeChat?.id) { + final messages = await _getHistoryTreeMessages(); + // Find the index of the last user message + final lastUserIndex = messages.lastIndexWhere((m) => m.role == MessageRole.user); + String parentId = ''; + + // If a user message is found, and there is an assistant message after it, use the ID of the assistant message + if (lastUserIndex != -1 && lastUserIndex + 1 < messages.length) { + parentId = messages[lastUserIndex + 1].messageId; + } else if (messages.isNotEmpty) { + // If no suitable message is found, use the ID of the last message + parentId = messages.last.messageId; + } + + ProviderManager.chatProvider.clearArtifactEvent(); + + setState(() { + _messages = messages; + _chat = activeChat; + _parentMessageId = parentId; + }); + _resetState(); + // Auto focus input on desktop when switching to a different chat + if (!kIsMobile) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _inputAreaKey.currentState?.requestFocus(); + }); + } + } + } + + // UI building related methods + Widget _buildMessageList() { + if (_messages.isEmpty) { + final l10n = AppLocalizations.of(context)!; + return Expanded( + child: Container( + color: AppColors.transparent, + child: Center( + child: Text(l10n.welcomeMessage, style: TextStyle(fontSize: 18, color: AppColors.getWelcomeMessageColor())), + ), + ), + ); + } + + final parentMsgIndex = _messages.length - 1; + for (var i = 0; i < parentMsgIndex; i++) { + if (_messages[i].content?.contains('>> tools, String toolName) { + for (var entry in tools.entries) { + final clientTools = entry.value; + if (clientTools.any((tool) => tool['name'] == toolName)) { + return entry.key; + } + } + return null; + } + + Future _sendToolCallAndProcessResponse(String toolName, Map toolArguments) async { + final clientName = _findClientName(ProviderManager.mcpServerProvider.tools, toolName); + if (clientName == null) { + Logger.root.severe('No MCP server found for tool: $toolName'); + return; + } + + final mcpClient = ProviderManager.mcpServerProvider.getClient(clientName); + if (mcpClient == null) { + Logger.root.severe('No MCP client found for tool: $toolName'); + return; + } + + // Configures tool call with timeout and retry mechanism + const int maxRetries = 3; + const Duration timeout = Duration(seconds: 60 * 5); + + JSONRPCMessage? response; + String? lastError; + + for (int attempt = 0; attempt < maxRetries; attempt++) { + try { + Logger.root.info('send tool call attempt ${attempt + 1}/$maxRetries - name: $toolName arguments: $toolArguments'); + + response = await mcpClient.sendToolCall(name: toolName, arguments: toolArguments).timeout(timeout); + + // Exits retry loop on successful response + break; + } catch (e) { + lastError = e.toString(); + Logger.root.warning('tool call attempt ${attempt + 1}/$maxRetries failed: $e'); + + // Implements exponential backoff before next retry attempt + if (attempt < maxRetries - 1) { + final delay = Duration(seconds: (attempt + 1) * 2); // Incremental delay + Logger.root.info('waiting ${delay.inSeconds}s before retry...'); + await Future.delayed(delay); + } + } + } + + // Logs error and updates UI when all retry attempts fail + if (response == null) { + Logger.root.severe('Tool call failed after $maxRetries attempts: $lastError'); + setState(() { + _parentMessageId = _messages.last.messageId; + final msgId = Uuid().v4(); + _messages.add( + ChatMessage( + messageId: msgId, + content: '\n failed to call function: $lastError\n', + role: MessageRole.assistant, + name: toolName, + parentMessageId: _parentMessageId, + ), + ); + _parentMessageId = msgId; + }); + return; + } + + Logger.root.info('Tool call success - name: $toolName arguments: $toolArguments response: $response'); + + setState(() { + _currentResponse = response!.result['content'].toString(); + if (_currentResponse.isNotEmpty) { + _parentMessageId = _messages.last.messageId; + final msgId = Uuid().v4(); + _messages.add( + ChatMessage( + messageId: msgId, + content: '\n$_currentResponse\n', + role: MessageRole.assistant, + name: toolName, + parentMessageId: _parentMessageId, + ), + ); + _parentMessageId = msgId; + } + }); + } + + ChatMessage? _findUserMessage(ChatMessage message) { + final parentMessage = _messages.firstWhere( + (m) => m.messageId == message.parentMessageId, + orElse: () => ChatMessage(messageId: '', content: '', role: MessageRole.user), + ); + + if (parentMessage.messageId.isEmpty) return null; + + if (parentMessage.role != MessageRole.user) { + return _findUserMessage(parentMessage); + } + + return parentMessage; + } + + Future _onRetry(ChatMessage message) async { + final userMessage = _findUserMessage(message); + if (userMessage == null) return; + + final messageIndex = _messages.indexOf(userMessage); + if (messageIndex == -1) return; + + final previousMessages = _messages.sublist(0, messageIndex + 1); + + setState(() { + _messages = previousMessages; + _parentMessageId = userMessage.messageId; + _isLoading = true; + }); + + await _handleSubmitted( + SubmitData(userMessage.content ?? '', (userMessage.files ?? []).map((f) => f as PlatformFile).toList()), + addUserMessage: false, + ); + } + + /// function calling style tool use + Future _checkNeedToolCallFunction() async { + if (_runFunctionEvents.isNotEmpty) return true; + + final lastMessage = _messages.last; + + final content = lastMessage.content ?? ''; + if (content.isEmpty) return false; + + final messages = _messages.toList(); + + Logger.root.info('check need tool call: $messages'); + + final result = await _llmClient!.checkToolCall( + ProviderManager.chatModelProvider.currentModel.name, + CompletionRequest(model: ProviderManager.chatModelProvider.currentModel.name, messages: [..._prepareMessageList()]), + ProviderManager.mcpServerProvider.tools, + ); + final needToolCall = result['need_tool_call'] ?? false; + + if (!needToolCall) { + return false; + } + + final toolCalls = result['tool_calls'] as List; + for (var toolCall in toolCalls) { + final functionEvent = RunFunctionEvent(toolCall['name'], toolCall['arguments']); + + _runFunctionEvents.add(functionEvent); + + _messages.add( + ChatMessage( + content: "\n${jsonEncode(functionEvent.arguments)}\n", + role: MessageRole.assistant, + parentMessageId: _parentMessageId, + ), + ); + + _onRunFunction(functionEvent); + } + + return needToolCall; + } + + /// xml style function calling tool use + Future _checkNeedToolCallXml() async { + if (_runFunctionEvents.isNotEmpty) return true; + + final lastMessage = _messages.last; + if (lastMessage.role == MessageRole.user) return true; + + final content = lastMessage.content ?? ''; + if (content.isEmpty) return false; + + // Parses function call tags in format args + final RegExp functionTagRegex = RegExp('(.*?)', dotAll: true); + final matches = functionTagRegex.allMatches(content); + + if (matches.isEmpty) return false; + + for (var match in matches) { + final toolName = match.group(1); + final toolArguments = match.group(2); + + if (toolName == null || toolArguments == null) continue; + + try { + // Cleans and parses tool arguments by removing whitespace and newlines + final cleanedToolArguments = toolArguments.replaceAll('\n', ' ').replaceAll(RegExp(r'\s+'), ' ').trim(); + final toolArgumentsMap = jsonDecode(cleanedToolArguments); + _onRunFunction(RunFunctionEvent(toolName, toolArgumentsMap)); + } catch (e) { + Logger.root.warning('Failed to parse tool parameters: $e'); + } + } + + return _runFunctionEvents.isNotEmpty; + } + + Future _checkNeedToolCall() async { + return await _checkNeedToolCallXml(); + } + + // Message submission processing + Future _handleSubmitted(SubmitData data, {bool addUserMessage = true}) async { + setState(() { + _isCancelled = false; + }); + final files = data.files.map((file) => platformFileToFile(file)).toList(); + + if (addUserMessage && data.text.isNotEmpty) { + _addUserMessage(data.text, files); + } + + try { + final generalSetting = ProviderManager.settingsProvider.generalSetting; + final maxLoops = generalSetting.maxLoops; + + while (await _checkNeedToolCall()) { + if (_currentLoop > maxLoops) { + Logger.root.warning('reach max loops: $maxLoops'); + break; + } + + if (_runFunctionEvents.isNotEmpty) { + // Processes function calls in sequential order + while (_runFunctionEvents.isNotEmpty) { + final event = _runFunctionEvents.first; + + // Requests user authorization + final approved = await _showFunctionApprovalDialog(event); + + if (approved) { + setState(() { + _isRunningFunction = true; + }); + + await _sendToolCallAndProcessResponse(event.name, event.arguments); + setState(() { + _isRunningFunction = false; + }); + _runFunctionEvents.removeAt(0); + } else { + setState(() { + _runFunctionEvents.clear(); + }); + final msgId = Uuid().v4(); + _messages.add( + ChatMessage(messageId: msgId, content: 'call function rejected', role: MessageRole.assistant, parentMessageId: _parentMessageId), + ); + _parentMessageId = msgId; + break; + } + } + } + + await _processLLMResponse(); + _currentLoop++; + } + await _updateChat(); + } catch (e, stackTrace) { + _handleError(e, stackTrace); + await _updateChat(); + } + + setState(() { + _isLoading = false; + }); + // Auto focus input on desktop when response completes + if (!kIsMobile) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _inputAreaKey.currentState?.requestFocus(); + }); + } + } + + void _addUserMessage(String text, List files) { + setState(() { + _isLoading = true; + _isComposing = false; + final msgId = Uuid().v4(); + _messages.add( + ChatMessage( + messageId: msgId, + parentMessageId: _parentMessageId, + content: text.replaceAll('\n', '\n\n'), + role: MessageRole.user, + files: files, + ), + ); + _parentMessageId = msgId; + }); + } + + Future _getSystemPrompt() async { + // return ProviderManager.settingsProvider.generalSetting.systemPrompt; + + final promptGenerator = SystemPromptGenerator(); + + var tools = >[]; + for (var entry in ProviderManager.mcpServerProvider.tools.entries) { + if (ProviderManager.serverStateProvider.isEnabled(entry.key)) { + tools.addAll(entry.value); + } + } + + return promptGenerator.generatePrompt(tools: tools); + } + + Future _processLLMResponse() async { + setState(() { + _isWaiting = true; + }); + + List messageList = _prepareMessageList(); + + final modelSetting = ProviderManager.settingsProvider.modelSetting; + final generalSetting = ProviderManager.settingsProvider.generalSetting; + + // Limit the number of messages + final maxMessages = generalSetting.maxMessages; + if (messageList.length > maxMessages) { + // Maintains only the most recent messages up to maxMessages limit + messageList = messageList.sublist(messageList.length - maxMessages); + } + + // Converts assistant's function call results to user role for proper context + for (var message in messageList) { + if (message.role == MessageRole.assistant && message.content?.contains('done="true"') == true) { + messageList[messageList.indexOf(message)] = message.copyWith(content: message.content?.replaceAll('done="true"', '')); + } + if (message.role == MessageRole.assistant && message.content?.startsWith('', '') + .replaceAll('', ''), + ); + } + } + + var messageList0 = messageMerge(messageList); + + if (messageList0.isNotEmpty && messageList0.last.role == MessageRole.assistant) { + messageList0.add(ChatMessage(content: 'continue', role: MessageRole.user)); + } + + final systemPrompt = await _getSystemPrompt(); + + Logger.root.info('Start processing LLM response: $messageList0'); + + final stream = _llmClient!.chatStreamCompletion( + CompletionRequest( + model: ProviderManager.chatModelProvider.currentModel.name, + messages: [ + ChatMessage(content: systemPrompt, role: MessageRole.system), + ...messageList0, + ], + modelSetting: modelSetting, + ), + ); + + _initializeAssistantResponse(); + await _processResponseStream(stream); + Logger.root.info('End processing LLM response'); + } + + List _prepareMessageList() { + final List messageList = _messages + .map((m) => ChatMessage(role: m.role, content: m.content, toolCallId: m.toolCallId, name: m.name, toolCalls: m.toolCalls, files: m.files)) + .toList(); + + _reorderMessages(messageList); + return messageList; + } + + List messageMerge(List messageList) { + if (messageList.isEmpty) return []; + + final newMessages = [messageList.first]; + + for (final message in messageList.sublist(1)) { + if (newMessages.isNotEmpty && newMessages.last.role == message.role) { + String content = message.content ?? ''; + + newMessages.last = newMessages.last.copyWith(content: '${newMessages.last.content}\n\n$content'); + } else { + newMessages.add(message); + } + } + + if (newMessages.isNotEmpty && newMessages.last.role != MessageRole.user) { + newMessages.add(ChatMessage(content: 'continue', role: MessageRole.user)); + } + + return newMessages; + } + + void _reorderMessages(List messageList) { + for (int i = 0; i < messageList.length - 1; i++) { + if (messageList[i].role == MessageRole.user && messageList[i + 1].role == MessageRole.tool) { + final temp = messageList[i]; + messageList[i] = messageList[i + 1]; + messageList[i + 1] = temp; + i++; + } + } + } + + void _initializeAssistantResponse() { + setState(() { + _currentResponse = ''; + _messages.add(ChatMessage(content: _currentResponse, role: MessageRole.assistant, parentMessageId: _parentMessageId)); + }); + } + + Future _processResponseStream(Stream stream) async { + bool isFirstChunk = true; + LLMResponse? lastChunk; + await for (final chunk in stream) { + if (isFirstChunk) { + setState(() { + _isWaiting = false; + }); + isFirstChunk = false; + } + if (_isCancelled) break; + _currentResponse += chunk.content ?? ''; + if (_messages.isNotEmpty) { + _messages.last = _messages.last.copyWith(content: _currentResponse); + } + + if (_debounce?.isActive ?? false) _debounce!.cancel(); + _debounce = Timer(const Duration(milliseconds: _chatPageDebounceTime), () { + if (mounted) { + setState(() {}); + } + }); + lastChunk = chunk; + } + + if (lastChunk?.tokenUsage != null) { + _messages.last = _messages.last.copyWith(tokenUsage: lastChunk?.tokenUsage); + } + + _debounce?.cancel(); + if (mounted) { + setState(() {}); + } + + _isCancelled = false; + } + + Future _updateChat() async { + if (ProviderManager.chatProvider.activeChat == null) { + await _createNewChat(); + } else { + await _updateExistingChat(); + } + } + + Future _createNewChat() async { + if (_messages.isEmpty) return; + + String title; + try { + title = await _llmClient!.genTitle([if (_messages.isNotEmpty) _messages.first, if (_messages.length > 1) _messages.last else _messages.first]); + } catch (e) { + Logger.root.warning('Failed to generate title: $e'); + // Creates fallback title from user message if title generation fails + final userMessage = _messages.isNotEmpty ? _messages.first.content ?? '' : ''; + title = _generateFallbackTitle(userMessage); + } + + await ProviderManager.chatProvider.createChat(Chat(title: title), _handleParentMessageId(_messages)); + Logger.root.info('Created new chat: $title'); + } + + String _generateFallbackTitle(String userMessage) { + if (userMessage.isEmpty) { + return 'new chat'; + } + + // Creates title by truncating first 20 characters of user message + String title = userMessage.replaceAll('\n', ' ').trim(); + if (title.length > 20) { + title = '${title.substring(0, 17)}...'; + } + + return title.isEmpty ? 'new chat' : title; + } + + // Handles parent message ID assignment for conversation thread + List _handleParentMessageId(List messages) { + if (messages.isEmpty) return []; + + // Locates the last user message to establish conversation thread + int lastUserIndex = messages.lastIndexWhere((m) => m.role == MessageRole.user); + if (lastUserIndex == -1) return messages; + + // Retrieves conversation thread starting from last user message + List relevantMessages = messages.sublist(lastUserIndex); + + // Resets parent IDs for long threads to maintain proper conversation flow + if (relevantMessages.length > 2) { + String secondMessageId = relevantMessages[1].messageId; + for (int i = 2; i < relevantMessages.length; i++) { + relevantMessages[i] = relevantMessages[i].copyWith(parentMessageId: secondMessageId); + } + } + + return relevantMessages; + } + + Future _updateExistingChat() async { + final activeChat = ProviderManager.chatProvider.activeChat!; + await ProviderManager.chatProvider.updateChat( + Chat(id: activeChat.id!, title: activeChat.title, createdAt: activeChat.createdAt, updatedAt: DateTime.now()), + ); + + await ProviderManager.chatProvider.addChatMessage(activeChat.id!, _handleParentMessageId(_messages)); + } + + void _handleError(dynamic error, StackTrace stackTrace) { + Logger.root.severe('Error: $error'); + Logger.root.severe('Stack trace: $stackTrace'); + + // Extracts detailed error information for debugging purposes + if (error is TypeError) { + Logger.root.severe('Type error: ${error.toString()}'); + } + + // Resets all state variables to their initial values + _resetState(); + + if (mounted) { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Row( + children: [ + Icon(Icons.error_outline, color: AppColors.getErrorIconColor()), + const SizedBox(width: 8), + Text(AppLocalizations.of(context)!.error), + ], + ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _getUserFriendlyErrorMessage(error), + style: TextStyle(fontWeight: FontWeight.bold, color: AppColors.getErrorTextColor()), + ), + const SizedBox(height: 8), + Text('error type: ${error.runtimeType}', style: TextStyle(fontSize: 12, color: AppColors.getErrorTextColor().withAlpha(128))), + if (error is LLMException) + Text(error.toString(), style: TextStyle(fontSize: 12, color: AppColors.getErrorTextColor().withAlpha(128))), + ], + ), + ), + actions: [TextButton(onPressed: () => Navigator.of(context).pop(), child: Text(AppLocalizations.of(context)!.close))], + ); + }, + ); + } + } + + // Formats error messages for user display + String _getUserFriendlyErrorMessage(dynamic error) { + final errorMap = { + 'connection': AppLocalizations.of(context)!.networkError, + 'timeout': AppLocalizations.of(context)!.timeoutError, + 'permission': AppLocalizations.of(context)!.permissionError, + 'cancelled': AppLocalizations.of(context)!.userCancelledToolCall, + 'No element': AppLocalizations.of(context)!.noElementError, + 'not found': AppLocalizations.of(context)!.notFoundError, + 'invalid': AppLocalizations.of(context)!.invalidError, + 'unauthorized': AppLocalizations.of(context)!.unauthorizedError, + }; + + for (final entry in errorMap.entries) { + if (error.toString().toLowerCase().contains(entry.key.toLowerCase())) { + return entry.value; + } + } + return AppLocalizations.of(context)!.unknownError; + } + + // Handles chat export functionality + Future _handleShare(ShareEvent event) async { + if (_messages.isEmpty) return; + await Future.delayed(const Duration(milliseconds: 100)); + if (mounted) { + if (kIsMobile) { + Navigator.push(context, MaterialPageRoute(builder: (context) => ListViewToImageScreen(messages: _messages))); + } else { + showDialog( + context: context, + builder: (context) => ListViewToImageScreen(messages: _messages), + ); + } + } + } + + bool _isMobile() { + final height = MediaQuery.of(context).size.height; + final width = MediaQuery.of(context).size.width; + return height > width; + } + + void _resetState() { + setState(() { + _isRunningFunction = false; + _runFunctionEvents.clear(); + _isLoading = false; + _isCancelled = false; + _isWaiting = false; + _currentLoop = 0; + }); + // Auto focus input on desktop when state resets + if (!kIsMobile) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _inputAreaKey.currentState?.requestFocus(); + }); + } + } + + void _handleCancel() { + _resetState(); + setState(() { + _isCancelled = true; + }); + } + + bool showModalCodePreview = false; + void _showMobileCodePreview() { + if (showModalCodePreview) { + return; + } + setState(() { + showModalCodePreview = true; + }); + + const txtNoCodePreview = Text('No code preview', style: TextStyle(fontSize: 14, color: Colors.grey)); + + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (BuildContext context) { + return Container( + decoration: BoxDecoration( + color: Theme.of(context).scaffoldBackgroundColor, + borderRadius: const BorderRadius.vertical(top: Radius.circular(20)), + ), + child: DraggableScrollableSheet( + initialChildSize: 0.9, + minChildSize: 0.3, + maxChildSize: 0.9, + expand: false, + builder: (context, scrollController) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 40, + height: 4, + margin: const EdgeInsets.symmetric(vertical: 16), + decoration: BoxDecoration(color: AppColors.getBottomSheetHandleColor(context), borderRadius: BorderRadius.circular(2)), + ), + Expanded( + child: ProviderManager.chatProvider.artifactEvent != null + ? ChatCodePreview(codePreviewEvent: ProviderManager.chatProvider.artifactEvent!) + : Center(child: txtNoCodePreview), + ), + ], + ); + }, + ), + ); + }, + ).whenComplete(() { + setState(() { + showModalCodePreview = false; + }); + ProviderManager.chatProvider.clearArtifactEvent(); + }); + } + + Widget _buildFunctionRunning() { + if (_isRunningFunction) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor)), + ), + const SizedBox(width: 12), + Text( + AppLocalizations.of(context)!.functionRunning, + style: TextStyle(fontSize: 14, color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha((0.7 * 255).round())), + ), + ], + ), + ); + } + return const SizedBox.shrink(); + } + + @override + Widget build(BuildContext context) { + if (mobile) { + return Column( + children: [ + _buildMessageList(), + _buildFunctionRunning(), + InputArea( + key: _inputAreaKey, + disabled: _isLoading, + isComposing: _isComposing, + onTextChanged: _handleTextChanged, + onSubmitted: _handleSubmitted, + onCancel: _handleCancel, + ), + ], + ); + } + + return Row( + children: [ + Expanded( + flex: 1, + child: Column( + children: [ + _buildMessageList(), + _buildFunctionRunning(), + InputArea( + key: _inputAreaKey, + disabled: _isLoading, + isComposing: _isComposing, + onTextChanged: _handleTextChanged, + onSubmitted: _handleSubmitted, + onCancel: _handleCancel, + ), + ], + ), + ), + if (!mobile && _showCodePreview && ProviderManager.chatProvider.artifactEvent != null) + Expanded(flex: 2, child: ChatCodePreview(codePreviewEvent: ProviderManager.chatProvider.artifactEvent!)), + ], + ); + } +} diff --git a/lib/page/layout/chat_page/input_area.dart b/lib/page/layout/chat_page/input_area.dart new file mode 100644 index 0000000..e6cbf79 --- /dev/null +++ b/lib/page/layout/chat_page/input_area.dart @@ -0,0 +1,363 @@ +import 'package:chatmcp/page/layout/widgets/mcp_tools.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:chatmcp/widgets/upload_menu.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/page/layout/widgets/conv_setting.dart'; + +class SubmitData { + final String text; + final List files; + + SubmitData(this.text, this.files); + + @override + String toString() { + return 'SubmitData(text: $text, files: $files)'; + } +} + +class InputArea extends StatefulWidget { + final bool isComposing; + final bool disabled; + final ValueChanged onTextChanged; + final ValueChanged onSubmitted; + final VoidCallback? onCancel; + final ValueChanged>? onFilesSelected; + final bool autoFocus; + + const InputArea({ + super.key, + required this.isComposing, + required this.disabled, + required this.onTextChanged, + required this.onSubmitted, + this.onFilesSelected, + this.onCancel, + this.autoFocus = false, + }); + + @override + State createState() => InputAreaState(); +} + +class InputAreaState extends State { + List _selectedFiles = []; + final TextEditingController textController = TextEditingController(); + final FocusNode _focusNode = FocusNode(); + bool _isImeComposing = false; + + @override + void initState() { + super.initState(); + // Auto focus on desktop when autoFocus is true + if (!kIsMobile && widget.autoFocus) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _focusNode.requestFocus(); + } + }); + } + } + + @override + void didUpdateWidget(InputArea oldWidget) { + super.didUpdateWidget(oldWidget); + // Auto focus on desktop when autoFocus changes to true + if (!kIsMobile && widget.autoFocus && !oldWidget.autoFocus) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _focusNode.requestFocus(); + } + }); + } + } + + @override + void dispose() { + _focusNode.dispose(); + super.dispose(); + } + + void requestFocus() { + if (!kIsMobile && mounted) { + _focusNode.requestFocus(); + } + } + + Future _pickFiles() async { + try { + final result = await FilePicker.platform.pickFiles(allowMultiple: true, type: FileType.any); + + if (result != null && result.files.isNotEmpty) { + setState(() { + _selectedFiles = [..._selectedFiles, ...result.files]; + }); + widget.onFilesSelected?.call(_selectedFiles); + } + } catch (e) { + debugPrint('Error picking files: $e'); + } + } + + Future _pickImages() async { + try { + final result = await FilePicker.platform.pickFiles(allowMultiple: true, type: FileType.image); + + if (result != null && result.files.isNotEmpty) { + setState(() { + _selectedFiles = [..._selectedFiles, ...result.files]; + }); + widget.onFilesSelected?.call(_selectedFiles); + } + } catch (e) { + debugPrint('Error picking images: $e'); + } + } + + void _removeFile(int index) { + setState(() { + _selectedFiles.removeAt(index); + }); + widget.onFilesSelected?.call(_selectedFiles); + } + + void _afterSubmitted() { + textController.clear(); + _selectedFiles.clear(); + } + + String _truncateFileName(String fileName) { + const int maxLength = 20; + if (fileName.length <= maxLength) return fileName; + + final extension = fileName.contains('.') ? '.${fileName.split('.').last}' : ''; + final nameWithoutExt = fileName.contains('.') ? fileName.substring(0, fileName.lastIndexOf('.')) : fileName; + + if (nameWithoutExt.length <= maxLength - extension.length - 3) { + return fileName; + } + + final truncatedLength = (maxLength - extension.length - 3) ~/ 2; + return '${nameWithoutExt.substring(0, truncatedLength)}' + '...' + '${nameWithoutExt.substring(nameWithoutExt.length - truncatedLength)}' + '$extension'; + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Container( + decoration: BoxDecoration( + // color: Theme.of(context).cardColor, + color: AppColors.getInputAreaBackgroundColor(context), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppColors.getInputAreaBorderColor(context), width: 1), + ), + margin: const EdgeInsets.only(left: 12.0, right: 12.0, top: 2.0, bottom: 8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (_selectedFiles.isNotEmpty) + Container( + padding: const EdgeInsets.only(left: 12.0, right: 12.0, top: 8.0), + constraints: const BoxConstraints(maxHeight: 65), + width: double.infinity, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: _selectedFiles.asMap().entries.map((entry) { + final index = entry.key; + final file = entry.value; + final isImage = + file.extension?.toLowerCase() == 'jpg' || + file.extension?.toLowerCase() == 'jpeg' || + file.extension?.toLowerCase() == 'png' || + file.extension?.toLowerCase() == 'gif'; + + return Padding( + padding: const EdgeInsets.only(right: 8.0), + child: Container( + decoration: BoxDecoration( + color: AppColors.getInputAreaFileItemBackgroundColor(context), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: AppColors.getInputAreaBorderColor(context), width: 1), + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0), + child: Row( + children: [ + Icon( + isImage ? Icons.image : Icons.insert_drive_file, + size: 16, + color: AppColors.getInputAreaFileIconColor(context), + ), + const SizedBox(width: 6), + Text( + _truncateFileName(file.name), + style: TextStyle(fontSize: 12, color: Theme.of(context).textTheme.bodyMedium?.color), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + Material( + color: Colors.transparent, + child: InkWell( + onTap: () => _removeFile(index), + borderRadius: const BorderRadius.only(topRight: Radius.circular(8), bottomRight: Radius.circular(8)), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6.0, vertical: 6.0), + child: Icon(Icons.close, size: 14, color: AppColors.getInputAreaIconColor(context)), + ), + ), + ), + ], + ), + ), + ); + }).toList(), + ), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0), + child: Container( + decoration: BoxDecoration(color: AppColors.getInputAreaBackgroundColor(context)), + child: Focus( + onKeyEvent: (node, event) { + if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.enter) { + if (HardwareKeyboard.instance.isShiftPressed) { + return KeyEventResult.ignored; + } + + if (_isImeComposing) { + return KeyEventResult.ignored; + } + + if (widget.isComposing && textController.text.trim().isNotEmpty) { + widget.onSubmitted(SubmitData(textController.text, _selectedFiles)); + _afterSubmitted(); + } + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: TextField( + enabled: !widget.disabled, + controller: textController, + focusNode: _focusNode, + onChanged: widget.onTextChanged, + maxLines: 5, + minLines: 1, + onAppPrivateCommand: (value, map) { + debugPrint('onAppPrivateCommand: $value'); + }, + buildCounter: (context, {required currentLength, required isFocused, maxLength}) { + return null; + }, + textInputAction: kIsMobile ? TextInputAction.newline : TextInputAction.done, + onSubmitted: null, + inputFormatters: [ + TextInputFormatter.withFunction((oldValue, newValue) { + _isImeComposing = newValue.composing != TextRange.empty; + return newValue; + }), + ], + keyboardType: TextInputType.multiline, + style: TextStyle(fontSize: 14.0, color: AppColors.getInputAreaTextColor(context)), + scrollPhysics: const BouncingScrollPhysics(), + decoration: InputDecoration( + hintText: l10n.askMeAnything, + hintStyle: TextStyle(fontSize: 14.0, color: AppColors.getInputAreaHintTextColor(context)), + filled: true, + fillColor: AppColors.getInputAreaBackgroundColor(context), + hoverColor: Colors.transparent, + border: InputBorder.none, + contentPadding: const EdgeInsets.symmetric(horizontal: 0, vertical: 10), + isDense: true, + ), + cursorColor: AppColors.getInputAreaCursorColor(context), + mouseCursor: WidgetStateMouseCursor.textable, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.only(left: 12.0, right: 12.0, bottom: 6.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + if (!widget.disabled) + Row( + children: [ + FutureBuilder( + future: ProviderManager.mcpServerProvider.installedServersCount, + builder: (context, snapshot) { + return const McpTools(); + }, + ), + const SizedBox(width: 10), + if (kIsMobile) ...[ + UploadMenu(disabled: widget.disabled, onPickImages: _pickImages, onPickFiles: _pickFiles), + ] else ...[ + InkIcon( + icon: CupertinoIcons.plus_app, + onTap: () { + if (widget.disabled) return; + _pickFiles(); + }, + disabled: widget.disabled, + hoverColor: Theme.of(context).hoverColor, + tooltip: AppLocalizations.of(context)!.uploadFile, + ), + ], + const SizedBox(width: 10), + const ConvSetting(), + ], + ), + if (!widget.disabled) ...[ + const Spacer(), + InkIcon( + icon: CupertinoIcons.arrow_up_circle, + onTap: () { + if (widget.disabled || textController.text.trim().isEmpty) { + return; + } + widget.onSubmitted(SubmitData(textController.text, _selectedFiles)); + _afterSubmitted(); + }, + tooltip: AppLocalizations.of(context)!.send, + ), + ] else ...[ + const Spacer(), + InkIcon( + icon: CupertinoIcons.stop, + onTap: widget.onCancel != null + ? () { + widget.onCancel!(); + } + : null, + tooltip: AppLocalizations.of(context)!.cancel, + ), + ], + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/page/layout/chat_page/scroll_down_button.dart b/lib/page/layout/chat_page/scroll_down_button.dart new file mode 100644 index 0000000..263aed4 --- /dev/null +++ b/lib/page/layout/chat_page/scroll_down_button.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; + +class ScrollDownButton extends StatelessWidget { + final VoidCallback onPressed; + + const ScrollDownButton({required this.onPressed, super.key}); + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 30, + width: 30, + child: Container( + decoration: BoxDecoration(color: Theme.of(context).colorScheme.onSurface.withAlpha(50), shape: BoxShape.circle), + child: IconButton(padding: EdgeInsets.zero, icon: const Icon(Icons.keyboard_arrow_down, size: 20), onPressed: onPressed), + ), + ); + } +} diff --git a/lib/page/layout/layout.dart b/lib/page/layout/layout.dart new file mode 100644 index 0000000..8a8f5d5 --- /dev/null +++ b/lib/page/layout/layout.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:provider/provider.dart'; + +import './chat_page/chat_page.dart'; +import 'sidebar.dart'; +import './widgets/top_toolbar.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/provider/chat_model_provider.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:keyboard_dismisser/keyboard_dismisser.dart'; +import 'package:chatmcp/page/setting/setting.dart'; + +class LayoutPage extends StatefulWidget { + const LayoutPage({super.key}); + + @override + State createState() => _LayoutPageState(); +} + +class _LayoutPageState extends State { + bool hideSidebar = false; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) async { + final llms = await ProviderManager.settingsProvider.loadSettings(); + if (llms.isNotEmpty) { + } else if (mounted) { + _showSettingsDialog(context); + } + }); + } + + void _handleWindowResize(BuildContext context) { + final width = MediaQuery.of(context).size.width; + if (width < 500 && !hideSidebar) { + setState(() { + hideSidebar = true; + }); + } + } + + void _toggleSidebar() { + setState(() { + hideSidebar = !hideSidebar; + }); + } + + void _showSettingsDialog(BuildContext context) { + if (kIsMobile) { + Navigator.push(context, MaterialPageRoute(builder: (context) => const SettingPage())); + } else { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + child: const SettingPage(), + ), + ), + ); + } + } + + Widget _buildLayout() { + return Scaffold( + backgroundColor: AppColors.getLayoutBackgroundColor(context), + drawer: (kIsMobile || (kIsBrowser && MediaQuery.of(context).size.width < 768)) + ? Builder( + builder: (BuildContext context) => Theme( + data: Theme.of(context), + child: Container( + width: 250, + color: AppColors.getThemeBackgroundColor(context), + child: SafeArea(child: SidebarPanel(onToggle: () {})), + ), + ), + ) + : null, + body: SafeArea( + child: Row( + children: [ + if ((kIsDesktop || kIsWeb) && !hideSidebar) + Container( + width: 250, + color: AppColors.getSidebarBackgroundColor(context), + child: SidebarPanel(onToggle: _toggleSidebar), + ), + Expanded( + child: Column( + children: [ + TopToolbar(hideSidebar: hideSidebar, onToggleSidebar: _toggleSidebar), + Expanded(child: ChatPage()), + ], + ), + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + if (kIsDesktop || kIsWeb) { + _handleWindowResize(context); + } + + return Consumer( + builder: (context, chatModelProvider, child) { + return kIsMobile + ? KeyboardDismisser(gestures: [GestureType.onTap, GestureType.onPanUpdateDownDirection], child: _buildLayout()) + : _buildLayout(); + }, + ); + } +} diff --git a/lib/page/layout/sidebar.dart b/lib/page/layout/sidebar.dart new file mode 100644 index 0000000..1058bf2 --- /dev/null +++ b/lib/page/layout/sidebar.dart @@ -0,0 +1,625 @@ +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:flutter/material.dart'; +import '../setting/setting.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/chat_provider.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:chatmcp/page/layout/widgets/app_info.dart'; +import 'package:chatmcp/config/pagination_config.dart'; +import 'dart:async'; + +class SidebarPanel extends StatefulWidget { + final VoidCallback? onToggle; + const SidebarPanel({super.key, this.onToggle}); + + @override + State createState() => _SidebarPanelState(); +} + +class _SidebarPanelState extends State { + bool _isSearchVisible = false; + final TextEditingController _searchController = TextEditingController(); + Timer? _debounceTimer; + + @override + void dispose() { + _searchController.dispose(); + _debounceTimer?.cancel(); + super.dispose(); + } + + void toggleSearchVisibility() { + setState(() { + _isSearchVisible = !_isSearchVisible; + if (!_isSearchVisible) { + _searchController.clear(); + _performSearch(''); // Reset search when hiding + } + }); + } + + void _performSearch(String keyword) { + final chatProvider = Provider.of(context, listen: false); + chatProvider.searchChats(keyword); + } + + void _onSearchChanged(String value) { + // Cancel previous timer + _debounceTimer?.cancel(); + + // Start new timer + _debounceTimer = Timer(const Duration(milliseconds: 300), () { + _performSearch(value); + }); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, chatProvider, child) => SizedBox( + height: double.infinity, + child: Column( + children: [ + // 顶部区域 + Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + if (kIsWindows || kIsLinux || kIsMobile || kIsBrowser) ...[ + Image.asset('assets/logo.png', width: 24, height: 24), + const Gap(size: 8), + CText(text: 'ChatMCP', size: 12, fontWeight: FontWeight.w700), + ], + const Spacer(), + InkIcon(icon: CupertinoIcons.search, onTap: toggleSearchVisibility, tooltip: AppLocalizations.of(context)!.search), + if (kIsDesktop) ...[ + const Gap(size: 8), + InkIcon(icon: CupertinoIcons.sidebar_left, onTap: widget.onToggle, tooltip: AppLocalizations.of(context)!.toggleSidebar), + ], + ], + ), + ), + + // 搜索框 + if (_isSearchVisible) + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 4), + child: Container( + height: 32, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + color: AppColors.getThemeColor(context, lightColor: Colors.grey[300], darkColor: Colors.grey[600]), + ), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: AppLocalizations.of(context)!.search, + hintStyle: const TextStyle(fontSize: 12), + suffixIcon: IconButton( + icon: const Icon(CupertinoIcons.clear, size: 14), + onPressed: () { + _searchController.clear(); + _onSearchChanged(''); + }, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + visualDensity: VisualDensity.compact, + ), + contentPadding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12), + border: InputBorder.none, + isDense: true, + isCollapsed: true, + ), + textAlignVertical: TextAlignVertical.center, + style: const TextStyle(fontSize: 12), + onChanged: _onSearchChanged, + ), + ), + ), + + // 中间区域 - 聊天历史列表 + Expanded(child: ChatHistoryList(chatProvider: chatProvider)), + + // 底部区域 + SidebarToolbar(chatProvider: chatProvider), + ], + ), + ), + ); + } +} + +class ChatHistoryList extends StatefulWidget { + final ChatProvider chatProvider; + + const ChatHistoryList({super.key, required this.chatProvider}); + + @override + State createState() => _ChatHistoryListState(); +} + +class _ChatHistoryListState extends State { + final ScrollController _scrollController = ScrollController(); + bool _isLoadingMore = false; // 防止重复触发加载 + + @override + void initState() { + super.initState(); + _scrollController.addListener(_scrollListener); + + // Load initial data if empty + WidgetsBinding.instance.addPostFrameCallback((_) { + if (widget.chatProvider.chats.isEmpty) { + widget.chatProvider.loadChats(); + } + }); + } + + @override + void dispose() { + _scrollController.removeListener(_scrollListener); + _scrollController.dispose(); + super.dispose(); + } + + void _scrollListener() { + // 如果已经在加载,不重复触发 + if (_isLoadingMore) return; + + // 检查是否滚动到接近底部 + final scrollPosition = _scrollController.position; + final isNearBottom = scrollPosition.pixels >= scrollPosition.maxScrollExtent - PaginationConfig.loadMoreTriggerDistance; + + // 只有在接近底部且有更多数据时才加载 + if (isNearBottom && widget.chatProvider.hasMoreChats && !widget.chatProvider.isLoadingChats && widget.chatProvider.chats.isNotEmpty) { + _triggerLoadMore(); + } + } + + void _triggerLoadMore() async { + if (_isLoadingMore) return; + + setState(() { + _isLoadingMore = true; + }); + + try { + await widget.chatProvider.loadMoreChats(); + } finally { + if (mounted) { + setState(() { + _isLoadingMore = false; + }); + } + } + } + + Map> _groupChats(BuildContext context, List chats) { + final l10n = AppLocalizations.of(context)!; + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final yesterday = today.subtract(const Duration(days: 1)); + final previous7Days = today.subtract(const Duration(days: 7)); + final previous30Days = today.subtract(const Duration(days: 30)); + + return { + l10n.today: chats.where((chat) { + final chatDate = DateTime(chat.updatedAt.year, chat.updatedAt.month, chat.updatedAt.day); + return chatDate.isAtSameMomentAs(today); + }).toList(), + l10n.yesterday: chats.where((chat) { + final chatDate = DateTime(chat.updatedAt.year, chat.updatedAt.month, chat.updatedAt.day); + return chatDate.isAtSameMomentAs(yesterday); + }).toList(), + l10n.last7Days: chats.where((chat) { + final chatDate = DateTime(chat.updatedAt.year, chat.updatedAt.month, chat.updatedAt.day); + return chatDate.isBefore(yesterday) && chatDate.isAfter(previous7Days); + }).toList(), + l10n.last30Days: chats.where((chat) { + final chatDate = DateTime(chat.updatedAt.year, chat.updatedAt.month, chat.updatedAt.day); + return chatDate.isBefore(previous7Days) && chatDate.isAfter(previous30Days); + }).toList(), + l10n.earlier: chats.where((chat) { + final chatDate = DateTime(chat.updatedAt.year, chat.updatedAt.month, chat.updatedAt.day); + return chatDate.isBefore(previous30Days); + }).toList(), + }; + } + + @override + Widget build(BuildContext context) { + final groupedChats = _groupChats(context, widget.chatProvider.chats); + final hasEmptyGroups = groupedChats.values.every((group) => group.isEmpty); + + if (hasEmptyGroups && !widget.chatProvider.isLoadingChats) { + final l10n = AppLocalizations.of(context)!; + return Center( + child: Text( + l10n.welcomeMessage, + style: TextStyle(color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha((0.6 * 255).round()), fontSize: 14), + ), + ); + } + + return Column( + children: [ + Expanded( + child: ListView.builder( + controller: _scrollController, + itemCount: _calculateItemCount(groupedChats) + 1, // +1 for footer + itemBuilder: (context, index) { + final normalItemCount = _calculateItemCount(groupedChats); + if (index == normalItemCount) { + // This is the footer item + return _buildFooter(); + } + return _buildItem(context, groupedChats, index); + }, + ), + ), + ], + ); + } + + int _calculateItemCount(Map> groupedChats) { + int count = 0; + for (final entry in groupedChats.entries) { + if (entry.value.isNotEmpty) { + count += 1 + entry.value.length; // Header + items + } + } + return count; + } + + Widget _buildItem(BuildContext context, Map> groupedChats, int index) { + int currentIndex = 0; + + for (final entry in groupedChats.entries) { + if (entry.value.isEmpty) continue; + + // Check if this is the header + if (currentIndex == index) { + return _buildGroupHeader(entry.key); + } + currentIndex++; + + // Check if this is within the group items + if (index < currentIndex + entry.value.length) { + final itemIndex = index - currentIndex; + return _buildChatItem(entry.value[itemIndex]); + } + currentIndex += entry.value.length; + } + + return const SizedBox.shrink(); + } + + Widget _buildGroupHeader(String title) { + return Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Text( + title, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha((0.7 * 255).round()), + ), + ), + ); + } + + Widget _buildChatItem(dynamic chat) { + return ChatHistoryItem(chat: chat, chatProvider: widget.chatProvider); + } + + Widget _buildFooter() { + // Don't show footer if there are no chats at all + if (widget.chatProvider.chats.isEmpty && !widget.chatProvider.isLoadingChats) { + return const SizedBox.shrink(); + } + + if (widget.chatProvider.isLoadingChats) { + // Show loading indicator when loading more + return Container( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor)), + ), + const SizedBox(width: 12), + Text( + AppLocalizations.of(context)!.downloadingData, + style: TextStyle(fontSize: 12, color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha((0.7 * 255).round())), + ), + ], + ), + ); + } else if (!widget.chatProvider.hasMoreChats && widget.chatProvider.chats.isNotEmpty) { + // Show "no more" message only when there are chats and no more to load + return Container( + padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16), + child: Text( + '—— ${AppLocalizations.of(context)!.noMoreData} ——', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha((0.5 * 255).round())), + ), + ); + } else { + // Has more but not loading, show minimal space for scroll detection + return const SizedBox(height: 50); + } + } +} + +class ChatHistoryItem extends StatelessWidget { + final dynamic chat; + final ChatProvider chatProvider; + + const ChatHistoryItem({super.key, required this.chat, required this.chatProvider}); + + @override + Widget build(BuildContext context) { + final isActive = chat.id == chatProvider.activeChat?.id; + final l10n = AppLocalizations.of(context)!; + final backgroundColor = AppColors.getThemeColor(context, lightColor: Colors.white, darkColor: Colors.grey[800]); + + // 创建弹出菜单的内容 + Widget popupContent = Container( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: () { + Navigator.pop(context); // 关闭弹窗 + _showDeleteConfirmDialog(context); + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + const Icon(CupertinoIcons.delete, size: 18, color: Colors.red), + const Gap(size: 8), + Text(l10n.delete, style: const TextStyle(color: Colors.red)), + ], + ), + ), + ), + ], + ), + ); + + // 创建聊天项 + Widget chatItem = ListTile( + dense: true, + visualDensity: VisualDensity(vertical: -4), + leading: chatProvider.isSelectMode + ? Checkbox( + value: chatProvider.selectedChats.contains(chat.id), + onChanged: (bool? value) { + if (value == true) { + chatProvider.selectChat(chat.id); + } else { + chatProvider.unselectChat(chat.id); + } + }, + ) + : null, + title: Row( + children: [ + Expanded( + child: CText(text: chat.title.replaceAll('\n', ' '), size: 12, overflow: TextOverflow.ellipsis), + ), + ], + ), + onTap: () { + if (chatProvider.isSelectMode) { + chatProvider.toggleSelectChat(chat.id); + } else { + chatProvider.setActiveChat(chat); + if (kIsMobile) { + Navigator.pop(context); + } + } + }, + ); + + return Container( + margin: const EdgeInsets.symmetric(vertical: 4), + decoration: BoxDecoration( + color: isActive ? AppColors.getSidebarActiveConversationColor(context) : null, + borderRadius: BorderRadius.circular(7), + ), + child: kIsDesktop + ? _buildDesktopChatItem(context, chatItem, popupContent, backgroundColor) + : _buildMobileChatItem(context, chatItem, popupContent, backgroundColor), + ); + } + + // 桌面端构建方法:右键触发 + Widget _buildDesktopChatItem(BuildContext context, Widget chatItem, Widget popupContent, Color? backgroundColor) { + return GestureDetector( + onSecondaryTapDown: (TapDownDetails details) { + _showCustomPopup(context, popupContent, backgroundColor, details.globalPosition); + }, + child: chatItem, + ); + } + + // 移动端构建方法:长按触发 + Widget _buildMobileChatItem(BuildContext context, Widget chatItem, Widget popupContent, Color? backgroundColor) { + return GestureDetector( + onLongPressStart: (LongPressStartDetails details) { + _showCustomPopup(context, popupContent, backgroundColor, details.globalPosition); + }, + child: chatItem, + ); + } + + // 显示自定义弹出窗口 + void _showCustomPopup(BuildContext context, Widget content, Color? backgroundColor, Offset position) { + // 估计弹出菜单的宽度 + const double estimatedPopupWidth = 150.0; + + // 计算屏幕宽度 + final double screenWidth = MediaQuery.of(context).size.width; + + // 计算合适的left位置,使菜单靠右显示 + double left = position.dx; + + // 确保菜单不会超出屏幕左边界 + left = left < 10 ? 10 : left; + + // 确保菜单不会超出屏幕右边界 + if (left + estimatedPopupWidth > screenWidth - 10) { + left = screenWidth - estimatedPopupWidth - 10; + } + + showDialog( + context: context, + barrierColor: Colors.transparent, + builder: (BuildContext context) { + return Stack( + children: [ + Positioned( + left: left, + top: position.dy, + child: Material(elevation: 4.0, borderRadius: BorderRadius.circular(8.0), color: backgroundColor, child: content), + ), + ], + ); + }, + ); + } + + void _showDeleteConfirmDialog(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.confirmDelete), + content: Text(l10n.confirmDeleteSelected), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: Text(l10n.cancel)), + TextButton( + onPressed: () { + chatProvider.deleteChat(chat.id); + Navigator.pop(context); + }, + child: Text(l10n.ok), + ), + ], + ), + ); + } +} + +class SidebarToolbar extends StatelessWidget { + final ChatProvider chatProvider; + + const SidebarToolbar({super.key, required this.chatProvider}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 6), + child: Row( + children: [ + _buildSettingsButton(context), + const Gap(size: 4), + _buildSelectModeButton(context), + if (chatProvider.isSelectMode) ...[const Gap(size: 4), _buildSelectAllButton(context), const Gap(size: 4), _buildDeleteButton(context)], + const Spacer(), + const AppInfo(), + const Gap(size: 4), + ], + ), + ); + } + + Widget _buildSettingsButton(BuildContext context) { + return InkIcon(icon: CupertinoIcons.settings, onTap: () => _showSettingsDialog(context), tooltip: AppLocalizations.of(context)!.settings); + } + + Widget _buildSelectModeButton(BuildContext context) { + return InkIcon( + icon: chatProvider.isSelectMode ? CupertinoIcons.clear : CupertinoIcons.trash, + onTap: () { + if (chatProvider.isSelectMode) { + chatProvider.exitSelectMode(); + } else { + chatProvider.enterSelectMode(); + } + }, + tooltip: AppLocalizations.of(context)!.deleteChat, + ); + } + + Widget _buildSelectAllButton(BuildContext context) { + return InkIcon( + icon: CupertinoIcons.checkmark_square, + onTap: () => chatProvider.toggleSelectAll(), + tooltip: AppLocalizations.of(context)!.selectAll, + ); + } + + Widget _buildDeleteButton(BuildContext context) { + return InkIcon( + icon: CupertinoIcons.delete, + onTap: chatProvider.selectedChats.isNotEmpty ? () => _showDeleteConfirmDialog(context) : null, + tooltip: AppLocalizations.of(context)!.delete, + ); + } + + void _showSettingsDialog(BuildContext context) { + if (kIsMobile) { + Navigator.push(context, MaterialPageRoute(builder: (context) => const SettingPage())); + } else { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + child: ClipRRect( + borderRadius: BorderRadius.circular(8.0), + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + child: const SettingPage(), + ), + ), + ), + ); + } + } + + void _showDeleteConfirmDialog(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.confirmDelete), + content: Text(l10n.confirmDeleteSelected), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: Text(l10n.cancel)), + TextButton( + onPressed: () { + chatProvider.deleteSelectedChats(); + Navigator.pop(context); + }, + child: Text(l10n.ok), + ), + ], + ), + ); + } +} diff --git a/lib/page/layout/widgets/app_info.dart b/lib/page/layout/widgets/app_info.dart new file mode 100644 index 0000000..e78db71 --- /dev/null +++ b/lib/page/layout/widgets/app_info.dart @@ -0,0 +1,118 @@ +import 'package:chatmcp/page/layout/widgets/llm_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:logging/logging.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:chatmcp/widgets/upgrade.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class AppInfo extends StatelessWidget { + final String? appWebsite; + final String? githubUrl; + final String? licenseInfo; + + const AppInfo({super.key, this.appWebsite, this.githubUrl = 'https://github.com/daodao97/chatmcp', this.licenseInfo = 'Apache License 2.0'}); + + Future _getAppVersion() async { + final packageInfo = await PackageInfo.fromPlatform(); + return packageInfo.version; + } + + void _showAboutDialog(BuildContext context) async { + final l10n = AppLocalizations.of(context)!; + final version = await _getAppVersion(); + + Logger.root.info('AppInfo: $version'); + + if (!context.mounted) return; + + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + child: Container( + width: kIsMobile ? null : 450, + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Logo + ClipRRect(borderRadius: BorderRadius.circular(8.0), child: Image.asset('assets/logo.png', width: 80, height: 80)), + const SizedBox(height: 16), + + // App Name + Text( + 'ChatMCP', + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: AppColors.getThemeTextColor(context)), + ), + + // Version + Text('v$version', style: TextStyle(fontSize: 16, color: AppColors.getThemeTextColor(context).withAlpha(120))), + const SizedBox(height: 16), + + // Description + Text( + l10n.appDescription, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: AppColors.getThemeTextColor(context)), + ), + const SizedBox(height: 24), + + // Links + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (appWebsite != null) _buildLinkButton(context, LlmIcon(icon: "github"), l10n.visitWebsite, appWebsite!), + if (appWebsite != null && githubUrl != null) const SizedBox(width: 12), + if (githubUrl != null) _buildLinkButton(context, LlmIcon(icon: "github"), 'GitHub', githubUrl!), + const SizedBox(width: 12), + UpgradeNotice(owner: 'daodao97', repo: 'chatmcp', showCheckUpdate: true, autoCheck: true), + ], + ), + + if (licenseInfo != null) ...[ + const SizedBox(height: 16), + Text( + licenseInfo!, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 12, color: AppColors.getThemeTextColor(context).withAlpha(128)), + ), + ], + ], + ), + ), + ), + ); + } + + Widget _buildLinkButton(BuildContext context, LlmIcon icon, String label, String url) { + return InkWell( + onTap: () { + launchUrl(Uri.parse(url)); + }, + borderRadius: BorderRadius.circular(20), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: AppColors.getInkIconHoverColor(context), borderRadius: BorderRadius.circular(20)), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + icon, + const SizedBox(width: 8), + Text(label, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: () => _showAboutDialog(context), + child: LlmIcon(icon: "github", tooltip: AppLocalizations.of(context)!.aboutApp), + ); + } +} diff --git a/lib/page/layout/widgets/chat_setting.dart b/lib/page/layout/widgets/chat_setting.dart new file mode 100644 index 0000000..6966824 --- /dev/null +++ b/lib/page/layout/widgets/chat_setting.dart @@ -0,0 +1,287 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +class ChatSetting extends StatelessWidget { + const ChatSetting({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + return Consumer( + builder: (context, settingsProvider, child) { + final modelSetting = settingsProvider.modelSetting; + + return SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.modelSettings, CupertinoIcons.slider_horizontal_3), + const SizedBox(height: 16), + Container( + decoration: BoxDecoration( + color: colorScheme.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: colorScheme.outline.withAlpha(26), width: 1), + boxShadow: [BoxShadow(color: colorScheme.shadow.withAlpha(13), blurRadius: 10, offset: const Offset(0, 2))], + ), + child: Column( + children: [ + _buildSliderWithLabel( + context: context, + label: l10n.temperature(modelSetting.temperature.toStringAsFixed(2)), + value: modelSetting.temperature, + min: 0.0, + max: 2.0, + onChanged: (value) => _updateModelSettings(settingsProvider, temperature: value), + tooltip: l10n.temperatureTooltip, + ), + _buildDivider(context), + _buildSliderWithLabel( + context: context, + label: l10n.topP(modelSetting.topP.toStringAsFixed(2)), + value: modelSetting.topP, + min: 0.0, + max: 1.0, + onChanged: (value) => _updateModelSettings(settingsProvider, topP: value), + tooltip: l10n.topPTooltip, + ), + _buildDivider(context), + _buildNumberInput( + context: context, + label: l10n.maxTokens, + value: modelSetting.maxTokens, + onChanged: (value) => _updateModelSettings(settingsProvider, maxTokens: value), + tooltip: l10n.maxTokensTooltip, + ), + _buildDivider(context), + _buildSliderWithLabel( + context: context, + label: l10n.frequencyPenalty(modelSetting.frequencyPenalty.toStringAsFixed(2)), + value: modelSetting.frequencyPenalty, + min: -2.0, + max: 2.0, + onChanged: (value) => _updateModelSettings(settingsProvider, frequencyPenalty: value), + tooltip: l10n.frequencyPenaltyTooltip, + ), + _buildDivider(context), + _buildSliderWithLabel( + context: context, + label: l10n.presencePenalty(modelSetting.presencePenalty.toStringAsFixed(2)), + value: modelSetting.presencePenalty, + min: -2.0, + max: 2.0, + onChanged: (value) => _updateModelSettings(settingsProvider, presencePenalty: value), + tooltip: l10n.presencePenaltyTooltip, + ), + ], + ), + ), + const SizedBox(height: 20), + Align( + alignment: Alignment.centerRight, + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all(color: colorScheme.primary.withAlpha(51), width: 1), + ), + child: TextButton.icon( + onPressed: () => _resetModelSettings(settingsProvider), + icon: Icon(CupertinoIcons.refresh_thin, size: 18, color: colorScheme.primary), + label: Text( + 'Reset', + style: TextStyle(color: colorScheme.primary, fontWeight: FontWeight.w500), + ), + style: TextButton.styleFrom( + foregroundColor: colorScheme.primary, + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + ), + ), + ), + ], + ), + ), + ); + }, + ); + } + + Widget _buildSectionTitle(BuildContext context, String title, IconData icon) { + final colorScheme = Theme.of(context).colorScheme; + + return Container( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 4.0), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration(color: colorScheme.primary.withAlpha(26), borderRadius: BorderRadius.circular(8)), + child: Icon(icon, size: 20, color: colorScheme.primary), + ), + const SizedBox(width: 12), + Text( + title, + style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: colorScheme.onSurface, letterSpacing: -0.5), + ), + ], + ), + ); + } + + Widget _buildDivider(BuildContext context) { + return Divider(height: 1, indent: 20, endIndent: 20, color: Theme.of(context).colorScheme.outline.withAlpha(21)); + } + + Widget _buildSliderWithLabel({ + required BuildContext context, + required String label, + required double value, + required double min, + required double max, + required ValueChanged onChanged, + String? tooltip, + }) { + final colorScheme = Theme.of(context).colorScheme; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + label, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: colorScheme.onSurface), + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration(color: colorScheme.primary.withAlpha(26), borderRadius: BorderRadius.circular(6)), + child: Text( + value.toStringAsFixed(2), + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colorScheme.primary), + ), + ), + ], + ), + if (tooltip != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(tooltip, style: TextStyle(fontSize: 13, color: colorScheme.onSurface.withAlpha(153), height: 1.3)), + ), + const SizedBox(height: 12), + SliderTheme( + data: SliderTheme.of(context).copyWith( + activeTrackColor: colorScheme.primary, + inactiveTrackColor: colorScheme.primary.withAlpha(39), + thumbColor: colorScheme.primary, + overlayColor: colorScheme.primary.withAlpha(26), + trackHeight: 4, + thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 8), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 16), + ), + child: Slider(value: value, min: min, max: max, onChanged: onChanged), + ), + ], + ), + ); + } + + Widget _buildNumberInput({ + required BuildContext context, + required String label, + required int? value, + required ValueChanged onChanged, + String? tooltip, + }) { + final l10n = AppLocalizations.of(context)!; + final colorScheme = Theme.of(context).colorScheme; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500, color: colorScheme.onSurface), + ), + if (tooltip != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text(tooltip, style: TextStyle(fontSize: 13, color: colorScheme.onSurface.withAlpha(153), height: 1.3)), + ), + const SizedBox(height: 12), + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all(color: colorScheme.outline.withAlpha(51), width: 1), + ), + child: TextField( + controller: TextEditingController(text: value?.toString() ?? ''), + keyboardType: TextInputType.number, + style: TextStyle(fontSize: 15, color: colorScheme.onSurface, fontWeight: FontWeight.w500), + decoration: InputDecoration( + hintText: l10n.enterMaxTokens, + hintStyle: TextStyle(color: colorScheme.onSurface.withAlpha(128), fontWeight: FontWeight.normal), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide(color: colorScheme.primary, width: 2), + ), + ), + onChanged: (value) { + if (value.isEmpty) { + onChanged(null); + } else { + onChanged(int.tryParse(value)); + } + }, + ), + ), + ], + ), + ); + } + + void _updateModelSettings( + SettingsProvider provider, { + double? temperature, + int? maxTokens, + double? topP, + double? frequencyPenalty, + double? presencePenalty, + }) { + final currentSettings = provider.modelSetting; + provider.updateModelSettings( + temperature: temperature != null ? _roundToOneDecimal(temperature) : currentSettings.temperature, + maxTokens: maxTokens, + topP: topP != null ? _roundToOneDecimal(topP) : currentSettings.topP, + frequencyPenalty: frequencyPenalty != null ? _roundToOneDecimal(frequencyPenalty) : currentSettings.frequencyPenalty, + presencePenalty: presencePenalty != null ? _roundToOneDecimal(presencePenalty) : currentSettings.presencePenalty, + ); + } + + /// 将double值四舍五入到小数点后一位 + double _roundToOneDecimal(double value) { + return (value * 10).round() / 10; + } + + Future _resetModelSettings(SettingsProvider provider) async { + await provider.resetModelSettings(); + } +} diff --git a/lib/page/layout/widgets/conv_setting.dart b/lib/page/layout/widgets/conv_setting.dart new file mode 100644 index 0000000..1343a2d --- /dev/null +++ b/lib/page/layout/widgets/conv_setting.dart @@ -0,0 +1,549 @@ +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/mcp_server_provider.dart'; +import 'package:chatmcp/provider/serve_state_provider.dart'; +import 'package:flutter_switch/flutter_switch.dart'; +import 'package:chatmcp/provider/settings_provider.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:chatmcp/components/widgets/custom_popup.dart'; +import 'dart:async'; + +class ConvSetting extends StatefulWidget { + const ConvSetting({super.key}); + + @override + State createState() => _ConvSettingState(); +} + +class _ConvSettingState extends State { + List? _cachedServers; + bool _isLoading = true; + String? _error; + + // server state provider + final ServerStateProvider _stateProvider = ServerStateProvider(); + + // add TextEditingController as state variable + late TextEditingController _maxMessagesController; + late TextEditingController _maxLoopsController; + + // debounce timer + Timer? _debounceTimer; + + @override + void initState() { + super.initState(); + _loadServers(); + // initialize controllers + _maxMessagesController = TextEditingController(); + _maxLoopsController = TextEditingController(); + + // set initial values in the next frame + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + final settingsProvider = Provider.of(context, listen: false); + final generalSetting = settingsProvider.generalSetting; + _maxMessagesController.text = generalSetting.maxMessages.toString(); + _maxLoopsController.text = generalSetting.maxLoops.toString(); + } + }); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // listen to provider changes and reload server list + final provider = Provider.of(context); + if (provider.loadingServerTools == false) { + _loadServers(); + } + + // update controllers only when initialized or values really changed + final settingsProvider = Provider.of(context); + final generalSetting = settingsProvider.generalSetting; + + // use WidgetsBinding.instance.addPostFrameCallback to avoid modifying state in the build process + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + final currentMaxMessages = generalSetting.maxMessages.toString(); + final currentMaxLoops = generalSetting.maxLoops.toString(); + + if (_maxMessagesController.text != currentMaxMessages) { + _maxMessagesController.text = currentMaxMessages; + } + if (_maxLoopsController.text != currentMaxLoops) { + _maxLoopsController.text = currentMaxLoops; + } + } + }); + } + + @override + void dispose() { + // release controllers + _maxMessagesController.dispose(); + _maxLoopsController.dispose(); + // cancel debounce timer + _debounceTimer?.cancel(); + super.dispose(); + } + + Future _loadServers() async { + setState(() { + _isLoading = true; + _error = null; + }); + + try { + final provider = Provider.of(context, listen: false); + final servers = await provider.loadServersAll(); + + setState(() { + _cachedServers = servers['mcpServers'].keys.toList(); + _isLoading = false; + }); + + _stateProvider.syncFromProvider(provider, _cachedServers!); + } catch (e) { + setState(() { + _error = e.toString(); + _isLoading = false; + }); + } + } + + // handle server status switch + Future _handleServerToggle(BuildContext context, String serverName, bool newValue) async { + final provider = Provider.of(context, listen: false); + + // update enabled state + _stateProvider.setEnabled(serverName, newValue); + + // update state in Provider + provider.toggleToolCategory(serverName, newValue); + + // if new state is true and server is not running, start server + if (newValue && !provider.mcpServerIsRunning(serverName)) { + _stateProvider.setStarting(serverName, true); + + try { + await provider.startMcpServer(serverName); + // update running state + _stateProvider.setRunning(serverName, true); + } catch (e) { + // update state if server start failed + _stateProvider.setRunning(serverName, false); + _stateProvider.setStarting(serverName, false); + } + } + } + + // debounce update settings + void _debouncedUpdateSettings(String field, int value) { + _debounceTimer?.cancel(); + _debounceTimer = Timer(const Duration(milliseconds: 500), () { + if (mounted) { + final settingsProvider = Provider.of(context, listen: false); + if (field == 'maxMessages') { + settingsProvider.updateGeneralSettingsPartially(maxMessages: value); + } else if (field == 'maxLoops') { + settingsProvider.updateGeneralSettingsPartially(maxLoops: value); + } + } + }); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, mcpServerProvider, child) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_cachedServers != null) { + _stateProvider.syncFromProvider(mcpServerProvider, _cachedServers!); + } + }); + + return BasePopup( + showArrow: true, + maxWidth: 400, + padding: EdgeInsets.zero, + content: _isLoading + ? const Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))) + : _error != null + ? Center(child: Text(_error!, style: Theme.of(context).textTheme.bodyMedium)) + : Container( + constraints: const BoxConstraints(maxHeight: 400), + child: SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, children: [_buildSettingsSection(context)]), + ), + ), + child: Consumer( + builder: (context, stateProvider, _) { + final l10n = AppLocalizations.of(context)!; + return InkIcon(icon: CupertinoIcons.gear, tooltip: l10n.settings); + }, + ), + ); + }, + ); + } + + Widget _buildSettingsSection(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return Consumer( + builder: (context, settingsProvider, child) { + return Container( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.conversationSettings, style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold)), + const SizedBox(height: 12), + + // Max Messages settings + Row( + children: [ + Expanded(child: Text(l10n.maxMessages, style: Theme.of(context).textTheme.bodyMedium)), + Container( + width: 120, + height: 36, + decoration: BoxDecoration( + border: Border.all(color: Theme.of(context).colorScheme.outline.withAlpha(77)), + borderRadius: BorderRadius.circular(6), + color: Theme.of(context).colorScheme.surface, + ), + child: Row( + children: [ + // decrease button + SizedBox( + width: 32, + height: 36, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: const BorderRadius.only(topLeft: Radius.circular(6), bottomLeft: Radius.circular(6)), + hoverColor: AppColors.getInkIconHoverColor(context), + onTap: () { + final currentValue = int.tryParse(_maxMessagesController.text) ?? 50; + if (currentValue > 1) { + final newValue = currentValue - 1; + _maxMessagesController.text = newValue.toString(); + _debouncedUpdateSettings('maxMessages', newValue); + } + }, + child: Icon( + Icons.remove, + size: 16, + color: AppColors.getThemeColor(context, lightColor: Colors.grey[600], darkColor: Colors.grey[400]), + ), + ), + ), + ), + // separator + Container(width: 1, height: 20, color: Theme.of(context).colorScheme.outline.withAlpha(51)), + // number input + Expanded( + child: TextField( + controller: _maxMessagesController, + keyboardType: TextInputType.number, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: AppColors.getThemeTextColor(context)), + inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(4)], + decoration: const InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(vertical: 8), + isDense: true, + ), + onChanged: (value) { + final intValue = int.tryParse(value); + if (intValue != null && intValue > 0 && intValue <= 1000) { + _debouncedUpdateSettings('maxMessages', intValue); + } + }, + ), + ), + // separator + Container(width: 1, height: 20, color: Theme.of(context).colorScheme.outline.withAlpha(51)), + // increase button + SizedBox( + width: 32, + height: 36, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: const BorderRadius.only(topRight: Radius.circular(6), bottomRight: Radius.circular(6)), + hoverColor: AppColors.getInkIconHoverColor(context), + onTap: () { + final currentValue = int.tryParse(_maxMessagesController.text) ?? 50; + if (currentValue < 1000) { + final newValue = currentValue + 1; + _maxMessagesController.text = newValue.toString(); + _debouncedUpdateSettings('maxMessages', newValue); + } + }, + child: Icon( + Icons.add, + size: 16, + color: AppColors.getThemeColor(context, lightColor: Colors.grey[600], darkColor: Colors.grey[400]), + ), + ), + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + l10n.maxMessagesDescription, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Theme.of(context).textTheme.bodySmall?.color?.withAlpha(128)), + ), + + const SizedBox(height: 16), + + // Max Loops settings + Row( + children: [ + Expanded(child: Text(l10n.maxLoops, style: Theme.of(context).textTheme.bodyMedium)), + Container( + width: 120, + height: 36, + decoration: BoxDecoration( + border: Border.all(color: Theme.of(context).colorScheme.outline.withAlpha(77)), + borderRadius: BorderRadius.circular(6), + color: Theme.of(context).colorScheme.surface, + ), + child: Row( + children: [ + // decrease button + SizedBox( + width: 32, + height: 36, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: const BorderRadius.only(topLeft: Radius.circular(6), bottomLeft: Radius.circular(6)), + hoverColor: AppColors.getInkIconHoverColor(context), + onTap: () { + final currentValue = int.tryParse(_maxLoopsController.text) ?? 100; + if (currentValue > 1) { + final newValue = currentValue - 1; + _maxLoopsController.text = newValue.toString(); + _debouncedUpdateSettings('maxLoops', newValue); + } + }, + child: Icon( + Icons.remove, + size: 16, + color: AppColors.getThemeColor(context, lightColor: Colors.grey[600], darkColor: Colors.grey[400]), + ), + ), + ), + ), + // separator + Container(width: 1, height: 20, color: Theme.of(context).colorScheme.outline.withAlpha(51)), + // number input + Expanded( + child: TextField( + controller: _maxLoopsController, + keyboardType: TextInputType.number, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 14, color: AppColors.getThemeTextColor(context)), + inputFormatters: [FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(4)], + decoration: const InputDecoration( + border: InputBorder.none, + contentPadding: EdgeInsets.symmetric(vertical: 8), + isDense: true, + ), + onChanged: (value) { + final intValue = int.tryParse(value); + if (intValue != null && intValue > 0 && intValue <= 1000) { + _debouncedUpdateSettings('maxLoops', intValue); + } + }, + ), + ), + // separator + Container(width: 1, height: 20, color: Theme.of(context).colorScheme.outline.withAlpha(51)), + // increase button + SizedBox( + width: 32, + height: 36, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: const BorderRadius.only(topRight: Radius.circular(6), bottomRight: Radius.circular(6)), + hoverColor: AppColors.getInkIconHoverColor(context), + onTap: () { + final currentValue = int.tryParse(_maxLoopsController.text) ?? 100; + if (currentValue < 1000) { + final newValue = currentValue + 1; + _maxLoopsController.text = newValue.toString(); + _debouncedUpdateSettings('maxLoops', newValue); + } + }, + child: Icon( + Icons.add, + size: 16, + color: AppColors.getThemeColor(context, lightColor: Colors.grey[600], darkColor: Colors.grey[400]), + ), + ), + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + l10n.maxLoopsDescription, + style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Theme.of(context).textTheme.bodySmall?.color?.withAlpha(128)), + ), + ], + ), + ); + }, + ); + } + + List _buildMenuItems(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final McpServerProvider provider = Provider.of(context, listen: false); + final List menuItems = []; + + // handle loading state + if (_isLoading) { + return [ + const SizedBox( + height: 40, + child: Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))), + ), + ]; + } + + // handle error state + if (_error != null) { + return [ + SizedBox( + height: 40, + child: Center(child: Text('Load failed: $_error', style: Theme.of(context).textTheme.bodyMedium)), + ), + ]; + } + + // handle no data state + if (_cachedServers == null || _cachedServers!.isEmpty) { + return []; + } + + // add server title + menuItems.add( + Container( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + child: Text(l10n.mcpServers, style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold)), + ), + ); + + // use cached server list to build menu items + for (String serverName in _cachedServers!) { + // add separator + if (menuItems.length > 1) { + menuItems.add(const Divider(height: 1)); + } + + // use normal Container instead of CustomPopupMenuWidget + menuItems.add( + Container( + height: 40, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: ChangeNotifierProvider.value( + value: _stateProvider, + child: Consumer( + builder: (context, stateProvider, _) { + bool isEnabled = stateProvider.isEnabled(serverName); + bool isRunning = stateProvider.isRunning(serverName); + bool isStarting = stateProvider.isStarting(serverName); + + // get server tool count + List>? serverTools = provider.tools[serverName]; + int toolCount = serverTools?.length ?? 0; + + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: Text(serverName, overflow: TextOverflow.ellipsis, maxLines: 1)), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only(right: 8), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: isRunning ? Colors.green : Colors.grey, shape: BoxShape.circle), + ), + ), + if (isEnabled && isRunning && toolCount > 0) + Container( + margin: const EdgeInsets.only(right: 8), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration(color: Colors.green.withAlpha(51), borderRadius: BorderRadius.circular(10)), + child: Text( + '$toolCount tools', + style: const TextStyle(fontSize: 12, color: Colors.green, fontWeight: FontWeight.bold), + ), + ), + FlutterSwitch( + width: 55.0, + height: 25.0, + value: isEnabled, + onToggle: (val) { + if (!isStarting) { + _handleServerToggle(context, serverName, val); + } + }, + toggleSize: 20.0, + activeColor: AppColors.getThemeColor(context, lightColor: Colors.blue, darkColor: Colors.blue.shade700), + inactiveColor: AppColors.getThemeColor(context, lightColor: Colors.grey[300]!, darkColor: Colors.grey[600]!), + activeToggleColor: AppColors.getThemeColor(context, lightColor: Colors.white, darkColor: Colors.white), + inactiveToggleColor: AppColors.getThemeColor(context, lightColor: Colors.blue, darkColor: Colors.blue.shade300), + showOnOff: true, + activeText: "ON", + inactiveText: "OFF", + valueFontSize: 10.0, + activeTextColor: AppColors.getThemeColor(context, lightColor: Colors.white, darkColor: Colors.white), + inactiveTextColor: AppColors.getThemeColor(context, lightColor: Colors.black, darkColor: Colors.white), + activeIcon: isStarting + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Colors.orange)), + ) + : isRunning + ? const Icon(Icons.check_circle, size: 16, color: Colors.green) + : null, + disabled: isStarting, + ), + ], + ), + ], + ); + }, + ), + ), + ), + ); + } + + return menuItems; + } +} diff --git a/lib/page/layout/widgets/llm_icon.dart b/lib/page/layout/widgets/llm_icon.dart new file mode 100644 index 0000000..1146420 --- /dev/null +++ b/lib/page/layout/widgets/llm_icon.dart @@ -0,0 +1,133 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; +import 'dart:async'; +import 'package:flutter/services.dart'; +import 'dart:io' show Platform; +import 'package:flutter/foundation.dart' show kIsWeb; + +class LlmIcon extends StatelessWidget { + final String icon; + final Color? color; + final double size; + final String? tooltip; + + const LlmIcon({ + super.key, + required this.icon, + this.color, + this.size = 16, // 基础默认值保持为常量16 + this.tooltip, + }); + + @override + Widget build(BuildContext context) { + // 在build方法中根据平台动态设置尺寸 + final double effectiveSize = size != 16 + ? size + : (kIsWeb + ? 16.0 + : (Platform.isAndroid || Platform.isIOS) + ? 24.0 + : 16.0); + + final isDark = Theme.of(context).brightness == Brightness.dark; + final defaultColor = isDark ? Colors.white : Colors.black; + + final Widget iconWidget; + if (icon.isNotEmpty) { + iconWidget = ColorAwareSvg(assetName: 'assets/logo/$icon.svg', size: effectiveSize, color: color ?? defaultColor); + } else { + iconWidget = ColorAwareSvg(assetName: 'assets/logo/ai-chip.svg', size: effectiveSize, color: color ?? defaultColor); + } + + if (tooltip == null) { + return iconWidget; + } + + return Tooltip(message: tooltip!, child: iconWidget); + } +} + +class ColorAwareSvg extends StatelessWidget { + final String assetName; + final double size; + final Color color; + + // 保存检测结果的静态缓存,避免重复检测 + static final Map _colorCache = {}; + + const ColorAwareSvg({super.key, required this.assetName, required this.size, required this.color}); + + // 检测SVG是否包含非黑白颜色 + Future _detectSvgHasColors(BuildContext context) async { + // 如果缓存中有结果,直接返回 + if (_colorCache.containsKey(assetName)) { + return _colorCache[assetName]!; + } + + try { + // 加载SVG文件内容 + final String svgString = await rootBundle.loadString(assetName); + + // 检查是否包含颜色相关属性(简化版) + bool hasColor = false; + + // 检查是否包含除了黑白之外的颜色 + if (svgString.contains('fill="#') || svgString.contains('stroke="#')) { + // 排除纯黑色 (#000000) 和纯白色 (#FFFFFF) + hasColor = + !svgString.contains('fill="#000000"') && + !svgString.contains('fill="#ffffff"') && + !svgString.contains('stroke="#000000"') && + !svgString.contains('stroke="#ffffff"'); + } + + // 检查是否包含 rgb/rgba/hsl 颜色 + if (!hasColor) { + hasColor = + svgString.contains('fill="rgb') || + svgString.contains('stroke="rgb') || + svgString.contains('fill="hsl') || + svgString.contains('stroke="hsl'); + } + + if (svgString.contains("style") || svgString.contains("color")) { + hasColor = true; + } + + _colorCache[assetName] = hasColor; + return hasColor; + } catch (e) { + // 出错时假设没有颜色 + _colorCache[assetName] = false; + return false; + } + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + // 检测SVG是否有自定义颜色 + future: _detectSvgHasColors(context), + builder: (context, snapshot) { + // 加载中显示占位图 + if (!snapshot.hasData) { + return SizedBox(width: size, height: size, child: const CircularProgressIndicator(strokeWidth: 2)); + } + + // 根据检测结果决定是否应用颜色滤镜 + final hasOwnColors = snapshot.data ?? false; + return SvgPicture.asset( + assetName, + width: size, + height: size, + allowDrawingOutsideViewBox: true, + placeholderBuilder: (context) => Icon(CupertinoIcons.cloud, size: size), + // 如果SVG有自己的颜色,则不应用colorFilter + colorFilter: hasOwnColors ? null : ColorFilter.mode(color, BlendMode.srcIn), + ); + }, + ); + } +} diff --git a/lib/page/layout/widgets/mcp_tools.dart b/lib/page/layout/widgets/mcp_tools.dart new file mode 100644 index 0000000..0b8bc45 --- /dev/null +++ b/lib/page/layout/widgets/mcp_tools.dart @@ -0,0 +1,279 @@ +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/page/setting/mcp_info.dart'; +import 'package:chatmcp/provider/mcp_server_provider.dart'; +import 'package:chatmcp/provider/serve_state_provider.dart'; +import 'package:flutter_switch/flutter_switch.dart'; +import 'package:chatmcp/components/widgets/custom_popup.dart'; + +class McpTools extends StatefulWidget { + const McpTools({super.key}); + + @override + State createState() => _McpToolsState(); +} + +class _McpToolsState extends State { + List? _cachedServers; + bool _isLoading = true; + String? _error; + + // 服务器状态提供者 + final ServerStateProvider _stateProvider = ServerStateProvider(); + + @override + void initState() { + super.initState(); + _loadServers(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // 监听 provider 变化并重新加载服务器列表 + final provider = Provider.of(context); + if (provider.loadingServerTools == false) { + _loadServers(); + } + } + + @override + void dispose() { + super.dispose(); + } + + Future _loadServers() async { + setState(() { + _isLoading = true; + _error = null; + }); + + try { + final provider = Provider.of(context, listen: false); + final servers = await provider.loadServersAll(); + + setState(() { + _cachedServers = servers['mcpServers'].keys.toList(); + _isLoading = false; + }); + + _stateProvider.syncFromProvider(provider, _cachedServers!); + } catch (e) { + setState(() { + _error = e.toString(); + _isLoading = false; + }); + } + } + + // 处理服务器的状态切换 + Future _handleServerToggle(BuildContext context, String serverName, bool newValue) async { + final provider = Provider.of(context, listen: false); + + // 更新启用状态 + _stateProvider.setEnabled(serverName, newValue); + + // 更新Provider中的状态 + provider.toggleToolCategory(serverName, newValue); + + // 如果新状态为true且服务器未运行,则启动服务器 + if (newValue && !provider.mcpServerIsRunning(serverName)) { + // 设置启动中状态 + _stateProvider.setStarting(serverName, true); + + try { + await provider.startMcpServer(serverName); + // 更新运行状态 + _stateProvider.setRunning(serverName, true); + } catch (e) { + // 启动失败,更新状态 + _stateProvider.setRunning(serverName, false); + _stateProvider.setStarting(serverName, false); + } + } + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, mcpServerProvider, child) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_cachedServers != null) { + _stateProvider.syncFromProvider(mcpServerProvider, _cachedServers!); + } + }); + + return BasePopup( + showArrow: true, + maxWidth: 400, + padding: EdgeInsets.zero, + content: _isLoading + ? const Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))) + : _error != null + ? PopupEmptyState(message: 'Load failed: $_error') + : _cachedServers == null || _cachedServers!.isEmpty + ? const PopupEmptyState(message: 'No available servers') + : SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, children: _buildMenuItems(context)), + ), + child: Consumer( + builder: (context, stateProvider, _) { + return InkIcon( + icon: CupertinoIcons.hammer, + tooltip: 'MCP Server', + child: stateProvider.enabledCount > 0 ? Text(' ${stateProvider.enabledCount}', style: const TextStyle(fontSize: 12)) : null, + ); + }, + ), + ); + }, + ); + } + + List _buildMenuItems(BuildContext context) { + final McpServerProvider provider = Provider.of(context, listen: false); + final List menuItems = []; + + // 处理加载状态 + if (_isLoading) { + return [ + const SizedBox( + height: 40, + child: Center(child: SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))), + ), + ]; + } + + // 处理错误状态 + if (_error != null) { + return [ + SizedBox( + height: 40, + child: Center(child: Text('Load failed: $_error', style: Theme.of(context).textTheme.bodyMedium)), + ), + ]; + } + + // 处理无数据状态 + if (_cachedServers == null || _cachedServers!.isEmpty) { + return [ + SizedBox( + height: 40, + child: Center(child: Text('No available servers', style: Theme.of(context).textTheme.bodyMedium)), + ), + ]; + } + + // 使用缓存的服务器列表构建菜单项 + for (String serverName in _cachedServers!) { + // 添加分隔线 + if (menuItems.isNotEmpty) { + menuItems.add(const Divider(height: 1)); + } + + // 使用普通的 Container 替代 CustomPopupMenuWidget + menuItems.add( + Container( + height: 40, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: ChangeNotifierProvider.value( + value: _stateProvider, + child: Consumer( + builder: (context, stateProvider, _) { + bool isEnabled = stateProvider.isEnabled(serverName); + bool isRunning = stateProvider.isRunning(serverName); + bool isStarting = stateProvider.isStarting(serverName); + + // 获取服务器工具数量 + List>? serverTools = provider.tools[serverName]; + int toolCount = serverTools?.length ?? 0; + + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: Text(serverName, overflow: TextOverflow.ellipsis, maxLines: 1)), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isRunning) + IconButton( + icon: const Icon(Icons.info_outline, size: 18, color: Colors.blue), + tooltip: 'Show server tools info', + onPressed: () { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + child: SizedBox(width: 400, height: 500, child: McpInfo(serverName: serverName)), + ), + ); + }, + ), + Container( + margin: const EdgeInsets.only(right: 8), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + child: Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: isRunning ? Colors.green : Colors.grey, shape: BoxShape.circle), + ), + ), + if (isEnabled && isRunning && toolCount > 0) + Container( + margin: const EdgeInsets.only(right: 8), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration(color: Colors.green.withAlpha(51), borderRadius: BorderRadius.circular(10)), + child: Text( + '$toolCount tools', + style: const TextStyle(fontSize: 12, color: Colors.green, fontWeight: FontWeight.bold), + ), + ), + FlutterSwitch( + width: 55.0, + height: 25.0, + value: isEnabled, + onToggle: (val) { + if (!isStarting) { + _handleServerToggle(context, serverName, val); + } + }, + toggleSize: 20.0, + activeColor: AppColors.getThemeColor(context, lightColor: Colors.blue, darkColor: Colors.blue.shade700), + inactiveColor: AppColors.getThemeColor(context, lightColor: Colors.grey[300]!, darkColor: Colors.grey[600]!), + activeToggleColor: AppColors.getThemeColor(context, lightColor: Colors.white, darkColor: Colors.white), + inactiveToggleColor: AppColors.getThemeColor(context, lightColor: Colors.blue, darkColor: Colors.blue.shade300), + showOnOff: true, + activeText: "ON", + inactiveText: "OFF", + valueFontSize: 10.0, + activeTextColor: AppColors.getThemeColor(context, lightColor: Colors.white, darkColor: Colors.white), + inactiveTextColor: AppColors.getThemeColor(context, lightColor: Colors.black, darkColor: Colors.white), + activeIcon: isStarting + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation(Colors.orange)), + ) + : isRunning + ? const Icon(Icons.check_circle, size: 16, color: Colors.green) + : null, + disabled: isStarting, + ), + ], + ), + ], + ); + }, + ), + ), + ), + ); + } + + return menuItems; + } +} diff --git a/lib/page/layout/widgets/model_selector.dart b/lib/page/layout/widgets/model_selector.dart new file mode 100644 index 0000000..bae2d8f --- /dev/null +++ b/lib/page/layout/widgets/model_selector.dart @@ -0,0 +1,185 @@ +import 'package:chatmcp/page/layout/widgets/llm_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/provider/chat_model_provider.dart'; +import 'package:chatmcp/llm/model.dart' as llm_model; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/components/widgets/custom_popup.dart'; + +class ModelSelector extends StatefulWidget { + const ModelSelector({super.key}); + + @override + State createState() => _ModelSelectorState(); +} + +class _ModelSelectorState extends State { + // 缓存future避免重复执行 + List _models = []; + + @override + void initState() { + super.initState(); + _updateModels(); + // 添加监听器 + ProviderManager.settingsProvider.addListener(_updateModels); + } + + @override + void dispose() { + // 移除监听器避免内存泄漏 + ProviderManager.settingsProvider.removeListener(_updateModels); + super.dispose(); + } + + void _updateModels() { + setState(() { + _models = ProviderManager.settingsProvider.availableModels; + }); + } + + bool isCurrentModel(llm_model.Model model) { + return model.name == ProviderManager.chatModelProvider.currentModel.name && + model.providerId == ProviderManager.chatModelProvider.currentModel.providerId; + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, chatModelProvider, child) { + return ModelSelectorPopup( + availableModels: _models, + isCurrentModel: isCurrentModel, + onModelSelected: (model) { + ProviderManager.chatModelProvider.currentModel = model; + }, + ); + }, + ); + } +} + +// 创建一个通知类来监听弹出窗口的打开状态 +class PopupNotification extends Notification { + final bool opened; + PopupNotification(this.opened); +} + +class ModelSelectorPopup extends StatefulWidget { + final List availableModels; + final bool Function(llm_model.Model) isCurrentModel; + final void Function(llm_model.Model) onModelSelected; + + const ModelSelectorPopup({super.key, required this.availableModels, required this.isCurrentModel, required this.onModelSelected}); + + @override + State createState() => _ModelSelectorPopupState(); +} + +class _ModelSelectorPopupState extends State { + // 按 provider 对模型进行分组并根据搜索文本过滤 + Map> _getFilteredModelsByProvider(String searchText) { + final modelsByProvider = >{}; + + // 筛选匹配搜索文本的模型 + final filteredModels = widget.availableModels.where((model) { + return searchText.isEmpty || model.label.toLowerCase().contains(searchText) || model.providerId.toLowerCase().contains(searchText); + }).toList(); + + for (var model in filteredModels) { + modelsByProvider.putIfAbsent(model.providerId, () => []).add(model); + } + + return modelsByProvider; + } + + // 构建模型列表 + Widget _buildModelList(String searchText) { + final modelsByProvider = _getFilteredModelsByProvider(searchText); + + if (modelsByProvider.isEmpty) { + return const PopupEmptyState(message: 'No results found'); + } + + final List items = []; + + modelsByProvider.forEach((provider, models) { + // 添加分隔线 + if (items.isNotEmpty) { + items.add(const PopupDivider()); + } + + final firstModel = models.first; + + // 添加提供商标题 + items.add( + PopupGroupHeader( + title: firstModel.providerName, + icon: LlmIcon(icon: firstModel.icon), + ), + ); + + // 添加该提供商下的所有模型 + for (var model in models) { + items.add( + PopupListItem( + onTap: () { + widget.onModelSelected(model); + Navigator.of(context).pop(); + }, + isSelected: widget.isCurrentModel(model), + padding: const EdgeInsets.fromLTRB(32, 6, 16, 6), + child: Text( + model.label, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: widget.isCurrentModel(model) ? AppColors.getTextButtonColor(context) : AppColors.getThemeTextColor(context), + ), + ), + ), + ); + } + }); + + return SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: items), + ); + } + + @override + Widget build(BuildContext context) { + final currentModel = widget.availableModels.firstWhere( + (model) => widget.isCurrentModel(model), + orElse: () => llm_model.Model(name: '', label: 'Loading...', providerId: '', icon: '', providerName: '', apiStyle: ''), + ); + + return SearchablePopup( + searchHint: 'Search', + contentBuilder: _buildModelList, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Row( + children: [ + LlmIcon(icon: currentModel.icon), + const SizedBox(width: 4), + Text( + currentModel.label, + style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: AppColors.getThemeTextColor(context)), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ], + ), + ), + const SizedBox(width: 4), + Icon(Icons.expand_more, size: 18, color: AppColors.getInactiveTextColor(context)), + ], + ), + ), + ); + } +} diff --git a/lib/page/layout/widgets/top_toolbar.dart b/lib/page/layout/widgets/top_toolbar.dart new file mode 100644 index 0000000..af87993 --- /dev/null +++ b/lib/page/layout/widgets/top_toolbar.dart @@ -0,0 +1,269 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import './model_selector.dart'; +import 'package:window_manager/window_manager.dart' as wm; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:provider/provider.dart'; +import 'package:chatmcp/provider/chat_provider.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:chatmcp/provider/mcp_server_provider.dart'; +// test page +import 'package:chatmcp/widgets/markdown/markit_widget.dart'; +import 'package:chatmcp/utils/event_bus.dart'; +import 'package:chatmcp/page/layout/widgets/chat_setting.dart'; +import 'package:chatmcp/widgets/upgrade.dart'; +import 'package:chatmcp/page/layout/widgets/window_controls.dart'; +import 'package:chatmcp/components/widgets/custom_popup.dart'; + +class TopToolbar extends StatelessWidget { + final bool hideSidebar; + final VoidCallback onToggleSidebar; + + const TopToolbar({super.key, required this.hideSidebar, required this.onToggleSidebar}); + + void _onShowChatSetting(BuildContext context) { + if (kIsMobile) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => Scaffold(body: SafeArea(child: const ChatSetting())), + ), + ); + } else { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + child: Padding(padding: const EdgeInsets.all(16), child: const ChatSetting()), + ), + ), + ); + } + } + + Widget _buildMoreMenu(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return BasePopup( + showArrow: true, + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (ProviderManager.chatProvider.activeChat != null) + InkWell( + onTap: () { + emit(ShareEvent(false)); + Navigator.of(context).pop(); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + const Icon(CupertinoIcons.share, size: 18), + const SizedBox(width: 12), + Text(l10n.share, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ), + ), + InkWell( + onTap: () { + _onShowChatSetting(context); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + const Icon(CupertinoIcons.slider_horizontal_3, size: 18), + const SizedBox(width: 12), + Text(l10n.modelConfig, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ), + ), + if (kIsDebug) + InkWell( + onTap: () { + Navigator.of(context).pop(); + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => Scaffold( + appBar: AppBar(title: Text(l10n.webSearchTest)), + body: const MarkitTestPage(), + ), + ), + ); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + const Icon(CupertinoIcons.ant, size: 18), + const SizedBox(width: 12), + Text(l10n.debug, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ), + ), + // delete chat + if (ProviderManager.chatProvider.activeChat != null) + InkWell( + onTap: () async { + final confirm = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.confirmDelete), + content: Text('${l10n.confirmThisChat}?'), + actions: [ + TextButton(onPressed: () => Navigator.of(context).pop(false), child: Text(MaterialLocalizations.of(context).cancelButtonLabel)), + TextButton(onPressed: () => Navigator.of(context).pop(true), child: Text(MaterialLocalizations.of(context).okButtonLabel)), + ], + ), + ); + if (confirm == true) { + final chat = ProviderManager.chatProvider.activeChat; + if (chat != null) { + ProviderManager.chatProvider.deleteChat(chat.id!); + } + Navigator.of(context).pop(); // Close the popup after deleting + } + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + const Icon(CupertinoIcons.delete, size: 18), + const SizedBox(width: 12), + Text(l10n.delete, style: TextStyle(color: AppColors.getThemeTextColor(context))), + ], + ), + ), + ), + ], + ), + maxWidth: 200, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: InkIcon(icon: CupertinoIcons.ellipsis_vertical, size: 18, tooltip: AppLocalizations.of(context)!.more), + ), + ); + } + + @override + Widget build(BuildContext context) { + return Consumer( + builder: (context, provider, child) { + return Consumer( + builder: (context, mcpProvider, child) { + return MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onDoubleTap: () async { + debugPrint('double tap'); + if (kIsDesktop) { + try { + bool isMaximized = await wm.windowManager.isMaximized(); + if (isMaximized) { + await wm.windowManager.unmaximize(); + } else { + await wm.windowManager.maximize(); + } + } catch (e) { + debugPrint('窗口操作失败: $e'); + } + } + }, + child: Container( + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: AppColors.getToolbarBottomBorderColor(context))), + ), + padding: kIsDesktop ? EdgeInsets.only(left: hideSidebar ? (kIsMacOS ? 70 : 8) : 0, top: 2) : null, + child: kIsDesktop ? wm.DragToMoveArea(child: _buildToolbarContent(context)) : _buildToolbarContent(context), + ), + ), + ); + }, + ); + }, + ); + } + + Widget _buildToolbarContent(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (hideSidebar && kIsDesktop) ...[ + // Show app logo and name when sidebar is hidden + if (!kIsMacOS) ...[ + Image.asset('assets/logo.png', width: 24, height: 24), + const Gap(size: 8), + CText(text: 'ChatMCP', size: 12, fontWeight: FontWeight.w700), + const Gap(size: 24), + ], + + InkIcon(icon: CupertinoIcons.sidebar_right, onTap: onToggleSidebar, tooltip: AppLocalizations.of(context)!.toggleSidebar), + const Gap(size: 8), + ], + Flexible( + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 50), + child: Row( + children: [ + if (kIsAndroid || (kIsBrowser && MediaQuery.of(context).size.width < 768)) ...[ + Gap(size: 12), + InkIcon( + icon: CupertinoIcons.sidebar_left, + onTap: () { + Scaffold.of(context).openDrawer(); + }, + ), + ], + const ModelSelector(), + ], + ), + ), + ), + ], + ), + ), + _buildDefaultToolbarActions(context), + ], + ); + } + + Widget _buildDefaultToolbarActions(BuildContext context) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width < 400 ? 30 : 120), + child: UpgradeNotice(), + ), + if (ProviderManager.chatProvider.activeChat != null) ...[ + Gap(size: 8), + InkIcon( + icon: CupertinoIcons.add, + onTap: () { + ProviderManager.chatProvider.clearActiveChat(); + }, + tooltip: AppLocalizations.of(context)!.newChat, + ), + ], + if (kIsWindows || kIsLinux) ...[const Gap(size: 8), const WindowControls()], + _buildMoreMenu(context), + ], + ); + } +} diff --git a/lib/page/layout/widgets/window_controls.dart b/lib/page/layout/widgets/window_controls.dart new file mode 100644 index 0000000..816297b --- /dev/null +++ b/lib/page/layout/widgets/window_controls.dart @@ -0,0 +1,75 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:flutter/material.dart'; +import 'package:window_manager/window_manager.dart' as wm; +import 'package:chatmcp/generated/app_localizations.dart'; + +class WindowControls extends StatelessWidget { + const WindowControls({super.key}); + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + _WindowButton( + icon: Icons.remove, + onPressed: () async { + await wm.windowManager.minimize(); + }, + tooltip: l10n.minimize, + ), + const Gap(size: 8), + _WindowButton( + icon: Icons.crop_square, + onPressed: () async { + bool isMaximized = await wm.windowManager.isMaximized(); + if (isMaximized) { + await wm.windowManager.unmaximize(); + } else { + await wm.windowManager.maximize(); + } + }, + tooltip: l10n.maximize, + ), + const Gap(size: 8), + _WindowButton( + icon: Icons.close, + onPressed: () async { + await wm.windowManager.close(); + }, + tooltip: l10n.close, + isCloseButton: true, + ), + ], + ); + } +} + +class _WindowButton extends StatefulWidget { + final IconData icon; + final VoidCallback onPressed; + final String tooltip; + final bool isCloseButton; + + const _WindowButton({required this.icon, required this.onPressed, required this.tooltip, this.isCloseButton = false}); + + @override + _WindowButtonState createState() => _WindowButtonState(); +} + +class _WindowButtonState extends State<_WindowButton> { + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + + Color backgroundColor = Colors.transparent; + + backgroundColor = widget.isCloseButton ? Colors.red : (isDark ? Colors.white24 : Colors.black12); + + return InkIcon(icon: widget.icon, onTap: widget.onPressed, hoverColor: backgroundColor, tooltip: widget.tooltip); + } +} diff --git a/lib/page/setting/general_setting.dart b/lib/page/setting/general_setting.dart new file mode 100644 index 0000000..b3ace37 --- /dev/null +++ b/lib/page/setting/general_setting.dart @@ -0,0 +1,534 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:provider/provider.dart'; +import '../../provider/settings_provider.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/toast.dart'; +import 'package:chatmcp/file_logger.dart'; + +import 'setting_switch.dart'; + +class GeneralSettings extends StatefulWidget { + const GeneralSettings({super.key}); + + @override + State createState() => _GeneralSettingsState(); +} + +class _GeneralSettingsState extends State { + final _formKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Form( + key: _formKey, + child: Column( + children: [ + Expanded( + child: ListView( + children: [ + const SizedBox(height: 10), + _buildThemeCard(context), + _buildLocaleCard(context), + _buildAvatarCard(context), + if (!kIsBrowser) _buildProxyCard(context), + _buildSystemPromptCard(context), + if (!kIsBrowser) _buildMaintenanceCard(context), + const SizedBox(height: 20), + ], + ), + ), + ], + ), + ), + ), + ), + ); + } + + Widget _buildSectionTitle(BuildContext context, String title, IconData icon) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0), + child: Row( + children: [ + Icon(icon, size: 14, color: Theme.of(context).colorScheme.primary), + const SizedBox(width: 8), + Text( + title, + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.primary), + ), + ], + ), + ); + } + + Widget _buildLocaleCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Consumer( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.languageSettings, CupertinoIcons.globe), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: ListTile( + title: CText(text: l10n.language), + trailing: DropdownButton( + value: settings.generalSetting.locale, + underline: const SizedBox(), + icon: Icon(CupertinoIcons.chevron_right, size: 16, color: Theme.of(context).colorScheme.onSurface.withAlpha(50)), + items: const [ + DropdownMenuItem( + value: 'en', + child: CText(text: 'English'), + ), + DropdownMenuItem( + value: 'zh', + child: CText(text: '中文'), + ), + DropdownMenuItem( + value: 'tr', + child: CText(text: 'Türkçe'), + ), + DropdownMenuItem( + value: 'de', + child: CText(text: 'Deutsch'), + ), + ], + onChanged: (String? value) { + if (value != null) { + settings.updateGeneralSettingsPartially(locale: value); + } + }, + ), + ), + ), + ], + ); + }, + ); + } + + Widget _buildThemeCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Consumer( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.themeSettings, CupertinoIcons.paintbrush), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(11), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 1.0), + child: DropdownButtonFormField( + value: settings.generalSetting.theme, + decoration: InputDecoration(border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(vertical: 2.0)), + icon: Icon(CupertinoIcons.chevron_right, size: 16, color: Theme.of(context).colorScheme.onSurface.withAlpha(50)), + items: [ + DropdownMenuItem( + value: 'light', + child: CText(text: l10n.lightTheme), + ), + DropdownMenuItem( + value: 'dark', + child: CText(text: l10n.darkTheme), + ), + DropdownMenuItem( + value: 'system', + child: CText(text: l10n.followSystem), + ), + ], + onChanged: (value) { + if (value != null) { + settings.updateGeneralSettingsPartially(theme: value); + } + }, + ), + ), + ), + ], + ); + }, + ); + } + + Widget _buildAvatarCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Consumer( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.showAvatar, CupertinoIcons.person_crop_circle), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: Column( + children: [ + SettingSwitch( + title: l10n.showAssistantAvatar, + subtitle: l10n.showAssistantAvatarDescription, + value: settings.generalSetting.showAssistantAvatar, + titleFontSize: 14, + subtitleFontSize: 12, + onChanged: (bool value) { + settings.updateGeneralSettingsPartially(showAssistantAvatar: value); + }, + ), + Divider(height: 1, indent: 16, endIndent: 16, color: Theme.of(context).colorScheme.outline.withAlpha(50)), + SettingSwitch( + title: l10n.showUserAvatar, + subtitle: l10n.showUserAvatarDescription, + value: settings.generalSetting.showUserAvatar, + titleFontSize: 14, + subtitleFontSize: 12, + onChanged: (bool value) { + settings.updateGeneralSettingsPartially(showUserAvatar: value); + }, + ), + ], + ), + ), + ], + ); + }, + ); + } + + Widget _buildProxyCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Consumer( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.proxySettings, CupertinoIcons.globe), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 启用代理开关 + SettingSwitch( + title: l10n.enableProxy, + subtitle: l10n.enableProxyDescription, + value: settings.generalSetting.enableProxy, + titleFontSize: 14, + subtitleFontSize: 12, + onChanged: (bool value) { + settings.updateGeneralSettingsPartially(enableProxy: value); + ToastUtils.success(l10n.saved); + }, + ), + + // 如果启用代理,显示代理配置选项 + if (settings.generalSetting.enableProxy) ...[ + const SizedBox(height: 16), + Divider(height: 1, color: Theme.of(context).colorScheme.outline.withAlpha(50)), + const SizedBox(height: 16), + + // 代理类型选择 + Row( + children: [ + Expanded( + flex: 2, + child: Text( + l10n.proxyType, + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + ), + Expanded( + flex: 3, + child: DropdownButtonFormField( + value: settings.generalSetting.proxyType, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(20)), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + items: const [ + DropdownMenuItem( + value: 'HTTP', + child: CText(text: 'HTTP'), + ), + DropdownMenuItem( + value: 'HTTPS', + child: CText(text: 'HTTPS'), + ), + DropdownMenuItem( + value: 'SOCKS4', + child: CText(text: 'SOCKS4'), + ), + DropdownMenuItem( + value: 'SOCKS5', + child: CText(text: 'SOCKS5'), + ), + ], + onChanged: (value) { + if (value != null) { + settings.updateGeneralSettingsPartially(proxyType: value); + ToastUtils.success(l10n.saved); + } + }, + ), + ), + ], + ), + const SizedBox(height: 16), + + // 代理地址和端口 + Row( + children: [ + Expanded( + flex: 3, + child: TextFormField( + initialValue: settings.generalSetting.proxyHost, + decoration: InputDecoration( + labelText: l10n.proxyHost, + hintText: l10n.enterProxyHost, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + validator: (value) { + if (settings.generalSetting.enableProxy && (value == null || value.isEmpty)) { + return l10n.proxyHostRequired; + } + return null; + }, + onChanged: (value) { + settings.updateGeneralSettingsPartially(proxyHost: value); + if (value.isNotEmpty) { + ToastUtils.success(l10n.saved); + } + }, + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 1, + child: TextFormField( + initialValue: settings.generalSetting.proxyPort.toString(), + decoration: InputDecoration( + labelText: l10n.proxyPort, + hintText: l10n.enterProxyPort, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + keyboardType: TextInputType.number, + validator: (value) { + if (value == null || value.isEmpty) { + return null; + } + final port = int.tryParse(value); + if (port == null || port < 1 || port > 65535) { + return l10n.proxyPortInvalid; + } + return null; + }, + onChanged: (value) { + final port = int.tryParse(value); + if (port != null && port >= 1 && port <= 65535) { + settings.updateGeneralSettingsPartially(proxyPort: port); + ToastUtils.success(l10n.saved); + } + }, + ), + ), + ], + ), + const SizedBox(height: 16), + + // 用户名和密码(可选) + Row( + children: [ + Expanded( + child: TextFormField( + initialValue: settings.generalSetting.proxyUsername, + decoration: InputDecoration( + labelText: l10n.proxyUsername, + hintText: l10n.enterProxyUsername, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + onChanged: (value) { + settings.updateGeneralSettingsPartially(proxyUsername: value); + ToastUtils.success(l10n.saved); + }, + ), + ), + const SizedBox(width: 12), + Expanded( + child: TextFormField( + initialValue: settings.generalSetting.proxyPassword, + decoration: InputDecoration( + labelText: l10n.proxyPassword, + hintText: l10n.enterProxyPassword, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + obscureText: true, + onChanged: (value) { + settings.updateGeneralSettingsPartially(proxyPassword: value); + ToastUtils.success(l10n.saved); + }, + ), + ), + ], + ), + ], + ], + ), + ), + ), + ], + ); + }, + ); + } + + Widget _buildSystemPromptCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Consumer( + builder: (context, settings, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.systemPrompt, CupertinoIcons.text_quote), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextFormField( + initialValue: settings.generalSetting.systemPrompt, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(20)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(20)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.all(12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + maxLines: 5, + onChanged: (value) { + settings.updateGeneralSettingsPartially(systemPrompt: value); + }, + ), + const SizedBox(height: 8), + Text(l10n.systemPromptDescription, style: TextStyle(fontSize: 13, color: Theme.of(context).colorScheme.onSurface.withAlpha(60))), + ], + ), + ), + ), + ], + ); + }, + ); + } + + Widget _buildMaintenanceCard(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSectionTitle(context, l10n.maintenance, CupertinoIcons.wrench), + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(50)), + ), + child: ListTile( + leading: Icon(CupertinoIcons.delete, color: Theme.of(context).colorScheme.onSurface.withAlpha(200)), + title: CText(text: l10n.cleanupLogs), + subtitle: CText(text: l10n.cleanupLogsDescription), + trailing: Icon(CupertinoIcons.chevron_right, size: 16, color: Theme.of(context).colorScheme.onSurface.withAlpha(50)), + onTap: () async { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: CText(text: l10n.confirmCleanup), + content: CText(text: l10n.confirmCleanupMessage), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: CText(text: l10n.cancel), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(true), + child: CText(text: l10n.confirm), + ), + ], + ), + ); + + if (confirmed == true) { + try { + await FileLogger.cleanupOldLogs(days: 0); + if (mounted) { + ToastUtils.success(l10n.cleanupSuccess); + } + } catch (e) { + if (mounted) { + ToastUtils.error('${l10n.cleanupFailed}: $e'); + } + } + } + }, + ), + ), + ], + ); + } +} diff --git a/lib/page/setting/llm_setting.dart b/lib/page/setting/llm_setting.dart new file mode 100644 index 0000000..ce0c538 --- /dev/null +++ b/lib/page/setting/llm_setting.dart @@ -0,0 +1,1350 @@ +import 'dart:convert'; + +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:chatmcp/llm/llm_factory.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/toast.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:http/http.dart'; +import 'package:provider/provider.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:uuid/uuid.dart'; +import '../../provider/settings_provider.dart'; +import '../../provider/provider_manager.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter_switch/flutter_switch.dart'; +import 'package:chatmcp/page/layout/widgets/llm_icon.dart'; + +class LLMSettingControllers { + TextEditingController keyController; + TextEditingController endpointController; + TextEditingController apiVersionController; + String apiStyleController; + TextEditingController providerNameController; + List models = []; + List enabledModels = []; + String providerId; + bool custom = false; + String icon = ''; + String genTitleModel = ''; + String link; + int priority; + LLMSettingControllers({ + required this.keyController, + required this.endpointController, // 默认版本 + required this.apiVersionController, + this.apiStyleController = 'openai', + required this.providerNameController, + this.providerId = '', + this.custom = false, + this.icon = '', + List? models, + List? enabledModels, + this.genTitleModel = '', + this.link = '', + this.priority = 0, + }) { + this.models = models ?? []; + this.enabledModels = enabledModels ?? []; + } + + void dispose() { + keyController.dispose(); + endpointController.dispose(); + apiVersionController.dispose(); + providerNameController.dispose(); + } +} + +class KeysSettings extends StatefulWidget { + const KeysSettings({super.key}); + + @override + State createState() => _KeysSettingsState(); +} + +class _KeysSettingsState extends State { + final _formKey = GlobalKey(); + bool _isLoading = false; + int _selectedProvider = 0; + bool _hasChanges = false; + bool _obscureText = true; // 添加密码可见性状态 + + final List _controllers = []; + + // 记录每个卡片的展开状态 + final Map _expandedState = {}; + + final List _llmApiConfigs = []; + + void _addModelsWithoutDuplicates(LLMSettingControllers controllers, List newModels) { + for (var model in newModels) { + if (!controllers.models.contains(model)) { + controllers.models.add(model); + } + } + + if (controllers.enabledModels.isEmpty) { + controllers.enabledModels.addAll(newModels); + } else { + for (var model in newModels) { + if (!controllers.enabledModels.contains(model)) { + controllers.enabledModels.add(model); + } + } + } + + controllers.enabledModels.sort((a, b) => controllers.models.indexOf(a) - controllers.models.indexOf(b)); + setState(() { + _hasChanges = true; + }); + } + + @override + void initState() { + super.initState(); + _loadSettings(); + } + + @override + void dispose() { + for (var controller in _controllers) { + controller.dispose(); + } + super.dispose(); + } + + Future _loadSettings() async { + final settings = Provider.of(context, listen: false); + final apiSettings = await settings.loadSettings(); + + setState(() { + _llmApiConfigs.clear(); + _controllers.clear(); + }); + + // 添加所有加载的设置 + for (var apiSetting in apiSettings) { + setState(() { + _llmApiConfigs.add(apiSetting); + // 为每个配置添加一个控制器 + _controllers.add( + LLMSettingControllers( + keyController: TextEditingController(text: apiSetting.apiKey), + endpointController: TextEditingController(text: apiSetting.apiEndpoint), + apiVersionController: TextEditingController(text: apiSetting.apiVersion), + apiStyleController: apiSetting.apiStyle ?? 'openai', + providerNameController: TextEditingController(text: apiSetting.providerName ?? ''), + providerId: apiSetting.providerId ?? '', + custom: apiSetting.custom, + models: apiSetting.models ?? [], + enabledModels: apiSetting.enabledModels ?? [], + icon: apiSetting.icon, + genTitleModel: apiSetting.genTitleModel ?? '', + link: apiSetting.link ?? '', + priority: apiSetting.priority ?? 0, + ), + ); + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Form( + key: _formKey, + onChanged: () { + if (!_hasChanges) { + setState(() { + _hasChanges = true; + }); + } + }, + child: LayoutBuilder( + builder: (context, constraints) { + final isMobile = constraints.maxWidth < 600; + return isMobile ? _buildMobileLayout() : _buildDesktopLayout(); + }, + ), + ), + ), + ), + ); + } + + // 构建移动端布局 + Widget _buildMobileLayout() { + return Column( + children: [ + // 配置卡片列表 + Expanded( + child: ListView.separated( + padding: const EdgeInsets.only(top: 4), + itemCount: _llmApiConfigs.length, + separatorBuilder: (context, index) => const SizedBox(height: 12), + itemBuilder: (context, index) => _buildProviderConfigCard(index), + ), + ), + const SizedBox(height: 12), + // 底部按钮区域 + Column( + children: [ + // 保存按钮 + _buildSaveButton(), + const SizedBox(height: 12), + // 添加服务器按钮 + _buildAddServerButton(), + ], + ), + ], + ); + } + + // 构建提供商配置卡片 + Widget _buildProviderConfigCard(int index) { + final config = _llmApiConfigs[index]; + final controllers = _controllers[index]; + + // 初始化展开状态,默认不展开 + _expandedState[index] ??= false; + + return Card( + elevation: 0, + margin: EdgeInsets.zero, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 卡片头部(点击可折叠) + InkWell( + onTap: () { + setState(() { + _expandedState[index] = !(_expandedState[index] ?? false); + }); + }, + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + children: [ + Expanded(child: _buildProviderCardHeader(config, controllers)), + Icon( + _expandedState[index] ?? false ? CupertinoIcons.chevron_up : CupertinoIcons.chevron_down, + size: 18, + color: Theme.of(context).colorScheme.onSurface.withAlpha(153), + ), + ], + ), + ), + ), + // 展开的配置内容 + if (_expandedState[index] ?? false) + Padding(padding: const EdgeInsets.fromLTRB(16.0, 0, 16.0, 16.0), child: _buildProviderConfigForm(index, showTitle: false)), + ], + ), + ); + } + + // 构建提供商卡片头部 + Widget _buildProviderCardHeader(LLMProviderSetting config, LLMSettingControllers controllers) { + final isEnabled = config.enable ?? true; // null 表示启用,只有 false 为禁用 + + return Row( + children: [ + LlmIcon(icon: config.icon), + const SizedBox(width: 8), + Expanded( + child: Text( + config.providerName ?? '', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface), + ), + ), + SizedBox( + width: 35.0, + child: FlutterSwitch( + value: isEnabled, + onToggle: (value) { + setState(() { + final index = _llmApiConfigs.indexOf(config); + if (index != -1) { + _llmApiConfigs[index].enable = value ? null : false; + _hasChanges = true; + } + }); + }, + width: 32.0, + height: 18.0, + toggleSize: 14.0, + borderRadius: 10.0, + padding: 1.5, + activeColor: Theme.of(context).colorScheme.primary, + inactiveColor: Theme.of(context).colorScheme.outline.withAlpha(76), + toggleColor: Colors.white, + ), + ), + const SizedBox(width: 4), + if (config.custom) + IconButton( + icon: const Icon(CupertinoIcons.delete, size: 18), + color: Colors.red, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () => _deleteProvider(config), + ), + ], + ); + } + + // 构建保存按钮 + Widget _buildSaveButton() { + final l10n = AppLocalizations.of(context)!; + return SizedBox( + width: double.infinity, + height: 44, + child: ElevatedButton( + onPressed: _isLoading || !_hasChanges ? null : _saveSettings, + style: ElevatedButton.styleFrom( + backgroundColor: _hasChanges ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.surfaceContainerHighest, + foregroundColor: _hasChanges ? Theme.of(context).colorScheme.onPrimary : Theme.of(context).colorScheme.onSurfaceVariant, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + elevation: _hasChanges ? 0 : 0, + padding: EdgeInsets.zero, + ), + child: _isLoading + ? const CupertinoActivityIndicator() + : Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + CupertinoIcons.checkmark_circle, + size: 18, + color: _hasChanges ? Theme.of(context).colorScheme.onPrimary : Theme.of(context).colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + CText(text: l10n.saveSettings), + ], + ), + ), + ); + } + + // 构建添加服务器按钮 + Widget _buildAddServerButton() { + final l10n = AppLocalizations.of(context)!; + return SizedBox( + width: double.infinity, + height: 44, + child: OutlinedButton.icon( + icon: Icon(CupertinoIcons.add_circled, size: 18, color: Theme.of(context).colorScheme.primary), + label: Text(l10n.addProvider), + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + side: BorderSide(color: Theme.of(context).colorScheme.primary), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + ), + onPressed: () => _showAddProviderDialog(), + ), + ); + } + + // 删除提供商的方法 + void _deleteProvider(LLMProviderSetting config) { + setState(() { + final index = _llmApiConfigs.indexOf(config); + if (index != -1) { + _llmApiConfigs.removeAt(index); + _controllers.removeAt(index); + if (_selectedProvider >= _llmApiConfigs.length) { + _selectedProvider = _llmApiConfigs.length - 1; + } + _hasChanges = true; + } + }); + } + + // 构建桌面端布局 + Widget _buildDesktopLayout() { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 左侧提供商列表 + SizedBox(width: 220, child: _buildProviderList()), + const SizedBox(width: 12), + // 右侧配置表单 + Expanded(child: _buildDesktopConfigSection()), + ], + ); + } + + // 构建提供商列表 + Widget _buildProviderList() { + return Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: Column( + children: [ + Expanded( + child: ListView.builder( + // itemExtent: 48.0, + itemCount: _llmApiConfigs.length, + itemBuilder: (context, index) { + final config = _llmApiConfigs[index]; + return _buildProviderListTile(index, config); + }, + ), + ), + Divider(color: Theme.of(context).colorScheme.outline.withAlpha(26), height: 1), + _buildAddServerListTile(), + ], + ), + ); + } + + // 构建添加服务器列表项 + Widget _buildAddServerListTile() { + final l10n = AppLocalizations.of(context)!; + return SizedBox( + height: 40, + child: ListTile( + dense: true, + title: Row( + children: [ + Icon(CupertinoIcons.add_circled, size: 18, color: Theme.of(context).colorScheme.primary), + const SizedBox(width: 8), + Text( + l10n.addProvider, + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.primary), + ), + ], + ), + onTap: () => _showAddProviderDialog(), + ), + ); + } + + // 构建桌面端配置区域 + Widget _buildDesktopConfigSection() { + return Column( + children: [ + Expanded( + child: Card( + elevation: 0, + margin: EdgeInsets.zero, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: Padding(padding: const EdgeInsets.all(12.0), child: _buildProviderConfigForm(_selectedProvider)), + ), + ), + const SizedBox(height: 12), + _buildSaveButton(), + ], + ); + } + + Future _showAddProviderDialog() async { + final l10n = AppLocalizations.of(context)!; + showDialog( + context: context, + builder: (context) { + final TextEditingController providerController = TextEditingController(); + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text(l10n.addProvider), + content: TextField( + controller: providerController, + decoration: InputDecoration(hintText: l10n.providerName), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.pop(context); + }, + child: Text(l10n.cancel), + ), + TextButton( + onPressed: () { + final providerName = providerController.text.trim(); + if (providerName.isNotEmpty) { + setState(() { + String providerId = Uuid().v4(); + _llmApiConfigs.add( + LLMProviderSetting( + providerName: providerName, + providerId: providerId, + apiKey: '', + apiEndpoint: '', + apiStyle: 'openai', + custom: true, + models: [], + enabledModels: [], + icon: '', + enable: null, // 默认启用 + ), + ); + _controllers.add( + LLMSettingControllers( + keyController: TextEditingController(), + endpointController: TextEditingController(), + apiVersionController: TextEditingController(), + providerNameController: TextEditingController(text: providerName), + providerId: providerId, + custom: true, + models: [], + enabledModels: [], + icon: '', + genTitleModel: '', + ), + ); + }); + } + Navigator.pop(context); + }, + child: Text(l10n.confirm), + ), + ], + ); + }, + ); + } + + Future _showAddModelDialog() async { + final l10n = AppLocalizations.of(context)!; + showDialog( + context: context, + builder: (context) { + final TextEditingController modelController = TextEditingController(); + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text(l10n.addModel), + content: TextField( + controller: modelController, + decoration: InputDecoration( + hintText: l10n.enterModelName, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.pop(context); + }, + child: Text(l10n.cancel), + ), + TextButton( + onPressed: () { + final modelName = modelController.text.trim(); + if (modelName.isNotEmpty) { + setState(() { + if (_controllers.isNotEmpty) { + // 将模型添加到当前选中的提供商 + final controller = _controllers[_selectedProvider]; + if (!controller.models.contains(modelName)) { + controller.models.add(modelName); + controller.enabledModels.add(modelName); + _hasChanges = true; + } + } + }); + } + Navigator.pop(context); + }, + child: Text(l10n.confirm), + ), + ], + ); + }, + ); + } + + Widget _buildProviderListTile(int index, LLMProviderSetting config) { + final isSelected = _selectedProvider == index; + final isEnabled = config.enable ?? true; // null 表示启用,只有 false 为禁用 + + return ListTile( + dense: true, + visualDensity: VisualDensity.compact, + contentPadding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 0), + selected: isSelected, + selectedTileColor: Theme.of(context).colorScheme.primary.withAlpha(31), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + leading: SizedBox(width: 20, child: LlmIcon(icon: config.icon)), + title: Text( + config.providerName ?? '', + style: TextStyle( + fontSize: 13, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500, + color: isSelected ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.onSurface, + ), + ), + trailing: SizedBox( + width: 35.0, + child: FlutterSwitch( + value: isEnabled, + onToggle: (value) { + setState(() { + _llmApiConfigs[index].enable = value ? null : false; + _hasChanges = true; + }); + }, + width: 32.0, + height: 18.0, + toggleSize: 14.0, + borderRadius: 10.0, + padding: 1.5, + activeColor: Theme.of(context).colorScheme.primary, + inactiveColor: Theme.of(context).colorScheme.outline.withAlpha(76), + toggleColor: Colors.white, + ), + ), + onTap: () { + setState(() { + _selectedProvider = index; + }); + }, + ); + } + + Widget _buildProviderConfigForm(int index, {bool showTitle = true}) { + // 安全检查:确保索引有效且数组不为空 + if (_llmApiConfigs.isEmpty || _controllers.isEmpty || index < 0 || index >= _llmApiConfigs.length || index >= _controllers.length) { + // 返回一个空白界面或提示信息 + final l10n = AppLocalizations.of(context)!; + return Center( + child: Text(l10n.noApiConfigs, style: TextStyle(fontSize: 16, color: Theme.of(context).colorScheme.onSurface)), + ); + } + + final config = _llmApiConfigs[index]; + final controllers = _controllers[index]; + final l10n = AppLocalizations.of(context)!; + + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 提供商标题 + if (showTitle) ...[ + Row( + children: [ + LlmIcon(icon: config.icon), + const SizedBox(width: 8), + Expanded( + child: Text( + config.providerName ?? '', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface), + ), + ), + if (config.custom) + IconButton( + icon: const Icon(CupertinoIcons.delete, size: 18), + color: Colors.red, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () { + setState(() { + _llmApiConfigs.removeAt(_selectedProvider); + _controllers.removeAt(_selectedProvider); + if (_selectedProvider >= _llmApiConfigs.length) { + _selectedProvider = _llmApiConfigs.length - 1; + } + _hasChanges = true; + }); + }, + ), + ], + ), + const SizedBox(height: 16), + ], + + // Provider Name + Text( + l10n.providerName, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 4), + TextFormField( + controller: controllers.providerNameController, + decoration: InputDecoration( + hintText: l10n.enterProviderName, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + validator: (value) { + if (value == null || value.isEmpty) { + return l10n.providerNameRequired; + } + if (value.length > 50) { + return l10n.serverNameTooLong; + } + return null; + }, + maxLength: 50, + buildCounter: (context, {required currentLength, required isFocused, maxLength}) { + return null; // 隐藏字符计数器 + }, + ), + const SizedBox(height: 12), + + // API 风格 + if (config.custom) ...[ + Text( + l10n.apiStyle, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 4), + DropdownButtonFormField( + value: controllers.apiStyleController, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + isDense: true, + icon: Icon(CupertinoIcons.chevron_down, size: 16, color: Theme.of(context).colorScheme.onSurface), + items: [ + DropdownMenuItem( + value: 'openai', + child: Text('OpenAI', style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface)), + ), + DropdownMenuItem( + value: 'claude', + child: Text('Claude', style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface)), + ), + DropdownMenuItem( + value: 'gemini', + child: Text('Gemini', style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface)), + ), + ], + onChanged: (value) { + if (value != null) { + setState(() { + controllers.apiStyleController = value; + }); + } + }, + validator: (value) { + if (value == null || value.isEmpty) { + return l10n.selectApiStyle; + } + return null; + }, + ), + const SizedBox(height: 12), + ], + + // API URL + Text( + l10n.apiUrl, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 4), + TextFormField( + controller: controllers.endpointController, + decoration: InputDecoration( + hintText: l10n.enterApiEndpoint, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 12), + + if (config.providerId == 'copilot') _copilotOAuthButtonList(), + + // API Version + if (config.providerId == 'foundry') ...[ + Text( + l10n.apiVersion, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 4), + TextFormField( + controller: controllers.apiVersionController, + decoration: InputDecoration( + //enabled: false, + hintText: l10n.enterApiVersion, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 12), + ], + + // API Key + Row( + children: [ + Text( + l10n.apiKey, + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + Gap(size: 4), + if (config.link != null && config.link!.isNotEmpty) + TextButton( + onPressed: () async { + await launchUrl(Uri.parse(config.link!)); + }, + child: Text(l10n.getApiKey, style: TextStyle(fontSize: 10, color: AppColors.blue)), + ), + ], + ), + const SizedBox(height: 4), + TextFormField( + controller: controllers.keyController, + obscureText: _obscureText, + decoration: InputDecoration( + hintText: l10n.enterApiKey(config.providerName ?? ''), + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + isDense: true, + suffixIcon: IconButton( + icon: Icon(_obscureText ? CupertinoIcons.eye_slash : CupertinoIcons.eye, size: 16), + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () { + setState(() { + _obscureText = !_obscureText; + }); + }, + ), + ), + style: TextStyle(fontSize: 14, color: Theme.of(context).colorScheme.onSurface), + validator: (value) { + if (value != null && value.isNotEmpty && value.length < 10) { + return l10n.apiKeyValidation; + } + return null; + }, + ), + const SizedBox(height: 12), + + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Text( + '${l10n.modelList} (${controllers.models.length})', + style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface), + ), + Spacer(), + if (kIsDesktop) ...[ + // choose gen title model + const Gap(size: 12), + _buildGenTitleModel(controllers), + ], + // add custom model + OutlinedButton.icon( + icon: const Icon(Icons.add_circle_outline, size: 14), + label: Text(l10n.add, style: const TextStyle(fontSize: 12)), + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + side: BorderSide(color: Theme.of(context).colorScheme.primary), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + minimumSize: const Size(0, 30), + ), + onPressed: () { + _showAddModelDialog(); + }, + ), + const SizedBox(width: 8), + // fetch models + OutlinedButton.icon( + icon: const Icon(CupertinoIcons.checkmark_seal, size: 14), + label: Text(l10n.fetch, style: const TextStyle(fontSize: 12)), + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + side: BorderSide(color: Theme.of(context).colorScheme.primary), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + minimumSize: const Size(0, 30), + ), + onPressed: () async { + var provider = LLMFactoryHelper.providerMap[controllers.providerId]; + + provider ??= LLMProvider.values.byName(controllers.apiStyleController); + + final llm = LLMFactory.create( + provider, + apiKey: controllers.keyController.text, + baseUrl: controllers.endpointController.text, + apiVersion: controllers.apiVersionController.text, + ); + + try { + final models = await llm.models(); + setState(() { + _addModelsWithoutDuplicates(controllers, models); + // 设置变更标志 + _hasChanges = true; + }); + } catch (e) { + ToastUtils.error('Failed to fetch models: $e'); + } + }, + ), + const Gap(size: 8), + // reset models + OutlinedButton.icon( + icon: const Icon(CupertinoIcons.arrow_counterclockwise, size: 14), + label: Text(l10n.reset, style: const TextStyle(fontSize: 12)), + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + side: BorderSide(color: Theme.of(context).colorScheme.primary), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + minimumSize: const Size(0, 30), + ), + onPressed: () async { + var provider = LLMFactoryHelper.providerMap[controllers.providerId]; + + provider ??= LLMProvider.values.byName(controllers.apiStyleController); + + final llm = LLMFactory.create( + provider, + apiKey: controllers.keyController.text, + baseUrl: controllers.endpointController.text, + apiVersion: controllers.apiVersionController.text, + ); + + final models = await llm.models(); + setState(() { + controllers.models.clear(); + controllers.enabledModels.clear(); + _hasChanges = true; + + _addModelsWithoutDuplicates(controllers, models); + // 设置变更标志 + _hasChanges = true; + }); + }, + ), + ], + ), + + // 模型列表 + const SizedBox(height: 12), + + if (!kIsDesktop) ...[const SizedBox(height: 12), _buildGenTitleModel(controllers), const SizedBox(height: 12)], + + // 模型列表,直接显示所有模型 + ...controllers.models.map((model) => _buildModelListItem(model, controllers.enabledModels.contains(model))), + const SizedBox(height: 8), // 底部留一些空间 + ], + ), + ); + } + + Widget _buildGenTitleModel(LLMSettingControllers controllers) { + final l10n = AppLocalizations.of(context)!; + return Center( + child: Container( + width: kIsDesktop ? 180 : double.infinity, + height: kIsDesktop ? null : 40, + margin: const EdgeInsets.only(right: 8), + child: DropdownButtonFormField( + value: controllers.enabledModels.contains(controllers.genTitleModel) + ? controllers.genTitleModel + : (controllers.enabledModels.isNotEmpty ? controllers.enabledModels.first : null), + decoration: InputDecoration( + labelText: l10n.genTitleModel, + labelStyle: TextStyle(fontSize: 12), + contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + isDense: true, + ), + icon: Icon(CupertinoIcons.chevron_down, size: 14, color: Theme.of(context).colorScheme.onSurface), + style: TextStyle(fontSize: 12), + isExpanded: true, + items: controllers.enabledModels + .map( + (model) => DropdownMenuItem( + value: model, + child: Text( + model, + style: TextStyle(fontSize: 12, color: Theme.of(context).colorScheme.onSurface), + overflow: TextOverflow.ellipsis, + ), + ), + ) + .toList(), + onChanged: (value) { + if (value != null) { + setState(() { + controllers.genTitleModel = value; + _hasChanges = true; + }); + } + }, + ), + ), + ); + } + + Widget _buildModelListItem(String modelName, bool isEnabled) { + if (_selectedProvider < 0 || _selectedProvider >= _controllers.length) { + return const SizedBox(); // 防止索引错误 + } + + final controllers = _controllers[_selectedProvider]; + final l10n = AppLocalizations.of(context)!; + // 检查模型是否在启用列表中 + bool modelEnabled = controllers.enabledModels.contains(modelName); + + return Container( + margin: const EdgeInsets.only(bottom: 6), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + border: Border.all(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Expanded( + child: Text(modelName, style: TextStyle(fontSize: 13, color: Theme.of(context).colorScheme.onSurface)), + ), + // delete model + Container( + width: 32, + height: 32, + alignment: Alignment.center, + margin: const EdgeInsets.only(right: 12), + child: IconButton( + icon: const Icon(CupertinoIcons.delete, size: 14), + color: Colors.red, + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + onPressed: () { + setState(() { + // 从两个列表中删除模型 + controllers.models.remove(modelName); + controllers.enabledModels.remove(modelName); + // 设置变更标志 + _hasChanges = true; + }); + }, + ), + ), + SizedBox( + width: 50, + child: FlutterSwitch( + width: 50.0, + height: 24.0, + value: modelEnabled, + onToggle: (val) { + setState(() { + // 更新模型启用状态 + if (val) { + // 启用模型 + if (!controllers.enabledModels.contains(modelName)) { + controllers.enabledModels.add(modelName); + // 确保enabledModels按照models中的顺序排序 + controllers.enabledModels.sort((a, b) => controllers.models.indexOf(a) - controllers.models.indexOf(b)); + } + } else { + // 禁用模型 + controllers.enabledModels.remove(modelName); + } + // 设置变更标志 + _hasChanges = true; + }); + }, + toggleSize: 18.0, + activeColor: Colors.blue, + inactiveColor: Colors.grey[300]!, + activeToggleColor: Colors.white, + inactiveToggleColor: Colors.grey[500]!, + showOnOff: true, + activeText: l10n.on, + inactiveText: l10n.off, + valueFontSize: 9.0, + activeTextColor: Colors.white, + inactiveTextColor: Colors.black, + ), + ), + ], + ), + ); + } + + Widget _copilotOAuthButtonList() { + return Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () async { + githubCopilotOAuth + .getCopilotDeviceCode() + .then((success) { + if (success) { + setState(() { + _hasChanges = true; + }); + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: const Text('Device Authorization'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SelectableText('User Code: ${githubCopilotOAuth.userCode ?? ""}', style: const TextStyle(fontWeight: FontWeight.bold)), + const SizedBox(height: 12), + Text('Please enter this code at:'), + InkWell( + child: Text( + githubCopilotOAuth.verificationUri ?? 'https://github.com/login/device', + style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline), + ), + onTap: () async { + final url = githubCopilotOAuth.verificationUri ?? 'https://github.com/login/device'; + await launchUrl(Uri.parse(url)); + }, + ), + ], + ), + actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('OK'))], + ); + }, + ); + ToastUtils.success('Device code fetched successfully'); + } else { + ToastUtils.error('Failed to fetch device code'); + } + }) + .catchError((error) { + ToastUtils.error('Error fetching device code: $error'); + }); + }, + child: const Text('Get Device Code'), + ), + const SizedBox(width: 12), + ElevatedButton( + onPressed: githubCopilotOAuth.userCode == null + ? null + : () { + githubCopilotOAuth + .getCopilotAccessToken() + .then((token) { + setState(() { + _controllers[_selectedProvider].keyController.text = token; + _hasChanges = true; + }); + ToastUtils.success('Token fetched successfully'); + }) + .catchError((error) { + ToastUtils.error('Failed to fetch token: $error'); + }); + }, // Disabled + child: const Text('Get Token'), + ), + ], + ); + } + + Future _saveSettings() async { + if (_formKey.currentState!.validate()) { + setState(() { + _isLoading = true; + }); + + try { + final settings = ProviderManager.settingsProvider; + + await settings.updateApiSettings( + apiSettings: _controllers + .map( + (e) => LLMProviderSetting( + providerId: e.providerId, + providerName: e.providerNameController.text, + apiKey: e.keyController.text, + apiEndpoint: e.endpointController.text, + apiVersion: e.apiVersionController.text, + apiStyle: e.apiStyleController, + custom: e.custom, + models: e.models, + enabledModels: e.enabledModels, + icon: e.icon, + genTitleModel: e.genTitleModel, + link: e.link, + priority: e.priority, + enable: _llmApiConfigs[_controllers.indexOf(e)].enable, + ), + ) + .toList(), + ); + + // 重置变更状态 + if (mounted) { + setState(() { + _hasChanges = false; + }); + } + + if (mounted) { + ToastUtils.success(AppLocalizations.of(context)!.saveSuccess); + } + } finally { + if (mounted) { + setState(() => _isLoading = false); + } + } + } + } + + final githubCopilotOAuth = GithubCopilotOAuth(clientId: "YOUR_CLIENT_ID_HERE"); +} + +class GithubCopilotOAuth { + final String clientId; // Replace with your actual client_id + final String scope = 'read:user'; + final String grantType = 'urn:ietf:params:oauth:grant-type:device_code'; + final Map headers = {'Accept': 'application/json'}; + final Map apiUrls = { + 'GITHUB_USER': 'https://api.github.com/user', + 'GITHUB_DEVICE_CODE': 'https://github.com/login/device/code', + 'GITHUB_ACCESS_TOKEN': 'https://github.com/login/oauth/access_token', + 'COPILOT_TOKEN': 'https://api.github.com/copilot_internal/v2/token', + }; + String? deviceCode; + String? userCode; + String? verificationUri; + + GithubCopilotOAuth({required this.clientId}); + + Map toJson() { + return { + 'clientId': clientId, + 'scope': scope, + 'headers': headers, + 'apiUrls': apiUrls, + 'deviceCode': deviceCode, + 'userCode': userCode, + 'verificationUri': verificationUri, + }; + } + + Future getCopilotDeviceCode() async { + // Füge die Parameter korrekt zur URI hinzu + final baseUri = Uri.parse(apiUrls['GITHUB_DEVICE_CODE']); + final requestBody = {'client_id': clientId, 'scope': scope}; + final uri = Uri(scheme: baseUri.scheme, host: baseUri.host, path: baseUri.path, queryParameters: requestBody); + final response = await post(uri, headers: headers); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + deviceCode = data['device_code']; + userCode = data['user_code']; + verificationUri = data['verification_uri']; + return true; + } else { + return false; + } + } + + Future getCopilotAccessToken() async { + if (deviceCode == null) { + throw Exception('Device code is not set. Call getCopilotDeviceCode first.'); + } + + final baseUri = Uri.parse(apiUrls['GITHUB_ACCESS_TOKEN']); + final requestBody = {'client_id': clientId, 'device_code': deviceCode, 'grant_type': grantType}; + final uri = Uri(scheme: baseUri.scheme, host: baseUri.host, path: baseUri.path, queryParameters: requestBody); + + final response = await post(uri, headers: headers); + + if (response.statusCode == 200) { + // Handle success, parse response.body + final data = jsonDecode(response.body); + return data['access_token']; + } else { + // Handle error + throw Exception('Failed to get access token: ${response.statusCode} ${response.body}'); + } + } +} diff --git a/lib/page/setting/mcp_info.dart b/lib/page/setting/mcp_info.dart new file mode 100644 index 0000000..3261ee0 --- /dev/null +++ b/lib/page/setting/mcp_info.dart @@ -0,0 +1,194 @@ +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:provider/provider.dart'; +import '../../provider/mcp_server_provider.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +// 定义工具的数据结构 +class Tool { + final String name; + final String desc; + + Tool({required this.name, required this.desc}); +} + +class McpInfo extends StatelessWidget { + final String serverName; + + const McpInfo({super.key, required this.serverName}); + + Future> _fetchTools(BuildContext context) async { + final client = ProviderManager.mcpServerProvider.clients[serverName]; + if (client == null) { + return []; + } + + final resp = await client.sendToolList(); + if (resp.error != null) { + return []; + } + final toolsData = resp.result['tools'] as List?; // Handle null case + if (toolsData == null) { + return []; + } + return toolsData.map((tool) => Tool(name: tool['name'] as String? ?? '', desc: tool['description'] as String? ?? '')).toList(); + } + + // Helper method to build an expandable card + Widget _buildExpandableCard({ + required BuildContext context, + required String title, + required IconData iconData, + required List childrenWidgets, + bool initiallyExpanded = false, + }) { + return Card( + margin: EdgeInsets.zero, + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + child: Theme( + data: Theme.of(context).copyWith(dividerColor: Colors.transparent), + child: ExpansionTile( + leading: Icon(iconData, color: Theme.of(context).colorScheme.primary), + title: Text( + title, + style: TextStyle(fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface), + ), + initiallyExpanded: initiallyExpanded, + childrenPadding: const EdgeInsets.only(bottom: 8, left: 8, right: 8), + children: childrenWidgets, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return Consumer( + builder: (context, provider, child) { + return FutureBuilder>( + future: _fetchTools(context), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CupertinoActivityIndicator()); + } + if (snapshot.hasError) { + return Center( + child: Padding(padding: const EdgeInsets.all(16.0), child: Text('${l10n.error}: ${snapshot.error}')), + ); + } + + final tools = snapshot.data ?? []; + + // Prepare children for the Tools card + List toolsChildren; + if (tools.isNotEmpty) { + toolsChildren = [ + ListView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: tools.length, + itemBuilder: (context, index) { + final tool = tools[index]; + return Card( + margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + elevation: 1, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: ListTile( + leading: Icon(CupertinoIcons.tag_fill, color: Theme.of(context).colorScheme.secondary), + title: Text( + tool.name, + style: TextStyle(fontWeight: FontWeight.w600, color: Theme.of(context).colorScheme.onSurface), + ), + subtitle: Text(tool.desc, style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant)), + ), + ); + }, + ), + ]; + } else { + toolsChildren = [ + ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0), + title: Text( + "No tools available for this server.", // TODO: Localize + textAlign: TextAlign.center, + style: TextStyle(color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), + ]; + } + + final sections = [ + { + 'title': "Tools", // TODO: Localize + 'icon': CupertinoIcons.wrench_fill, + 'children': toolsChildren, + 'initiallyExpanded': true, + }, + // { + // 'title': "Resource", // TODO: Localize + // 'icon': CupertinoIcons.archivebox_fill, + // 'children': [ + // ListTile( + // contentPadding: const EdgeInsets.symmetric( + // horizontal: 16.0, vertical: 16.0), + // title: Text( + // "No resource data available.", // TODO: Localize + // textAlign: TextAlign.center, + // style: TextStyle( + // color: + // Theme.of(context).colorScheme.onSurfaceVariant), + // ), + // ), + // ], + // 'initiallyExpanded': false, + // }, + // { + // 'title': "Prompt", // TODO: Localize + // 'icon': CupertinoIcons.lightbulb_fill, + // 'children': [ + // ListTile( + // contentPadding: const EdgeInsets.symmetric( + // horizontal: 16.0, vertical: 16.0), + // title: Text( + // "No prompt data available.", // TODO: Localize + // textAlign: TextAlign.center, + // style: TextStyle( + // color: + // Theme.of(context).colorScheme.onSurfaceVariant), + // ), + // ), + // ], + // 'initiallyExpanded': false, + // }, + ]; + + return ListView.separated( + padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0), + itemCount: sections.length, + itemBuilder: (context, index) { + final section = sections[index]; + return _buildExpandableCard( + context: context, + title: section['title'] as String, + iconData: section['icon'] as IconData, + childrenWidgets: section['children'] as List, + initiallyExpanded: section['initiallyExpanded'] as bool, + ); + }, + separatorBuilder: (context, index) => const SizedBox(height: 12), + ); + }, + ); + }, + ); + } +} diff --git a/lib/page/setting/mcp_server.dart b/lib/page/setting/mcp_server.dart new file mode 100644 index 0000000..19df9c9 --- /dev/null +++ b/lib/page/setting/mcp_server.dart @@ -0,0 +1,1065 @@ +import 'dart:async'; + +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:chatmcp/page/setting/mcp_info.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:provider/provider.dart'; +import '../../provider/mcp_server_provider.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/utils/process.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:chatmcp/utils/oauth_discovery.dart'; + +class McpServer extends StatefulWidget { + const McpServer({super.key}); + + @override + State createState() => _McpServerState(); +} + +class _McpServerState extends State { + final TextEditingController _searchController = TextEditingController(); + String _selectedTab = 'installed'; // 使用固定的英文标识符 + int _refreshCounter = 0; + final Map _serverLoading = {}; + + // OAuth auto-discovery state + OAuthDiscoveryResult? _oauthDiscovery; + bool _isCheckingOAuth = false; + + // 标签映射:内部标识符 -> 显示文本 + Map _getTabLabels(AppLocalizations l10n) { + return {'all': l10n.all, 'installed': l10n.installed, 'inmemory': 'inmemory'}; + } + + // 验证URL是否合法 + bool isValidUrl(String urlString) { + try { + final uri = Uri.parse(urlString); + return uri.scheme.isNotEmpty && uri.host.isNotEmpty; + } catch (e) { + return false; + } + } + + // Check OAuth requirement for URL + Future _checkOAuthRequirement(String url) async { + if (!kIsWeb || !isValidUrl(url)) return; + + setState(() { + _isCheckingOAuth = true; + }); + + try { + final provider = Provider.of(context, listen: false); + final result = await provider.discoverOAuthForServer(url); + + setState(() { + _oauthDiscovery = result; + _isCheckingOAuth = false; + }); + } catch (e) { + Logger.root.warning('OAuth discovery failed: $e'); + setState(() { + _oauthDiscovery = null; + _isCheckingOAuth = false; + }); + } + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return Scaffold( + body: SafeArea( + child: Consumer( + builder: (context, provider, child) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Column( + children: [ + const SizedBox(height: 20), + // 搜索框 + Card( + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: l10n.searchServer, + prefixIcon: Icon(CupertinoIcons.search, color: Theme.of(context).colorScheme.onSurface.withAlpha(153)), + border: InputBorder.none, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + onChanged: (value) => setState(() {}), + ), + ), + const SizedBox(height: 16), + + // 标签选择和操作按钮 + LayoutBuilder( + builder: (context, constraints) { + // 在宽屏设备上使用Row实现两边对齐 + if (constraints.maxWidth > 500) { + // 设定一个合理的宽度阈值 + return Row( + children: [ + Wrap( + spacing: 12, + children: [ + _buildFilterChip('all', l10n.all), + _buildFilterChip('installed', l10n.installed), + _buildFilterChip('inmemory', l10n.inmemory), + ], + ), + const Spacer(), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + _buildActionButton( + icon: CupertinoIcons.add, + tooltip: l10n.addProvider, + onPressed: () { + final provider = ProviderManager.mcpServerProvider; + _showEditDialog(context, '', provider, null); + }, + ), + const SizedBox(width: 8), + _buildActionButton(icon: CupertinoIcons.refresh, tooltip: l10n.refresh, onPressed: () => setState(() {})), + ], + ), + ], + ); + } else { + // 在窄屏设备上继续使用Wrap自动换行 + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Wrap( + spacing: 12, + children: [ + _buildFilterChip('all', l10n.all), + _buildFilterChip('installed', l10n.installed), + _buildFilterChip('inmemory', l10n.inmemory), + ], + ), + ], + ), + const SizedBox(height: 12), + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + _buildActionButton( + icon: CupertinoIcons.add, + tooltip: l10n.addProvider, + onPressed: () { + final provider = ProviderManager.mcpServerProvider; + _showEditDialog(context, '', provider, null); + }, + ), + const SizedBox(width: 8), + _buildActionButton(icon: CupertinoIcons.refresh, tooltip: l10n.refresh, onPressed: () => setState(() {})), + ], + ), + ], + ); + } + }, + ), + const SizedBox(height: 16), + + // 服务器列表 + Expanded( + child: FutureBuilder>( + future: (_selectedTab == 'all' + ? provider.loadMarketServers() + : _selectedTab == 'inmemory' + ? provider.loadInMemoryServers() + : provider.loadServers()), + key: ValueKey('server_list_$_refreshCounter'), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CupertinoActivityIndicator()); + } + + if (snapshot.hasError) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(CupertinoIcons.exclamationmark_circle, size: 48, color: Theme.of(context).colorScheme.error), + const SizedBox(height: 16), + Text('Failed to load: ${snapshot.error}', style: TextStyle(color: Theme.of(context).colorScheme.error)), + ], + ), + ); + } + + if (snapshot.hasData) { + final servers = snapshot.data?['mcpServers'] as Map? ?? {}; + + if (servers.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(CupertinoIcons.desktopcomputer, size: 64, color: Theme.of(context).colorScheme.onSurface.withAlpha(153)), + const SizedBox(height: 16), + Text( + l10n.noServerConfigs, + style: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(153), fontSize: 16), + ), + ], + ), + ); + } + + return ListView.builder( + itemCount: servers.length, + itemBuilder: (context, index) { + final serverName = servers.keys.elementAt(index); + final serverConfig = servers[serverName]; + + return _buildServerCard(context, serverName, serverConfig, provider, serverConfig['installed'] ?? false); + }, + ); + } + return const Center(child: CupertinoActivityIndicator()); + }, + ), + ), + ], + ), + ); + }, + ), + ), + ); + } + + bool isActive(String serverName) { + final provider = ProviderManager.mcpServerProvider.clients; + for (var client in provider.entries) { + if (client.key == serverName) { + return true; + } + } + return false; + } + + Widget _buildServerCard(BuildContext context, String serverName, dynamic serverConfig, McpServerProvider provider, bool installed) { + final l10n = AppLocalizations.of(context)!; + bool serverActive = isActive(serverName); + + return Card( + margin: const EdgeInsets.symmetric(vertical: 8), + elevation: 0, + color: Theme.of(context).colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Icon(serverActive ? CupertinoIcons.checkmark : CupertinoIcons.desktopcomputer, color: Theme.of(context).colorScheme.primary, size: 20), + const SizedBox(width: 12), + Expanded( + child: Row( + children: [ + Text( + serverName, + style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + if (serverConfig['type'] != null) ...[ + const Gap(size: 10), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primaryContainer.withAlpha(80), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Theme.of(context).colorScheme.primary.withAlpha(30), width: 1), + ), + child: Text( + (serverConfig['type'] ?? '').toString().toLowerCase(), + style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Theme.of(context).colorScheme.onSurface.withAlpha(180)), + ), + ), + ], + ], + ), + ), + if (installed) ...[ + // OAuth authentication button (web only) + if (kIsWeb) ...[ + FutureBuilder>( + future: provider.getServerOAuthStatus(serverName), + builder: (context, snapshot) { + final oauthStatus = snapshot.data ?? {}; + final oauthEnabled = oauthStatus['enabled'] == true; + final isAuthenticated = oauthStatus['authenticated'] == true; + final needsRefresh = oauthStatus['needs_refresh'] == true; + + if (!oauthEnabled) return const SizedBox.shrink(); + + return _buildActionButton( + icon: isAuthenticated + ? (needsRefresh ? CupertinoIcons.refresh : CupertinoIcons.checkmark_shield) + : CupertinoIcons.lock, + tooltip: isAuthenticated + ? (needsRefresh ? 'Refresh OAuth Token' : 'OAuth Authenticated') + : 'Authenticate with OAuth', + onPressed: () async { + setState(() { + _serverLoading[serverName] = true; + }); + try { + if (needsRefresh) { + await provider.refreshServerToken(serverName); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('OAuth token refreshed successfully')), + ); + } else if (!isAuthenticated) { + await provider.authenticateServer(serverName); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('OAuth authentication successful')), + ); + } + setState(() { + _refreshCounter++; + }); + } catch (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('OAuth error: ${e.toString()}')), + ); + } finally { + if (mounted) { + setState(() { + _serverLoading[serverName] = false; + }); + } + } + }, + isLoading: _serverLoading[serverName] == true, + ); + }, + ), + const Gap(size: 10), + ], + + _buildActionButton( + icon: provider.mcpServerIsRunning(serverName) ? CupertinoIcons.stop : CupertinoIcons.play, + tooltip: provider.mcpServerIsRunning(serverName) ? l10n.stop : l10n.start, + onPressed: () async { + if (provider.mcpServerIsRunning(serverName)) { + await provider.stopMcpServer(serverName); + } else { + setState(() { + _serverLoading[serverName] = true; + }); + try { + await provider.startMcpServer(serverName); + } finally { + if (mounted) { + setState(() { + _serverLoading[serverName] = false; + }); + } + } + } + }, + isLoading: _serverLoading[serverName] == true, + ), + const Gap(size: 10), + if (provider.mcpServerIsRunning(serverName)) + _buildActionButton(icon: CupertinoIcons.info_circle, tooltip: "info", onPressed: () => _showInfoDialog(context, serverName)), + const Gap(size: 10), + _buildActionButton( + icon: CupertinoIcons.pencil, + tooltip: l10n.edit, + onPressed: () => _showEditDialog(context, serverName, provider, null), + ), + const Gap(size: 10), + _buildActionButton( + icon: CupertinoIcons.delete, + tooltip: l10n.delete, + color: Theme.of(context).colorScheme.error, + onPressed: () => _showDeleteConfirmDialog(context, serverName, provider), + ), + ] else ...[ + ElevatedButton.icon( + icon: Icon(CupertinoIcons.cloud_download, color: Theme.of(context).colorScheme.onPrimary), + label: Text(l10n.install), + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.primary, + foregroundColor: Theme.of(context).colorScheme.onPrimary, + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + onPressed: () async { + final cmdExists = await isCommandAvailable(serverConfig['command']); + if (!cmdExists) { + showErrorDialog(context, l10n.commandNotExist(serverConfig['command'], getPlatformPath() ?? '')); + } else { + Logger.root.info('Install server configuration: $serverName ${serverConfig['command']} ${serverConfig['args']}'); + await _showEditDialog(context, serverName, provider, serverConfig); + } + }, + ), + ], + ], + ), + ), + ); + } + + void _showInfoDialog(BuildContext context, String serverName) { + if (kIsMobile) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => Scaffold( + body: SafeArea(child: McpInfo(serverName: serverName)), + ), + ), + ); + } else { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + child: ClipRRect( + borderRadius: BorderRadius.circular(8.0), + child: SizedBox( + width: MediaQuery.of(context).size.width * 0.8, + height: MediaQuery.of(context).size.height * 0.8, + child: McpInfo(serverName: serverName), + ), + ), + ), + ); + } + } + + Widget _buildActionButton({ + required IconData icon, + required String tooltip, + required VoidCallback onPressed, + Color? color, + bool isLoading = false, + }) { + return Tooltip( + message: tooltip, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: isLoading ? null : onPressed, + child: Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color ?? Theme.of(context).colorScheme.primary.withAlpha(51)), + ), + child: isLoading + ? SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2, color: color ?? Theme.of(context).colorScheme.primary), + ) + : Icon(icon, size: 18, color: color ?? Theme.of(context).colorScheme.primary), + ), + ), + ), + ); + } + + Widget _buildFilterChip(String tabKey, String displayLabel) { + final isSelected = _selectedTab == tabKey; + return FilterChip( + label: Text( + displayLabel, + style: TextStyle(color: Theme.of(context).colorScheme.onSurface, fontSize: 14, fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal), + ), + selected: isSelected, + onSelected: (selected) { + setState(() { + _selectedTab = tabKey; + }); + }, + backgroundColor: Theme.of(context).colorScheme.surface, + selectedColor: Theme.of(context).colorScheme.primary.withAlpha(31), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: isSelected ? Theme.of(context).colorScheme.primary : Theme.of(context).colorScheme.outline.withAlpha(26)), + ), + ); + } + + Future _showEditDialog(BuildContext context, String serverName, McpServerProvider provider, Map? newServerConfig) async { + if (!context.mounted) return; + + var config = await provider.loadServers(); + if (_selectedTab == 'inmemory') { + config = await provider.loadInMemoryServers(); + } + + var servers = config['mcpServers'] ?? {}; + + if (!context.mounted) return; + + final serverConfig = + newServerConfig ?? + servers[serverName] as Map? ?? + { + 'type': 'sse', // streamable, sse, stdio, inmemory + 'command': '', + 'args': [], + 'env': {}, + 'auto_approve': false, + }; + + String resultServerName = serverName; + String resultType = serverConfig['type']?.toString() ?? ''; + String resultCommand = serverConfig['command']?.toString() ?? ''; + String resultArgs = (serverConfig['args'] as List?)?.map((e) => e.toString()).join(' ') ?? ''; + String resultEnv = (serverConfig['env'] as Map?)?.entries.map((e) => '${e.key}=${e.value}').join('\n') ?? ''; + bool autoApprove = serverConfig['auto_approve'] as bool? ?? false; + + final formKey = GlobalKey(); + + final isEdit = serverName.isNotEmpty; + + try { + if (!context.mounted) { + return; + } + + final l10n = AppLocalizations.of(context)!; + final confirmed = await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext dialogContext) { + return AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text( + 'MCP Server - ${serverName.isEmpty ? l10n.addProvider : serverName}', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600), + ), + content: SingleChildScrollView( + child: FormBuilder( + key: formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (!isEdit) + FormBuilderTextField( + name: 'serverName', + initialValue: resultServerName, + decoration: InputDecoration( + labelText: l10n.serverName, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + prefixIcon: Icon(CupertinoIcons.command, color: Theme.of(context).colorScheme.primary, size: 20), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + validator: (value) { + if (value == null || value.isEmpty) { + return l10n.fieldRequired; + } + if (value.length > 50) { + return l10n.serverNameTooLong; + } + return null; + }, + ), + if (!isEdit) const SizedBox(height: 16), + FormBuilderDropdown( + name: 'type', + initialValue: resultType, + enabled: _selectedTab != 'inmemory', + decoration: InputDecoration( + labelText: l10n.serverType, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + prefixIcon: Icon(CupertinoIcons.gear, color: Theme.of(context).colorScheme.primary, size: 20), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + items: [ + DropdownMenuItem(value: 'sse', child: Text('SSE')), + DropdownMenuItem(value: 'stdio', child: Text('STDIO')), + DropdownMenuItem(value: 'streamable', child: Text('Streamable')), + if (isEdit) DropdownMenuItem(value: 'inmemory', enabled: false, child: Text('InMemory')), + ], + validator: (value) { + if (value == null || value.isEmpty) { + return l10n.fieldRequired; + } + return null; + }, + ), + const SizedBox(height: 16), + FormBuilderTextField( + name: 'command', + enabled: resultType != 'inmemory', + initialValue: resultCommand, + decoration: InputDecoration( + labelText: l10n.command, + hintText: l10n.commandExample, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + prefixIcon: Icon(CupertinoIcons.command, color: Theme.of(context).colorScheme.primary, size: 20), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + validator: (value) { + if (value == null || value.isEmpty) { + return l10n.fieldRequired; + } + return null; + }, + onChanged: (value) { + if (value != null && value.trim().isNotEmpty && value.startsWith('http')) { + _checkOAuthRequirement(value.trim()); + } + }, + ), + + // OAuth discovery status + if (_isCheckingOAuth) ...[ + const SizedBox(height: 8), + Row( + children: [ + const SizedBox(width: 40), // Align with field content + SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 8), + Text( + 'Checking authentication requirements...', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface.withAlpha(150), + fontSize: 13, + ), + ), + ], + ), + ] else if (_oauthDiscovery?.requiresOAuth == true) ...[ + const SizedBox(height: 8), + Container( + margin: const EdgeInsets.only(left: 40), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.primaryContainer.withAlpha(100), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: Theme.of(context).colorScheme.primary.withAlpha(100), + width: 1, + ), + ), + child: Row( + children: [ + Icon( + Icons.security, + size: 16, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'This server requires OAuth authentication. You\'ll be prompted to login after saving.', + style: TextStyle( + color: Theme.of(context).colorScheme.onPrimaryContainer, + fontSize: 13, + ), + ), + ), + ], + ), + ), + ], + const SizedBox(height: 16), + FormBuilderTextField( + name: 'args', + initialValue: resultArgs, + decoration: InputDecoration( + labelText: l10n.arguments, + hintText: l10n.argumentsExample, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + prefixIcon: Icon(CupertinoIcons.command, color: Theme.of(context).colorScheme.primary, size: 20), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 16), + FormBuilderTextField( + name: 'env', + initialValue: resultEnv, + maxLines: 4, + decoration: InputDecoration( + labelText: l10n.environmentVariables, + hintText: l10n.envVarsFormat, + hintStyle: TextStyle(color: Theme.of(context).colorScheme.onSurface.withAlpha(102)), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.outline.withAlpha(51)), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide(color: Theme.of(context).colorScheme.primary), + ), + prefixIcon: Icon(CupertinoIcons.command, color: Theme.of(context).colorScheme.primary, size: 20), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface), + ), + const SizedBox(height: 16), + FormBuilderCheckbox( + name: 'auto_approve', + initialValue: autoApprove, + title: Text(l10n.autoApprove, style: TextStyle(fontSize: 15, color: Theme.of(context).colorScheme.onSurface)), + decoration: const InputDecoration(border: InputBorder.none, contentPadding: EdgeInsets.zero), + ), + const SizedBox(height: 16), + + // OAuth Auto-Discovery Information + if (kIsWeb) ...[ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest.withAlpha(100), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: Theme.of(context).colorScheme.outline.withAlpha(100), + width: 1, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.info_outline, + size: 20, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: 8), + Text( + 'Authentication', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: Theme.of(context).colorScheme.primary, + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + 'Authentication is now handled automatically. When you enter a server URL that requires authentication, you\'ll be prompted to login after saving.', + style: TextStyle( + fontSize: 14, + color: Theme.of(context).colorScheme.onSurface.withAlpha(200), + ), + ), + ], + ), + ), + ], + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.pop(dialogContext, false); + }, + style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.primary), + child: Text(l10n.cancel), + ), + TextButton( + onPressed: () async { + if (!formKey.currentState!.saveAndValidate()) { + return; + } + + final values = formKey.currentState!.value; + final saveServerName = serverName.isEmpty ? (values['serverName'] as String).trim() : serverName; + final type = values['type'] as String; + final command = (values['command'] as String).trim(); + final argsString = (values['args'] as String).trim(); + + // 改进的参数解析逻辑,支持引号包围的参数 + List args = []; + if (argsString.isNotEmpty) { + // 匹配单引号、双引号包围的参数,或者不包含空格的参数 + RegExp regExp = RegExp(r'''"[^"]*"|'[^']*'|\S+'''); + Iterable matches = regExp.allMatches(argsString); + for (RegExpMatch match in matches) { + // 保留原始引号 + args.add(match.group(0)!); + } + } + + final envStr = values['env'] as String; + + bool isRemote = type == 'sse' || type == 'streamable'; + bool isUrl = isValidUrl(command.trim()); + + if (kIsMobile && kIsWeb) { + if (type == "stdio") { + showErrorDialog(dialogContext, 'Mobile only supports mcp sse and streamable servers'); + return; + } + if (isRemote && !isUrl) { + showErrorDialog(dialogContext, 'Server command must be a valid URL'); + return; + } + } + + final env = Map.fromEntries( + envStr.split('\n').where((line) => line.trim().isNotEmpty).map((line) { + final parts = line.split('='); + if (parts.length < 2) { + return MapEntry(parts[0].trim(), ''); + } + return MapEntry(parts[0].trim(), parts.sublist(1).join('=').trim()); + }), + ); + + if (config['mcpServers'] == null) { + config['mcpServers'] = {}; + } + + // Build server configuration + final serverConfigData = { + 'name': saveServerName, + 'type': type, + 'command': command, + 'args': args, + 'env': env, + 'auto_approve': values['auto_approve'] as bool? ?? false, + }; + + await provider.addMcpServer(serverConfigData); + + if (mounted) { + setState(() { + _refreshCounter++; + }); + } + + if (dialogContext.mounted) { + Navigator.pop(dialogContext, true); + } + + // Handle auto-discovered OAuth authentication BEFORE starting server + if (_oauthDiscovery?.requiresOAuth == true && kIsWeb) { + if (mounted) { + // Always try automatic OAuth first + final shouldAuth = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Authentication Required'), + content: Text( + 'This server requires OAuth authentication. Would you like to login now?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('Later'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('Login Now'), + ), + ], + ), + ); + + if (shouldAuth == true) { + try { + Logger.root.info('Starting OAuth authentication for $saveServerName'); + + final success = await provider.autoAuthenticateServer( + saveServerName, + _oauthDiscovery! + ); + + if (success && mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Authentication successful for $saveServerName'), + backgroundColor: Colors.green, + ), + ); + } else if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Authentication failed: No success response'), + backgroundColor: Colors.orange, + ), + ); + } + } catch (e) { + Logger.root.severe('OAuth authentication error: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Authentication failed: ${e.toString()}'), + backgroundColor: Colors.red, + duration: const Duration(seconds: 5), + ), + ); + } + } + } + } + } + + // if server is running, restart it (AFTER OAuth authentication) + if (provider.mcpServerIsRunning(saveServerName)) { + await provider.stopMcpServer(saveServerName); + setState(() { + _serverLoading[serverName] = true; + }); + await provider.startMcpServer(saveServerName); + setState(() { + _serverLoading[serverName] = false; + }); + } + }, + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + backgroundColor: Theme.of(context).colorScheme.primary.withAlpha(31), + ), + child: Text(l10n.save, style: const TextStyle(fontWeight: FontWeight.w600)), + ), + ], + backgroundColor: Theme.of(context).colorScheme.surface, + ); + }, + ); + + if (confirmed == true && context.mounted) { + setState(() { + _refreshCounter++; + }); + } + } finally { + // No controllers to dispose as FormBuilder handles that internally + } + } + + Future _showDeleteConfirmDialog(BuildContext context, String serverName, McpServerProvider provider) async { + final l10n = AppLocalizations.of(context)!; + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text(l10n.confirmDelete), + content: Text(l10n.confirmDeleteServer(serverName)), + actions: [ + TextButton(onPressed: () => Navigator.pop(context, false), child: Text(l10n.cancel)), + TextButton(onPressed: () => Navigator.pop(context, true), child: Text(l10n.delete)), + ], + ), + ); + + if (confirmed == true && context.mounted) { + await provider.removeMcpServer(serverName); + setState(() { + _refreshCounter++; + }); + } + } + + Future showErrorDialog(BuildContext context, String message) async { + final l10n = AppLocalizations.of(context)!; + return showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + title: Text(l10n.error), + content: Text(message), + actions: [TextButton(onPressed: () => Navigator.pop(context), child: Text(l10n.ok))], + ), + ); + } +} diff --git a/lib/page/setting/network_sync_setting.dart b/lib/page/setting/network_sync_setting.dart new file mode 100644 index 0000000..4500332 --- /dev/null +++ b/lib/page/setting/network_sync_setting.dart @@ -0,0 +1,862 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:qr_flutter/qr_flutter.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; +import 'package:chatmcp/services/network_sync_service.dart'; +import 'package:chatmcp/utils/toast.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/utils/platform.dart'; + +class NetworkSyncSetting extends StatefulWidget { + const NetworkSyncSetting({super.key}); + + @override + State createState() => _NetworkSyncSettingState(); +} + +class _NetworkSyncSettingState extends State { + final NetworkSyncService _syncService = NetworkSyncService(); + final TextEditingController _serverUrlController = TextEditingController(); + + bool _isServerRunning = false; + String? _serverAddress; + int _serverPort = 8080; + + // 同步状态 + bool _isSyncing = false; + String _syncStatus = ''; + bool _syncSuccess = false; + String? _syncError; + + // 连接历史 + List _connectionHistory = []; + + @override + void initState() { + super.initState(); + _isServerRunning = _syncService.isServerRunning; + _serverAddress = _syncService.serverAddress; + _serverPort = _syncService.serverPort; + + // 加载连接历史 + _loadConnectionHistory(); + + // 监听服务器状态变化 + _syncService.onServerStateChanged = (isRunning, address, port) { + if (mounted) { + setState(() { + _isServerRunning = isRunning; + _serverAddress = address; + _serverPort = port; + }); + } + }; + + // 监听同步状态变化 + _syncService.onSyncStateChanged = (status, {bool? isLoading, bool? isSuccess, String? error}) { + if (mounted) { + final l10n = AppLocalizations.of(context)!; + final localizedStatus = _getLocalizedStatus(status, l10n); + + setState(() { + _syncStatus = localizedStatus; + _isSyncing = isLoading ?? false; + _syncSuccess = isSuccess ?? false; + _syncError = error; + }); + + // 显示Toast消息 + if (isSuccess == true) { + ToastUtils.success(localizedStatus); + } else if (error != null) { + ToastUtils.error(localizedStatus); + } + } + }; + } + + @override + void dispose() { + _serverUrlController.dispose(); + super.dispose(); + } + + /// 加载连接历史 + Future _loadConnectionHistory() async { + final histories = await SyncHistoryManager.getHistories(); + if (mounted) { + setState(() { + _connectionHistory = histories; + }); + } + } + + /// 保存连接历史 + Future _saveConnectionHistory(String url, Map? serverInfo) async { + final l10n = AppLocalizations.of(context)!; + final history = SyncServerHistory( + url: url, + deviceName: serverInfo?['deviceName'] ?? l10n.unknownDevice, + platform: serverInfo?['platform'] ?? l10n.unknownPlatform, + lastConnected: DateTime.now(), + displayName: serverInfo?['displayName'] ?? url, + ); + + await SyncHistoryManager.saveHistory(history); + await _loadConnectionHistory(); + } + + /// 获取本地化状态消息 + String _getLocalizedStatus(String status, AppLocalizations l10n) { + switch (status) { + case 'connectingToServer': + return l10n.connectingToServer; + case 'downloadingData': + return l10n.downloadingData; + case 'importingData': + return l10n.importingData; + case 'reinitializingData': + return l10n.reinitializingData; + case 'dataSyncSuccess': + return l10n.dataSyncSuccess; + case 'preparingData': + return l10n.preparingData; + case 'uploadingData': + return l10n.uploadingData; + case 'dataPushSuccess': + return l10n.dataPushSuccess; + default: + // 处理错误消息 + if (status.startsWith('syncFailed:')) { + return '${l10n.syncFailed}: ${status.substring(11)}'; + } else if (status.startsWith('pushFailed:')) { + return '${l10n.pushFailed}: ${status.substring(11)}'; + } + return status; // 如果没有匹配的,返回原始状态 + } + } + + /// 格式化时间显示 + String _formatTime(DateTime dateTime) { + final l10n = AppLocalizations.of(context)!; + final now = DateTime.now(); + final difference = now.difference(dateTime); + + if (difference.inMinutes < 1) { + return l10n.justNow; + } else if (difference.inHours < 1) { + return l10n.minutesAgo(difference.inMinutes); + } else if (difference.inDays < 1) { + return l10n.hoursAgo(difference.inHours); + } else if (difference.inDays < 7) { + return l10n.daysAgo(difference.inDays); + } else { + return '${dateTime.month}/${dateTime.day}'; + } + } + + /// 连接到历史记录中的服务器 + Future _connectToHistory(SyncServerHistory history) async { + final l10n = AppLocalizations.of(context)!; + _serverUrlController.text = history.url; + ToastUtils.success(l10n.serverSelected(history.displayName)); + } + + /// 删除连接历史 + Future _removeHistory(String url) async { + final l10n = AppLocalizations.of(context)!; + await SyncHistoryManager.removeHistory(url); + await _loadConnectionHistory(); + ToastUtils.success(l10n.connectionRecordDeleted); + } + + /// 显示所有连接历史 + void _showAllHistory() { + final l10n = AppLocalizations.of(context)!; + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.connectionHistory.replaceAll(':', '')), + content: SizedBox( + width: double.maxFinite, + height: 400, + child: ListView.builder( + itemCount: _connectionHistory.length, + itemBuilder: (context, index) { + final history = _connectionHistory[index]; + return ListTile( + leading: Icon( + history.platform.toLowerCase().contains('windows') + ? Icons.computer + : history.platform.toLowerCase().contains('android') + ? Icons.phone_android + : history.platform.toLowerCase().contains('ios') + ? Icons.phone_iphone + : Icons.devices, + color: Colors.blue, + ), + title: Text(history.displayName), + subtitle: Text('${history.url}\n${_formatTime(history.lastConnected)}'), + isThreeLine: true, + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.connect_without_contact), + onPressed: () { + Navigator.pop(context); + _connectToHistory(history); + }, + ), + IconButton( + icon: const Icon(Icons.delete), + onPressed: () async { + await _removeHistory(history.url); + Navigator.pop(context); + _showAllHistory(); + }, + ), + ], + ), + ); + }, + ), + ), + actions: [ + TextButton( + onPressed: () async { + await SyncHistoryManager.clearHistory(); + await _loadConnectionHistory(); + Navigator.pop(context); + ToastUtils.success(l10n.clearAllConnectionHistory); + }, + child: Text(l10n.clearAllHistory), + ), + TextButton(onPressed: () => Navigator.pop(context), child: Text(l10n.close)), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return Scaffold( + body: SafeArea( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + // 服务器状态卡片 + _buildServerStatusCard(l10n), + + const SizedBox(height: 16), + + // 连接远程服务器 + _buildConnectCard(l10n), + + const SizedBox(height: 16), + + // 使用说明 + _buildInstructionsCard(l10n), + ], + ), + ), + ); + } + + Widget _buildServerStatusCard(AppLocalizations l10n) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + _isServerRunning ? Icons.radio_button_checked : Icons.radio_button_unchecked, + color: _isServerRunning ? AppColors.green : AppColors.getInactiveTextColor(context), + ), + const SizedBox(width: 8), + Text( + _isServerRunning ? l10n.syncServerRunning : l10n.syncServerStopped, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + ], + ), + + if (_isServerRunning && _serverAddress != null) ...[ + const SizedBox(height: 16), + Text('📱 ${l10n.scanQRToConnect}', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)), + const SizedBox(height: 12), + + // 服务器地址和二维码 + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppColors.getThemeBackgroundColor(context), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppColors.getCodePreviewBorderColor(context)), + ), + child: Column( + children: [ + // 服务器地址 + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: Theme.of(context).cardColor, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: AppColors.getCodePreviewBorderColor(context)), + ), + child: Row( + children: [ + Expanded( + child: Text('http://$_serverAddress:$_serverPort', style: const TextStyle(fontFamily: 'monospace', fontSize: 14)), + ), + IconButton( + icon: const Icon(Icons.copy, size: 20), + onPressed: () { + Clipboard.setData(ClipboardData(text: 'http://$_serverAddress:$_serverPort')); + ToastUtils.success(l10n.addressCopied); + }, + ), + ], + ), + ), + + const SizedBox(height: 16), + + // 二维码 + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppColors.white, // 二维码背景始终为白色以确保可读性 + borderRadius: BorderRadius.circular(12), + border: Theme.of(context).brightness == Brightness.dark + ? Border.all(color: AppColors.getCodePreviewBorderColor(context), width: 1) + : null, + ), + child: QrImageView( + data: 'http://$_serverAddress:$_serverPort', + version: QrVersions.auto, + size: 200, + backgroundColor: AppColors.white, + foregroundColor: AppColors.black, // 确保二维码为黑色 + ), + ), + + const SizedBox(height: 12), + Text( + '🔄 ${l10n.otherDevicesCanScan}', + style: TextStyle(fontSize: 12, color: AppColors.getInactiveTextColor(context), fontStyle: FontStyle.italic), + textAlign: TextAlign.center, + ), + ], + ), + ), + ], + + const SizedBox(height: 16), + + // 服务器控制按钮 + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: _isServerRunning ? _stopServer : _startServer, + icon: Icon(_isServerRunning ? Icons.stop : Icons.play_arrow), + label: Text(_isServerRunning ? l10n.stopServer : l10n.startServer), + style: ElevatedButton.styleFrom( + backgroundColor: _isServerRunning ? AppColors.red : AppColors.green, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric(vertical: 12), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildConnectCard(AppLocalizations l10n) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('📲 ${l10n.connectToOtherDevices}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 12), + + // 扫码按钮 - 仅在移动平台显示 + if (kIsMobile) ...[ + SizedBox( + width: double.infinity, + child: ElevatedButton.icon( + onPressed: _openQRScanner, + icon: const Icon(Icons.qr_code_scanner), + label: Text(l10n.scanQRCode), + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.blue, + foregroundColor: AppColors.white, + padding: const EdgeInsets.symmetric(vertical: 12), + ), + ), + ), + const SizedBox(height: 16), + ], + + // 连接历史 + if (_connectionHistory.isNotEmpty) ...[ + const Divider(), + const SizedBox(height: 8), + Text('📋 ${l10n.connectionHistory}', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + ...(_connectionHistory + .take(3) + .map( + (history) => Container( + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + dense: true, + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: AppColors.getCodePreviewBorderColor(context)), + ), + leading: Icon( + history.platform.toLowerCase().contains('windows') + ? Icons.computer + : history.platform.toLowerCase().contains('android') + ? Icons.phone_android + : history.platform.toLowerCase().contains('ios') + ? Icons.phone_iphone + : Icons.devices, + size: 20, + color: AppColors.blue, + ), + title: Text(history.displayName, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), + subtitle: Text( + '${history.url} • ${_formatTime(history.lastConnected)}', + style: TextStyle(fontSize: 11, color: AppColors.getInactiveTextColor(context)), + ), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.connect_without_contact, size: 16), + onPressed: () => _connectToHistory(history), + tooltip: l10n.connect, + ), + IconButton(icon: const Icon(Icons.delete, size: 16), onPressed: () => _removeHistory(history.url), tooltip: l10n.delete), + ], + ), + ), + ), + )), + if (_connectionHistory.length > 3) + TextButton(onPressed: _showAllHistory, child: Text(l10n.viewAllConnections(_connectionHistory.length))), + const SizedBox(height: 8), + ], + + if (_connectionHistory.isNotEmpty) const Divider(), + const SizedBox(height: 8), + + Text(l10n.manualInputAddress, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)), + const SizedBox(height: 8), + + TextField( + controller: _serverUrlController, + decoration: InputDecoration( + labelText: l10n.serverAddress, + hintText: 'http://192.168.1.100:8080', + border: const OutlineInputBorder(), + prefixIcon: const Icon(Icons.link), + ), + ), + + const SizedBox(height: 12), + + // 同步状态显示 + if (_isSyncing || _syncStatus.isNotEmpty) ...[ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: _syncSuccess + ? AppColors.getThemeColor(context, lightColor: AppColors.green[50], darkColor: AppColors.green[900]) + : _syncError != null + ? AppColors.getThemeColor(context, lightColor: AppColors.red[50], darkColor: AppColors.red[900]) + : AppColors.getThemeColor(context, lightColor: AppColors.blue[50], darkColor: AppColors.blue[900]), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: _syncSuccess + ? AppColors.getThemeColor(context, lightColor: AppColors.green[200], darkColor: AppColors.green[700]) + : _syncError != null + ? AppColors.getThemeColor(context, lightColor: AppColors.red[200], darkColor: AppColors.red[700]) + : AppColors.getThemeColor(context, lightColor: AppColors.blue[200], darkColor: AppColors.blue[700]), + ), + ), + child: Row( + children: [ + if (_isSyncing) + const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)) + else + Icon( + _syncSuccess + ? Icons.check_circle + : _syncError != null + ? Icons.error + : Icons.info, + color: _syncSuccess + ? AppColors.green + : _syncError != null + ? AppColors.red + : AppColors.blue, + size: 16, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + _syncStatus, + style: TextStyle( + fontSize: 14, + color: _syncSuccess + ? AppColors.getThemeColor(context, lightColor: AppColors.green[800], darkColor: AppColors.green[200]) + : _syncError != null + ? AppColors.getThemeColor(context, lightColor: AppColors.red[800], darkColor: AppColors.red[200]) + : AppColors.getThemeColor(context, lightColor: AppColors.blue[800], darkColor: AppColors.blue[200]), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 12), + ], + + Row( + children: [ + Expanded( + child: ElevatedButton.icon( + onPressed: _isSyncing ? null : _syncFromRemote, + icon: const Icon(Icons.download), + label: Text(l10n.syncFromServer), + ), + ), + const SizedBox(width: 8), + Expanded( + child: ElevatedButton.icon( + onPressed: _isSyncing ? null : _pushToRemote, + icon: const Icon(Icons.upload), + label: Text(l10n.pushToServer), + ), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildInstructionsCard(AppLocalizations l10n) { + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('📖 ${l10n.usageInstructions}', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 12), + Text( + '🖥️ ${l10n.desktopAsServer}\n' + '${l10n.desktopStep1}\n' + '${l10n.desktopStep2}\n' + '${l10n.desktopStep3}\n\n' + '📱 ${l10n.mobileConnect}\n' + '${l10n.mobileStep1}\n' + '${l10n.mobileStep2}\n' + '${l10n.mobileStep3}\n\n' + '🔄 ${l10n.dataSync}\n' + '${l10n.uploadDescription}\n' + '${l10n.downloadDescription}\n' + '${l10n.syncContent}', + style: const TextStyle(fontSize: 14, height: 1.5), + ), + ], + ), + ), + ); + } + + Future _startServer() async { + final l10n = AppLocalizations.of(context)!; + try { + await _syncService.startServer(); + ToastUtils.success(l10n.syncServerStarted); + } catch (e) { + ToastUtils.error('${l10n.syncServerStartFailed}: $e'); + } + } + + Future _stopServer() async { + final l10n = AppLocalizations.of(context)!; + try { + await _syncService.stopServer(); + ToastUtils.success(l10n.syncServerStopped); + } catch (e) { + ToastUtils.error('${l10n.syncServerStopFailed}: $e'); + } + } + + Future _openQRScanner() async { + try { + final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => const QRScannerPage())); + + if (result != null && result is String && mounted) { + _serverUrlController.text = result; + + // 尝试获取服务器信息并显示设备名称 + final l10n = AppLocalizations.of(context)!; + try { + final serverInfo = await _syncService.getServerInfo(result); + if (serverInfo != null) { + ToastUtils.success(l10n.scanSuccessConnectTo(serverInfo['displayName'])); + } else { + ToastUtils.success(l10n.scanSuccessAddressFilled); + } + } catch (e) { + ToastUtils.success(l10n.scanSuccessAddressFilled); + } + } + } catch (e) { + final l10n = AppLocalizations.of(context)!; + ToastUtils.error('${l10n.scannerOpenFailed}: $e'); + } + } + + Future _syncFromRemote() async { + final l10n = AppLocalizations.of(context)!; + final url = _serverUrlController.text.trim(); + if (url.isEmpty) { + ToastUtils.warn(l10n.pleaseInputServerAddress); + return; + } + + try { + // Get server info + final serverInfo = await _syncService.getServerInfo(url); + + // Sync from remote + await _syncService.syncFromRemote(url); + + // Save connection history + await _saveConnectionHistory(url, serverInfo); + + // Success message displayed by status callback + } catch (e) { + // Error message displayed by status callback + } + } + + Future _pushToRemote() async { + final l10n = AppLocalizations.of(context)!; + final url = _serverUrlController.text.trim(); + if (url.isEmpty) { + ToastUtils.warn(l10n.pleaseInputServerAddress); + return; + } + + try { + // 先获取服务器信息 + final serverInfo = await _syncService.getServerInfo(url); + + // 执行推送 + await _syncService.pushToRemote(url); + + // 保存连接历史 + await _saveConnectionHistory(url, serverInfo); + + // 成功消息通过状态回调显示 + } catch (e) { + // 错误消息通过状态回调显示 + } + } +} + +// 二维码扫描页面 +class QRScannerPage extends StatefulWidget { + const QRScannerPage({super.key}); + + @override + State createState() => _QRScannerPageState(); +} + +class _QRScannerPageState extends State { + final MobileScannerController controller = MobileScannerController(); + bool _isFlashOn = false; + bool _hasScanned = false; // 防止重复扫描 + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + + return Scaffold( + backgroundColor: AppColors.getThemeBackgroundColor(context), + appBar: AppBar( + title: Text(l10n.scanQRCodeTitle), + backgroundColor: AppColors.getToolbarBackgroundColor(context), + foregroundColor: AppColors.getThemeTextColor(context), + elevation: 0, + actions: [ + IconButton( + icon: Icon(_isFlashOn ? Icons.flash_off : Icons.flash_on, color: AppColors.getThemeTextColor(context)), + onPressed: _toggleFlash, + ), + ], + ), + body: Container( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [AppColors.getToolbarBackgroundColor(context), AppColors.getThemeBackgroundColor(context)], + ), + ), + child: Column( + children: [ + // 扫描区域 + Expanded( + flex: 3, + child: Container( + margin: const EdgeInsets.all(20), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20), + boxShadow: [BoxShadow(color: AppColors.black.withAlpha(30), blurRadius: 10, offset: const Offset(0, 5))], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(20), + child: MobileScanner( + controller: controller, + onDetect: _onDetect, + overlayBuilder: (context, constraints) => Container( + decoration: BoxDecoration( + border: Border.all(color: AppColors.blue, width: 6), + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ), + ), + ), + + // 提示信息区域 + Expanded( + flex: 2, + child: Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // 扫描提示 + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppColors.getMessageBubbleBackgroundColor(context, false), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: AppColors.getCodePreviewBorderColor(context), width: 1), + ), + child: Column( + children: [ + Icon(Icons.qr_code_scanner, size: 32, color: AppColors.blue), + const SizedBox(height: 12), + Text( + l10n.aimQRCode, + style: TextStyle(color: AppColors.getThemeTextColor(context), fontSize: 16, fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + Text( + l10n.scanSyncQRCode, + style: TextStyle(color: AppColors.getInactiveTextColor(context), fontSize: 14), + textAlign: TextAlign.center, + ), + ], + ), + ), + + const SizedBox(height: 20), + + // 闪光灯控制按钮 + Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(25), + color: AppColors.getThemeColor(context, lightColor: AppColors.grey[100], darkColor: AppColors.grey[800]), + ), + child: IconButton( + onPressed: _toggleFlash, + icon: Icon(_isFlashOn ? Icons.flash_off : Icons.flash_on, size: 28), + color: _isFlashOn ? Colors.yellow[600] : AppColors.getInactiveTextColor(context), + tooltip: _isFlashOn ? l10n.flashOff : l10n.flashOn, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } + + void _onDetect(BarcodeCapture capture) { + final List barcodes = capture.barcodes; + + for (final barcode in barcodes) { + if (barcode.rawValue != null && !_hasScanned && mounted) { + final code = barcode.rawValue!; + + // 标记已扫描,防止重复 + _hasScanned = true; + + // 立即停止扫描 + controller.stop(); + + // 验证是否是有效的URL + if (code.startsWith('http://') || code.startsWith('https://')) { + // 扫描成功,立即退出并返回结果 + Navigator.of(context).pop(code); + } else { + // 无效URL,显示错误并重置扫描状态 + ToastUtils.warn('Invalid URL'); + Future.delayed(const Duration(seconds: 2), () { + if (mounted) { + setState(() { + _hasScanned = false; + }); + controller.start(); + } + }); + } + break; + } + } + } + + Future _toggleFlash() async { + await controller.toggleTorch(); + setState(() { + _isFlashOn = !_isFlashOn; + }); + } +} diff --git a/lib/page/setting/setting.dart b/lib/page/setting/setting.dart new file mode 100644 index 0000000..cb9353c --- /dev/null +++ b/lib/page/setting/setting.dart @@ -0,0 +1,60 @@ +import 'package:chatmcp/utils/platform.dart'; +import 'package:flutter/material.dart'; +import 'llm_setting.dart'; +import 'mcp_server.dart'; +import 'general_setting.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter/cupertino.dart'; +import 'network_sync_setting.dart'; + +class SettingPage extends StatefulWidget { + const SettingPage({super.key}); + + @override + State createState() => _SettingPageState(); +} + +class _SettingPageState extends State { + List _getTabs(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return [ + SettingTab(title: l10n.general, icon: CupertinoIcons.settings, content: GeneralSettings()), + SettingTab(title: l10n.providers, icon: CupertinoIcons.cube, content: KeysSettings()), + SettingTab(title: l10n.mcpServer, icon: CupertinoIcons.hammer, content: McpServer()), + if (!kIsBrowser) SettingTab(title: l10n.dataSync, icon: CupertinoIcons.cloud_download, content: NetworkSyncSetting()), + ]; + } + + @override + Widget build(BuildContext context) { + final tabs = _getTabs(context); + + return DefaultTabController( + length: tabs.length, + child: Scaffold( + appBar: AppBar( + toolbarHeight: 0, + bottom: TabBar( + indicatorSize: TabBarIndicatorSize.tab, + indicatorWeight: 5, + labelStyle: TextStyle(fontSize: kIsMobile ? 10 : 14), + tabs: tabs.map((tab) => Tab(icon: Icon(tab.icon), text: tab.title)).toList(), + onTap: (index) { + setState(() {}); + }, + ), + ), + body: TabBarView(children: tabs.map((tab) => tab.content).toList()), + ), + ); + } +} + +// 选项卡数据模型 +class SettingTab { + final String title; + final IconData icon; + final Widget content; + + SettingTab({required this.title, required this.icon, required this.content}); +} diff --git a/lib/page/setting/setting_switch.dart b/lib/page/setting/setting_switch.dart new file mode 100644 index 0000000..56ab0c9 --- /dev/null +++ b/lib/page/setting/setting_switch.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_switch/flutter_switch.dart'; + +class SettingSwitch extends StatelessWidget { + final String title; + final String subtitle; + final bool value; + final ValueChanged onChanged; + final double titleFontSize; + final double subtitleFontSize; + final int subtitleAlpha; + + const SettingSwitch({ + required this.title, + required this.subtitle, + required this.value, + required this.onChanged, + this.titleFontSize = 16, + this.subtitleFontSize = 13, + this.subtitleAlpha = 60, + super.key, + }); + + @override + Widget build(BuildContext context) { + return ListTile( + contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), + title: Text( + title, + style: TextStyle(fontSize: titleFontSize, color: Theme.of(context).colorScheme.onSurface), + ), + subtitle: Text( + subtitle, + style: TextStyle(fontSize: subtitleFontSize, color: Theme.of(context).colorScheme.onSurface.withAlpha(subtitleAlpha)), + ), + trailing: SizedBox( + width: 35.0, + child: FlutterSwitch( + value: value, + onToggle: onChanged, + width: 32.0, + height: 18.0, + toggleSize: 14.0, + borderRadius: 10.0, + padding: 1.5, + activeColor: Theme.of(context).colorScheme.primary, + inactiveColor: Theme.of(context).colorScheme.outline.withAlpha(76), + toggleColor: Colors.white, + ), + ), + onTap: () => onChanged(!value), + ); + } +} diff --git a/lib/page/setting/tools_setting.dart b/lib/page/setting/tools_setting.dart new file mode 100644 index 0000000..2d783b2 --- /dev/null +++ b/lib/page/setting/tools_setting.dart @@ -0,0 +1,24 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/widgets/tabs.dart'; + +class ToolsSettings extends StatefulWidget { + const ToolsSettings({super.key}); + + @override + State createState() => _ToolsSettingsState(); +} + +class _ToolsSettingsState extends State { + @override + Widget build(BuildContext context) { + return Tabs( + selectedIndex: 0, + onTap: (index) {}, + tabs: [ + MyTab(text: 'Tavily Search1', child: Text('Tavily Search1')), + MyTab(text: 'Tavily Search2', child: Text('Tavily Search2')), + MyTab(text: 'Tavily Search3', child: Text('Tavily Search3')), + ], + ); + } +} diff --git a/lib/provider/chat_model_provider.dart b/lib/provider/chat_model_provider.dart new file mode 100644 index 0000000..531a885 --- /dev/null +++ b/lib/provider/chat_model_provider.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/llm/model.dart' as llm_model; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:convert'; + +class ChatModelProvider extends ChangeNotifier { + static final ChatModelProvider _instance = ChatModelProvider._internal(); + factory ChatModelProvider() => _instance; + ChatModelProvider._internal() { + _loadSavedModel(); + } + + // Get the currently selected model + static const String _modelKey = 'current_model'; + llm_model.Model _currentModel = llm_model.Model( + name: "gpt-4o-mini", + label: "GPT-4o-mini", + providerId: "openai", + icon: "openai", + providerName: "OpenAI", + apiStyle: "openai", + ); + + llm_model.Model get currentModel => _currentModel; + + set currentModel(llm_model.Model model) { + _currentModel = model; + _saveSavedModel(); + notifyListeners(); + } + + Future _loadSavedModel() async { + final prefs = await SharedPreferences.getInstance(); + final modelName = prefs.getString(_modelKey) ?? ""; + if (modelName.isNotEmpty) { + _currentModel = llm_model.Model.fromJson(jsonDecode(modelName)); + } + notifyListeners(); + } + + Future _saveSavedModel() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_modelKey, _currentModel.toString()); + } +} diff --git a/lib/provider/chat_provider.dart b/lib/provider/chat_provider.dart new file mode 100644 index 0000000..89543b0 --- /dev/null +++ b/lib/provider/chat_provider.dart @@ -0,0 +1,237 @@ +import 'package:chatmcp/utils/event_bus.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/dao/chat.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/llm/model.dart' as llm_model; +import 'package:chatmcp/repository/chat_repository_provider.dart'; +import 'package:chatmcp/config/pagination_config.dart'; + +class ChatProvider extends ChangeNotifier { + static final ChatProvider _instance = ChatProvider._internal(); + factory ChatProvider() => _instance; + ChatProvider._internal(); + + Chat? _activeChat; + List _chats = []; + bool isSelectMode = false; + Set selectedChats = {}; + + // Pagination state + int _currentPage = 1; // 从 1 开始更符合常规分页概念 + bool _hasMoreChats = true; + bool _isLoadingChats = false; + String? _currentSearchKeyword; + + Chat? get activeChat => _activeChat; + List get chats => _chats; + bool get hasMoreChats => _hasMoreChats; + bool get isLoadingChats => _isLoadingChats; + + bool _showCodePreview = false; + bool get showCodePreview => _showCodePreview; + + void setShowCodePreview(String hash, bool show) { + if (show) { + _showCodePreview = true; + _artifactEvent = _previewEvents[hash]; + } else { + _showCodePreview = false; + _artifactEvent = null; + } + notifyListeners(); + } + + CodePreviewEvent? _artifactEvent; + CodePreviewEvent? get artifactEvent => _artifactEvent; + final Map _previewEvents = {}; + Map get previewEvents => _previewEvents; + + void setPreviewEvent(CodePreviewEvent event) { + _previewEvents[event.hash] = event; + if (_artifactEvent != null && _artifactEvent!.hash == event.hash) { + _artifactEvent = event; + } + notifyListeners(); + } + + void clearPreviewEvent(String hash) { + _previewEvents.remove(hash); + notifyListeners(); + } + + void clearArtifactEvent() { + _artifactEvent = null; + _showCodePreview = false; + notifyListeners(); + } + + Future loadChats({String? searchKeyword, bool refresh = false}) async { + if (_isLoadingChats) return; + + if (refresh || searchKeyword != _currentSearchKeyword) { + // Reset pagination state for new search or refresh + _currentPage = 1; // 重置为第一页 + _hasMoreChats = true; + _chats.clear(); + _currentSearchKeyword = searchKeyword; + } + + if (!_hasMoreChats) return; + + _isLoadingChats = true; + notifyListeners(); + + try { + Logger.root.info('loadChats: currentPage: $_currentPage, pageSize: ${PaginationConfig.defaultPageSize}'); + final result = await ChatRepositoryProvider.instance.getChats( + page: _currentPage, + pageSize: PaginationConfig.defaultPageSize, + searchKeyword: searchKeyword, + ); + + if (_currentPage == 1) { + // 第一页,替换现有数据 + _chats = result.chats; + } else { + // 后续页面,追加数据 + _chats.addAll(result.chats); + } + + _hasMoreChats = result.hasMore; + _currentPage++; + } catch (e) { + Logger.root.severe('Failed to load chats: $e'); + } finally { + _isLoadingChats = false; + notifyListeners(); + } + } + + Future loadMoreChats() async { + if (!_hasMoreChats || _isLoadingChats) return; + await loadChats(searchKeyword: _currentSearchKeyword); + } + + Future searchChats(String keyword) async { + await loadChats(searchKeyword: keyword.isEmpty ? null : keyword, refresh: true); + } + + Future refreshChats() async { + await loadChats(searchKeyword: _currentSearchKeyword, refresh: true); + } + + Future setActiveChat(Chat chat) async { + _activeChat = chat; + notifyListeners(); + } + + Future updateChatTitle(String title) async { + if (_activeChat == null) { + return; + } + final updatedChat = Chat(id: _activeChat!.id, title: title, createdAt: _activeChat!.createdAt, updatedAt: DateTime.now()); + await ChatRepositoryProvider.instance.updateChat(updatedChat); + await loadChats(); + if (_activeChat?.id == _activeChat!.id) { + setActiveChat(updatedChat); + } + } + + Future createChat(Chat chat, List messages) async { + final newChat = await ChatRepositoryProvider.instance.createChat(chat, messages); + await refreshChats(); // Refresh to get updated list + setActiveChat(newChat); + } + + Future updateChat(Chat chat) async { + Logger.root.info('updateChat: ${chat.toJson()}'); + await ChatRepositoryProvider.instance.updateChat(chat); + await refreshChats(); + if (_activeChat?.id == chat.id) { + setActiveChat(chat); + } + } + + Future deleteChat(int chatId) async { + await ChatRepositoryProvider.instance.deleteChat(chatId); + await refreshChats(); + if (_activeChat?.id == chatId) { + _activeChat = null; + } + notifyListeners(); + } + + Future clearActiveChat() async { + _activeChat = null; + notifyListeners(); + } + + Future addChatMessage(int chatId, List messages) async { + await ChatRepositoryProvider.instance.addChatMessage(chatId, messages); + notifyListeners(); + } + + void enterSelectMode() { + isSelectMode = true; + selectedChats.clear(); + notifyListeners(); + } + + void exitSelectMode() { + isSelectMode = false; + selectedChats.clear(); + notifyListeners(); + } + + void selectChat(int? chatId) { + selectedChats.add(chatId); + notifyListeners(); + } + + void unselectChat(int? chatId) { + selectedChats.remove(chatId); + notifyListeners(); + } + + void toggleSelectChat(int? chatId) { + if (selectedChats.contains(chatId)) { + selectedChats.remove(chatId); + } else { + selectedChats.add(chatId); + } + notifyListeners(); + } + + void toggleSelectAll() { + if (selectedChats.length == chats.length) { + selectedChats.clear(); + } else { + selectedChats = chats.map((chat) => chat.id).toSet(); + } + notifyListeners(); + } + + Future deleteSelectedChats() async { + // Delete selected chats from repository + for (var chatId in selectedChats) { + if (chatId != null) { + await ChatRepositoryProvider.instance.deleteChat(chatId); + } + } + + // Reload chat list + await refreshChats(); + + // Update activeChat if current active chat was deleted + if (selectedChats.contains(activeChat?.id)) { + if (_chats.isNotEmpty) { + await setActiveChat(_chats.first); + } else { + await clearActiveChat(); + } + } + + // Exit select mode + exitSelectMode(); + } +} diff --git a/lib/provider/mcp_server_provider.dart b/lib/provider/mcp_server_provider.dart new file mode 100644 index 0000000..268490d --- /dev/null +++ b/lib/provider/mcp_server_provider.dart @@ -0,0 +1,742 @@ +import 'dart:io'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import '../mcp/mcp.dart'; +import 'package:logging/logging.dart'; +import 'package:flutter/services.dart' show rootBundle; +import 'package:http/http.dart' as http; +import 'package:chatmcp/utils/platform.dart'; +import 'package:chatmcp/utils/storage_manager.dart'; +import '../mcp/client/mcp_client_interface.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../mcp/models/server.dart'; +import '../utils/oauth_web.dart' if (dart.library.io) '../utils/oauth_stub.dart'; +import '../utils/oauth_discovery.dart'; + +var defaultInMemoryServers = [ + {'name': 'Math', 'type': 'inmemory', 'command': 'math', 'env': {}, 'args': [], 'tools': []}, + {'name': 'Artifact Instructions', 'type': 'inmemory', 'command': 'artifact_instructions', 'env': {}, 'args': [], 'tools': []}, +]; + +class McpServerProvider extends ChangeNotifier { + static final McpServerProvider _instance = McpServerProvider._internal(); + factory McpServerProvider() => _instance; + + bool _isInitialized = false; + + McpServerProvider._internal() { + _initialize(); + } + + static const _configFileName = 'mcp_server.json'; + + final Map _servers = {}; + + Map get clients => _servers; + + // Check if current platform supports MCP Server + bool get isSupported { + return !kIsMobile && !kIsWeb; + } + + // Get configuration file path + Future get _configFilePath async { + if (kIsWeb) return ''; + final directoryPath = await StorageManager.getAppDataDirectory(); + return '$directoryPath/$_configFileName'; + } + + // Check and create initial configuration file + Future _initConfigFile() async { + if (kIsWeb) return; + + final file = File(await _configFilePath); + + if (!await file.exists()) { + // Load default configuration from assets + final defaultConfig = await rootBundle.loadString('assets/mcp_server.json'); + // Write default configuration to file + await file.writeAsString(defaultConfig); + Logger.root.info('Default configuration file initialized from assets'); + } + } + + // get installed servers count + Future get installedServersCount async { + if (kIsWeb) return 0; + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'] as Map; + return serverConfig.length; + } + + // Read server configuration + Future> _loadServers() async { + if (kIsWeb) { + final prefs = await SharedPreferences.getInstance(); + var configString = prefs.getString('mcp_servers_json'); + if (configString == null || configString.isEmpty) { + configString = await rootBundle.loadString('assets/mcp_server.json'); + await prefs.setString('mcp_servers_json', configString); + } + final Map data = json.decode(configString); + if (data['mcpServers'] == null) { + data['mcpServers'] = {}; + } + for (var server in data['mcpServers'].entries) { + server.value['installed'] = true; + } + return data; + } + + File? file; // Make file nullable or assign later + try { + await _initConfigFile(); + final configPath = await _configFilePath; + file = File(configPath); // Assign file here + final String contents = await file.readAsString(); + + // Check if contents are empty before attempting to decode + if (contents.trim().isEmpty) { + Logger.root.warning('Configuration file ($configPath) is empty. Returning default configuration.'); + return {'mcpServers': {}}; + } + + final Map data = json.decode(contents); + if (data['mcpServers'] == null) { + data['mcpServers'] = {}; + } + // 遍历data['mcpServers'],直接设置installed为true, + for (var server in data['mcpServers'].entries) { + server.value['installed'] = true; + } + return data; + } on FormatException catch (e, stackTrace) { + // Catch specific exception + final configPath = await _configFilePath; + Logger.root.severe('Failed to parse configuration file ($configPath): $e, stackTrace: $stackTrace'); + // Log the problematic content if possible and file is not null + if (file != null) { + try { + final String errorContents = await file.readAsString(); // Read again or use already read contents if file was assigned earlier + Logger.root.severe('Problematic configuration file content: "$errorContents"'); + } catch (readError) { + Logger.root.severe('Could not read configuration file content after format error: $readError'); + } + } + return {'mcpServers': {}}; // Return default on format error + } catch (e, stackTrace) { + // Catch other potential errors + final configPath = await _configFilePath; + Logger.root.severe('Failed to read configuration file ($configPath): $e, stackTrace: $stackTrace'); + return {'mcpServers': {}}; + } + } + + Future> loadServersAll() async { + final allServerConfig = await _loadServers(); + return allServerConfig; + } + + Future> loadServers() async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'] as Map; + final servers = Map.fromEntries(serverConfig.entries.where((entry) => entry.value['type'] != 'inmemory')); + return {'mcpServers': servers}; + } + + Future> loadInMemoryServers() async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'] as Map; + + // 检查默认内存服务器是否已存在,如不存在则添加 + bool needSave = false; + for (var server in defaultInMemoryServers) { + if (!serverConfig.containsKey(server['name'])) { + serverConfig[server['name'] as String] = server; + needSave = true; + } + } + + // 如果有新增服务器,保存配置 + if (needSave) { + await saveServers({'mcpServers': serverConfig}); + } + + // 过滤得到所有内存类型服务器 + final servers = Map.fromEntries(serverConfig.entries.where((entry) => entry.value['type'] == 'inmemory')); + + return {'mcpServers': servers}; + } + + Future addMcpServer(Map server) async { + final allServerConfig = await _loadServers(); + final newServers = {}; + newServers.addAll(allServerConfig['mcpServers'] as Map); + newServers[server['name']] = server; + // 更新配置 + allServerConfig['mcpServers'] = newServers; + await saveServers(allServerConfig); + notifyListeners(); + } + + Future removeMcpServer(String serverName) async { + final allServerConfig = await _loadServers(); + allServerConfig['mcpServers'].remove(serverName); + await saveServers(allServerConfig); + notifyListeners(); + } + + // Save server configuration + Future saveServers(Map servers) async { + if (kIsWeb) { + final prefs = await SharedPreferences.getInstance(); + final prettyContents = const JsonEncoder.withIndent(' ').convert(servers); + await prefs.setString('mcp_servers_json', prettyContents); + await _reinitializeClients(); + return; + } + try { + final file = File(await _configFilePath); + final prettyContents = const JsonEncoder.withIndent(' ').convert(servers); + await file.writeAsString(prettyContents); + // Reinitialize clients after saving + await _reinitializeClients(); + } catch (e, stackTrace) { + Logger.root.severe('Failed to save configuration file: $e, stackTrace: $stackTrace'); + } + } + + // Reinitialize clients + Future _reinitializeClients() async { + if (kIsWeb) return; + // _servers.clear(); + await init(); + notifyListeners(); + } + + void addClient(String key, McpClient client) { + _servers[key] = client; + notifyListeners(); + } + + void removeClient(String key) { + _servers.remove(key); + notifyListeners(); + } + + McpClient? getClient(String key) { + return _servers[key]; + } + + final Map>> _tools = {}; + Map>> get tools { + return _tools; + } + + // 存储工具类别的启用状态 + final Map _toolCategoryEnabled = {}; + Map get toolCategoryEnabled => _toolCategoryEnabled; + + // 切换工具类别的启用状态 + void toggleToolCategory(String category, bool enabled) { + _toolCategoryEnabled[category] = enabled; + notifyListeners(); + } + + // 获取工具类别的启用状态,默认为启用 + bool isToolCategoryEnabled(String category) { + return _toolCategoryEnabled[category] ?? false; + } + + bool loadingServerTools = false; + + Future>> getServerTools(String serverName, McpClient client) async { + final tools = >[]; + final response = await client.sendToolList(); + final toolsList = response.toJson()['result']['tools'] as List; + tools.addAll(toolsList.cast>()); + return tools; + } + + Future _initialize() async { + if (_isInitialized) return; + if (kIsWeb) { + _isInitialized = true; + return; + } + + try { + await _initConfigFile(); + _isInitialized = true; + } catch (e, stackTrace) { + Logger.root.severe('Failed to initialize MCP servers: $e, stackTrace: $stackTrace'); + } + } + + Future init() async { + if (!_isInitialized) { + await _initialize(); + } + + if (kIsWeb) { + return; + } + + try { + final configFilePath = await _configFilePath; + Logger.root.info('mcp_server path: $configFilePath'); + + final configFile = File(configFilePath); + final configContent = await configFile.readAsString(); + Logger.root.info('mcp_server config: $configContent'); + + final ignoreServers = []; + for (var entry in clients.entries) { + ignoreServers.add(entry.key); + } + + Logger.root.info('mcp_server ignoreServers: $ignoreServers'); + + notifyListeners(); + } catch (e, stackTrace) { + Logger.root.severe('Failed to initialize MCP servers: $e, stackTrace: $stackTrace'); + if (e is TypeError) { + final configFile = File(await _configFilePath); + final content = await configFile.readAsString(); + Logger.root.severe('Configuration file parsing error, current content: $content'); + } + } + } + + Future get mcpServerCount async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'] as Map; + return serverConfig.length; + } + + Future> get mcpServers async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'] as Map; + return serverConfig.keys.toList(); + } + + bool mcpServerIsRunning(String serverName) { + final client = clients[serverName]; + return client != null; + } + + Future stopMcpServer(String serverName) async { + final client = clients[serverName]; + if (client != null) { + await client.dispose(); + clients.remove(serverName); + notifyListeners(); + } + } + + Future startMcpServer(String serverName) async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName]; + final client = await initializeMcpServer(serverConfig); + if (client != null) { + clients[serverName] = client; + loadingServerTools = true; + notifyListeners(); + final tools = await getServerTools(serverName, client); + _tools[serverName] = tools; + loadingServerTools = false; + notifyListeners(); + } + return client; + } + + Future> initializeAllMcpServers(String configPath, List ignoreServers) async { + if (kIsWeb) return {}; + final file = File(configPath); + final contents = await file.readAsString(); + + final Map config = json.decode(contents) as Map? ?? {}; + + final mcpServers = config['mcpServers'] as Map; + + final Map clients = {}; + + for (var entry in mcpServers.entries) { + if (ignoreServers.contains(entry.key)) { + continue; + } + + final serverName = entry.key; + final serverConfig = entry.value as Map; + + try { + // Create async task and add to list + final client = await initializeMcpServer(serverConfig); + if (client != null) { + clients[serverName] = client; + loadingServerTools = true; + notifyListeners(); + final tools = await getServerTools(serverName, client); + _tools[serverName] = tools; + loadingServerTools = false; + notifyListeners(); + } + } catch (e, stackTrace) { + Logger.root.severe('Failed to initialize MCP server: $serverName, $e, stackTrace: $stackTrace'); + } + } + + return clients; + } + + String mcpServerMarket = "https://raw.githubusercontent.com/chatmcpclient/mcp_server_market/refs/heads/main/mcp_server_market.json"; + + Future> loadMarketServers() async { + try { + final response = await http.get(Uri.parse(mcpServerMarket)); + if (response.statusCode == 200) { + Logger.root.info('Successfully loaded market servers: ${response.body}'); + final Map jsonData = json.decode(response.body); + + final Map servers = jsonData['mcpServers'] as Map; + + var sseServers = {}; + + // For mobile platforms, only keep servers with commands starting with http + if (kIsMobile) { + for (var server in servers.entries) { + if (server.value['command'] != null && server.value['command'].toString().startsWith('http')) { + sseServers[server.key] = server.value; + } + } + } else { + sseServers = servers; + } + + // 获取本地已安装的mcp服务器 + final localInstalledServers = await _loadServers(); + //遍历sseServers,如果本地已安装的mcp服务器中存在,则将sseServers中的该服务器设置为已安装 + for (var server in sseServers.entries) { + if (localInstalledServers['mcpServers'][server.key] != null) { + server.value['installed'] = true; + } else { + server.value['installed'] = false; + } + } + + return {'mcpServers': sseServers}; + } + throw Exception('Failed to load market servers: ${response.statusCode}'); + } catch (e, stackTrace) { + Logger.root.severe('Failed to load market servers: $e, stackTrace: $stackTrace'); + throw Exception('Failed to load market servers: $e'); + } + } + + // OAuth-related methods + + /// Discovers OAuth configuration for a server URL automatically + Future discoverOAuthForServer(String serverUrl) async { + if (!kIsWeb) { + return OAuthDiscoveryResult(requiresOAuth: false); + } + + try { + Logger.root.info('Discovering OAuth for server: $serverUrl'); + final result = await OAuthDiscoveryService.discoverOAuth(serverUrl); + + if (result.requiresOAuth) { + Logger.root.info('OAuth required for server: $serverUrl'); + Logger.root.info(' Authorization URL: ${result.authorizationUrl}'); + Logger.root.info(' Token URL: ${result.tokenUrl}'); + Logger.root.info(' Client ID: ${result.clientId}'); + } else { + Logger.root.info('No OAuth required for server: $serverUrl'); + } + + return result; + } catch (e) { + Logger.root.warning('OAuth discovery failed for $serverUrl: $e'); + return OAuthDiscoveryResult(requiresOAuth: false); + } + } + + /// Automatically configures and authenticates a server with discovered OAuth + Future autoAuthenticateServer(String serverName, OAuthDiscoveryResult oauthConfig) async { + if (!kIsWeb || !oauthConfig.requiresOAuth) { + return false; + } + + try { + Logger.root.info('Auto-authenticating server: $serverName'); + + // Use discovered client ID or null for public clients (like Notion MCP) + String? clientId = oauthConfig.clientId; + String scope = oauthConfig.scope ?? 'read write'; + String redirectUri = oauthConfig.redirectUri ?? '${Uri.base.origin}/oauth_callback.html'; + + Logger.root.info('Using clientId: $clientId, scope: $scope, redirectUri: $redirectUri'); + + // Start OAuth flow with discovered configuration + final authResult = await WebOAuthHandler.startOAuthFlow( + authorizationUrl: oauthConfig.authorizationUrl!, + clientId: clientId, + redirectUri: redirectUri, + scope: scope, + ); + + // Exchange code for token + final tokenResult = await WebOAuthHandler.exchangeCodeForToken( + tokenUrl: oauthConfig.tokenUrl!, + clientId: clientId, + clientSecret: null, // Public clients don't require client secret + code: authResult['code'] as String, + codeVerifier: authResult['code_verifier'] as String, + redirectUri: redirectUri, + ); + + // Update server configuration with OAuth info and tokens + final updatedConfig = OAuthDiscoveryResult( + requiresOAuth: oauthConfig.requiresOAuth, + authorizationUrl: oauthConfig.authorizationUrl, + tokenUrl: oauthConfig.tokenUrl, + clientId: clientId, + scope: scope, + redirectUri: redirectUri, + ); + await _saveOAuthConfigForServer(serverName, updatedConfig, tokenResult); + + Logger.root.info('Auto-authentication successful for: $serverName'); + notifyListeners(); + return true; + + } catch (e) { + Logger.root.severe('Auto-authentication failed for $serverName: $e'); + return false; + } + } + + /// Saves discovered OAuth configuration and tokens to server config + Future _saveOAuthConfigForServer( + String serverName, + OAuthDiscoveryResult oauthConfig, + Map tokenResult + ) async { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName] as Map?; + + if (serverConfig != null) { + serverConfig['oauth'] = { + 'enabled': true, + 'client_id': oauthConfig.clientId, + 'authorization_url': oauthConfig.authorizationUrl, + 'token_url': oauthConfig.tokenUrl, + 'scope': oauthConfig.scope, + 'redirect_uri': oauthConfig.redirectUri, + 'access_token': tokenResult['access_token'], + 'refresh_token': tokenResult['refresh_token'], + 'token_expiry': tokenResult['expires_at'] ?? + DateTime.now().add(Duration(seconds: tokenResult['expires_in'] ?? 3600)).toIso8601String(), + }; + + // Save updated configuration + await saveServers(allServerConfig); + } + } + + /// Initiates OAuth flow for a server + Future authenticateServer(String serverName) async { + try { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName] as Map?; + + Logger.root.info('Authenticating server: $serverName'); + Logger.root.info('Server config: $serverConfig'); + + if (serverConfig == null) { + throw Exception('Server not found: $serverName'); + } + + final oauth = serverConfig['oauth'] as Map?; + Logger.root.info('OAuth config: $oauth'); + + if (oauth == null || oauth['enabled'] != true) { + throw Exception('OAuth not enabled for server: $serverName'); + } + + if (!kIsWeb) { + throw Exception('OAuth is only supported on web platform'); + } + + // Extract OAuth parameters with debugging + final authorizationUrl = oauth['authorization_url'] as String? ?? ''; + final clientId = oauth['client_id'] as String? ?? ''; + final redirectUri = oauth['redirect_uri'] as String? ?? ''; + final scope = oauth['scope'] as String? ?? ''; + + Logger.root.info('OAuth params extracted:'); + Logger.root.info(' authorizationUrl: "$authorizationUrl"'); + Logger.root.info(' clientId: "$clientId"'); + Logger.root.info(' redirectUri: "$redirectUri"'); + Logger.root.info(' scope: "$scope"'); + + // Start OAuth flow + final authResult = await WebOAuthHandler.startOAuthFlow( + authorizationUrl: authorizationUrl, + clientId: clientId, + redirectUri: redirectUri, + scope: scope, + ); + + // Exchange code for token + final tokenResult = await WebOAuthHandler.exchangeCodeForToken( + tokenUrl: oauth['token_url'] as String, + clientId: oauth['client_id'] as String, + clientSecret: oauth['client_secret'] as String?, + code: authResult['code'] as String, + codeVerifier: authResult['code_verifier'] as String, + redirectUri: oauth['redirect_uri'] as String, + ); + + // Update server config with tokens + final updatedOAuth = { + ...oauth, + 'access_token': tokenResult['access_token'], + 'refresh_token': tokenResult['refresh_token'], + 'token_expiry': tokenResult['expires_at'] ?? + DateTime.now().add(Duration(seconds: tokenResult['expires_in'] ?? 3600)).toIso8601String(), + }; + + serverConfig['oauth'] = updatedOAuth; + allServerConfig['mcpServers'][serverName] = serverConfig; + + await saveServers(allServerConfig); + + Logger.root.info('OAuth authentication successful for server: $serverName'); + return true; + } catch (e, stackTrace) { + Logger.root.severe('OAuth authentication failed for server $serverName: $e, stackTrace: $stackTrace'); + rethrow; + } + } + + /// Refreshes OAuth token for a server + Future refreshServerToken(String serverName) async { + try { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName] as Map?; + + if (serverConfig == null) { + throw Exception('Server not found: $serverName'); + } + + final oauth = serverConfig['oauth'] as Map?; + if (oauth == null || oauth['enabled'] != true) { + throw Exception('OAuth not enabled for server: $serverName'); + } + + final refreshToken = oauth['refresh_token'] as String?; + if (refreshToken == null) { + throw Exception('No refresh token available for server: $serverName'); + } + + if (!kIsWeb) { + throw Exception('OAuth is only supported on web platform'); + } + + // Refresh token + final tokenResult = await WebOAuthHandler.refreshToken( + tokenUrl: oauth['token_url'] as String, + clientId: oauth['client_id'] as String, + clientSecret: oauth['client_secret'] as String?, + refreshToken: refreshToken, + ); + + // Update server config with new tokens + final updatedOAuth = { + ...oauth, + 'access_token': tokenResult['access_token'], + if (tokenResult['refresh_token'] != null) 'refresh_token': tokenResult['refresh_token'], + 'token_expiry': tokenResult['expires_at'] ?? + DateTime.now().add(Duration(seconds: tokenResult['expires_in'] ?? 3600)).toIso8601String(), + }; + + serverConfig['oauth'] = updatedOAuth; + allServerConfig['mcpServers'][serverName] = serverConfig; + + await saveServers(allServerConfig); + + Logger.root.info('OAuth token refresh successful for server: $serverName'); + return true; + } catch (e, stackTrace) { + Logger.root.severe('OAuth token refresh failed for server $serverName: $e, stackTrace: $stackTrace'); + rethrow; + } + } + + /// Checks if server has valid OAuth token + Future isServerAuthenticated(String serverName) async { + try { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName] as Map?; + if (serverConfig == null) return false; + + final oauth = serverConfig['oauth'] as Map?; + if (oauth == null || oauth['enabled'] != true) return false; + + final accessToken = oauth['access_token'] as String?; + if (accessToken == null) return false; + + final tokenExpiry = oauth['token_expiry'] as String?; + if (tokenExpiry != null) { + final expiry = DateTime.parse(tokenExpiry); + if (DateTime.now().isAfter(expiry)) return false; + } + + return true; + } catch (e) { + return false; + } + } + + /// Gets current OAuth status for a server + Future> getServerOAuthStatus(String serverName) async { + try { + final allServerConfig = await _loadServers(); + final serverConfig = allServerConfig['mcpServers'][serverName] as Map?; + + if (serverConfig == null) { + return {'enabled': false, 'authenticated': false, 'error': 'Server not found'}; + } + + final oauth = serverConfig['oauth'] as Map?; + if (oauth == null || oauth['enabled'] != true) { + return {'enabled': false, 'authenticated': false}; + } + + final accessToken = oauth['access_token'] as String?; + if (accessToken == null) { + return {'enabled': true, 'authenticated': false, 'error': 'No access token'}; + } + + final tokenExpiry = oauth['token_expiry'] as String?; + bool isExpired = false; + bool needsRefresh = false; + + if (tokenExpiry != null) { + final expiry = DateTime.parse(tokenExpiry); + isExpired = DateTime.now().isAfter(expiry); + needsRefresh = DateTime.now().isAfter(expiry.subtract(const Duration(minutes: 5))); + } + + return { + 'enabled': true, + 'authenticated': !isExpired, + 'needs_refresh': needsRefresh, + 'token_expiry': tokenExpiry, + }; + } catch (e) { + return {'enabled': false, 'authenticated': false, 'error': e.toString()}; + } + } +} diff --git a/lib/provider/provider_manager.dart b/lib/provider/provider_manager.dart new file mode 100644 index 0000000..744e40c --- /dev/null +++ b/lib/provider/provider_manager.dart @@ -0,0 +1,60 @@ +import 'dart:async'; +import 'package:provider/provider.dart'; +import 'settings_provider.dart'; +import 'mcp_server_provider.dart'; +import 'chat_provider.dart'; +import 'chat_model_provider.dart'; +import 'serve_state_provider.dart'; + +class ProviderManager { + static List providers = [ + ChangeNotifierProvider(create: (_) => SettingsProvider()), + ChangeNotifierProvider(create: (_) => McpServerProvider()), + ChangeNotifierProvider(create: (_) => ChatProvider()), + ChangeNotifierProvider(create: (_) => ChatModelProvider()), + ChangeNotifierProvider(create: (_) => ServerStateProvider()), + // Add other Providers here + ]; + + static SettingsProvider? _settingsProvider; + + static SettingsProvider get settingsProvider { + _settingsProvider ??= SettingsProvider(); + return _settingsProvider!; + } + + static McpServerProvider? _mcpServerProvider; + + static McpServerProvider get mcpServerProvider { + _mcpServerProvider ??= McpServerProvider(); + return _mcpServerProvider!; + } + + static ChatProvider? _chatProvider; + + static ChatProvider get chatProvider { + _chatProvider ??= ChatProvider(); + return _chatProvider!; + } + + static ChatModelProvider? _chatModelProvider; + + static ChatModelProvider get chatModelProvider { + _chatModelProvider ??= ChatModelProvider(); + return _chatModelProvider!; + } + + static ServerStateProvider? _serverStateProvider; + + static ServerStateProvider get serverStateProvider { + _serverStateProvider ??= ServerStateProvider(); + return _serverStateProvider!; + } + + static Future init() async { + await SettingsProvider().loadSettings(); + await ChatProvider().loadChats(); + await McpServerProvider().init(); + await McpServerProvider().loadInMemoryServers(); + } +} diff --git a/lib/provider/serve_state_provider.dart b/lib/provider/serve_state_provider.dart new file mode 100644 index 0000000..a605b58 --- /dev/null +++ b/lib/provider/serve_state_provider.dart @@ -0,0 +1,73 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:chatmcp/provider/mcp_server_provider.dart'; + +class ServerStateProvider extends ChangeNotifier { + static final ServerStateProvider _instance = ServerStateProvider._internal(); + factory ServerStateProvider() => _instance; + ServerStateProvider._internal(); + + // 服务器启用状态 + final Map _enabledStates = {}; + // 服务器运行状态 + final Map _runningStates = {}; + // 正在启动的服务器 + final Map _startingStates = {}; + + // 获取已启用的服务器数量 + int get enabledCount => _enabledStates.values.where((value) => value).length; + + // 获取服务器启用状态 + bool isEnabled(String serverName) => _enabledStates[serverName] ?? false; + + // 获取服务器运行状态 + bool isRunning(String serverName) => _runningStates[serverName] ?? false; + + // 获取服务器启动中状态 + bool isStarting(String serverName) => _startingStates[serverName] ?? false; + + // 设置服务器启用状态 + void setEnabled(String serverName, bool value) { + _enabledStates[serverName] = value; + notifyListeners(); + } + + // 设置服务器运行状态 + void setRunning(String serverName, bool value) { + _runningStates[serverName] = value; + _startingStates.remove(serverName); // 不再处于启动中状态 + notifyListeners(); + } + + // 设置服务器启动中状态 + void setStarting(String serverName, bool value) { + _startingStates[serverName] = value; + notifyListeners(); + } + + // 从McpServerProvider同步状态 + void syncFromProvider(McpServerProvider provider, List servers) { + if (servers.isEmpty) return; + + bool changed = false; + for (String server in servers) { + // 同步启用状态 + bool enabled = provider.isToolCategoryEnabled(server); + if (_enabledStates[server] != enabled) { + _enabledStates[server] = enabled; + changed = true; + } + + // 同步运行状态 + bool running = provider.mcpServerIsRunning(server); + if (_runningStates[server] != running) { + _runningStates[server] = running; + changed = true; + } + } + + if (changed) { + notifyListeners(); + } + } +} diff --git a/lib/provider/settings_provider.dart b/lib/provider/settings_provider.dart new file mode 100644 index 0000000..5a839ca --- /dev/null +++ b/lib/provider/settings_provider.dart @@ -0,0 +1,501 @@ +import 'package:chatmcp/llm/llm_factory.dart'; +import 'package:chatmcp/llm/model.dart' as llm_model; +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:convert'; +import 'package:logging/logging.dart'; + +class LLMProviderSetting { + String apiKey; + String apiEndpoint; + String? apiVersion; + String? apiStyle; + String? providerName; + List? models; + List? enabledModels; + String? providerId; + bool custom = false; + String icon = ''; + String? genTitleModel; + String? link; + int? priority; + bool? enable; + + LLMProviderSetting({ + required this.apiKey, + required this.apiEndpoint, + this.apiVersion, + this.apiStyle, + this.providerName, + this.models, + this.enabledModels, + this.providerId, + this.custom = false, + this.icon = '', + this.genTitleModel, + this.link, + this.priority, + this.enable, + }); + + Map toJson() { + return { + 'apiKey': apiKey, + 'apiEndpoint': apiEndpoint, + 'apiVersion': apiVersion, + 'apiStyle': apiStyle, + 'providerName': providerName, + 'models': models, + 'enabledModels': enabledModels, + 'provider': providerId, + 'custom': custom, + 'icon': icon, + 'genTitleModel': genTitleModel, + 'link': link, + 'priority': priority, + 'enable': enable, + }; + } + + factory LLMProviderSetting.fromJson(Map json) { + return LLMProviderSetting( + apiKey: json['apiKey'] as String, + apiEndpoint: json['apiEndpoint'] as String, + apiVersion: json['apiVersion'] as String?, + apiStyle: json['apiStyle'] as String? ?? 'openai', + providerName: json['providerName'] as String, + models: json['models'] != null ? List.from(json['models']) : [], + enabledModels: json['enabledModels'] != null ? List.from(json['enabledModels']) : [], + providerId: json['provider'] as String? ?? '', + icon: json['icon'] as String? ?? '', + custom: json['custom'] as bool? ?? false, + genTitleModel: json['genTitleModel'] as String? ?? '', + link: json['link'] as String? ?? '', + priority: json['priority'] as int? ?? 0, + enable: json['enable'] as bool?, + ); + } +} + +var defaultSystemPrompt = '''You are an intelligent and helpful AI assistant. Please: +1. Provide clear and concise responses +2. If you're not sure about something, please say so +3. When appropriate, provide examples to illustrate your points +4. If a user messages you in a specific language, respond in that language +5. Format responses using markdown when helpful +6. Use mermaid to generate diagrams'''; + +class GeneralSetting { + String theme; + bool showAssistantAvatar = false; + bool showUserAvatar = false; + String systemPrompt; + String locale; + int maxMessages; + int maxLoops; + + // 代理设置 + bool enableProxy = false; + String proxyType = 'HTTP'; // HTTP, HTTPS, SOCKS4, SOCKS5 + String proxyHost = ''; + int proxyPort = 8080; + String proxyUsername = ''; + String proxyPassword = ''; + + GeneralSetting({ + required this.theme, + this.showAssistantAvatar = false, + this.showUserAvatar = false, + this.systemPrompt = 'You are a helpful assistant.', + this.locale = 'en', + this.maxMessages = 50, + this.maxLoops = 100, + this.enableProxy = false, + this.proxyType = 'HTTP', + this.proxyHost = '', + this.proxyPort = 8080, + this.proxyUsername = '', + this.proxyPassword = '', + }); + + Map toJson() { + return { + 'theme': theme, + 'showAssistantAvatar': showAssistantAvatar, + 'showUserAvatar': showUserAvatar, + 'systemPrompt': systemPrompt, + 'locale': locale, + 'maxMessages': maxMessages, + 'maxLoops': maxLoops, + 'enableProxy': enableProxy, + 'proxyType': proxyType, + 'proxyHost': proxyHost, + 'proxyPort': proxyPort, + 'proxyUsername': proxyUsername, + 'proxyPassword': proxyPassword, + }; + } + + factory GeneralSetting.fromJson(Map json) { + return GeneralSetting( + theme: json['theme'] as String? ?? 'light', + showAssistantAvatar: json['showAssistantAvatar'] as bool? ?? false, + showUserAvatar: json['showUserAvatar'] as bool? ?? false, + systemPrompt: json['systemPrompt'] as String? ?? defaultSystemPrompt, + locale: json['locale'] as String? ?? 'en', + maxMessages: json['maxMessages'] as int? ?? 50, + maxLoops: json['maxLoops'] as int? ?? 100, + enableProxy: json['enableProxy'] as bool? ?? false, + proxyType: json['proxyType'] as String? ?? 'HTTP', + proxyHost: json['proxyHost'] as String? ?? '', + proxyPort: json['proxyPort'] as int? ?? 8080, + proxyUsername: json['proxyUsername'] as String? ?? '', + proxyPassword: json['proxyPassword'] as String? ?? '', + ); + } +} + +class ChatSetting { + double temperature = 1.0; + int? maxTokens; + double topP = 1.0; + double frequencyPenalty = 0.0; + double presencePenalty = 0.0; + + ChatSetting({this.temperature = 1.0, this.maxTokens, this.topP = 1.0, this.frequencyPenalty = 0.0, this.presencePenalty = 0.0}); + + Map toJson() { + return { + 'temperature': temperature, + 'maxTokens': maxTokens, + 'topP': topP, + 'frequencyPenalty': frequencyPenalty, + 'presencePenalty': presencePenalty, + }; + } + + factory ChatSetting.fromJson(Map json) { + return ChatSetting( + temperature: json['temperature'] as double? ?? 1.0, + maxTokens: json['maxTokens'] == null ? null : json['maxTokens'] as int, + topP: json['topP'] as double? ?? 1.0, + frequencyPenalty: json['frequencyPenalty'] as double? ?? 0.0, + presencePenalty: json['presencePenalty'] as double? ?? 0.0, + ); + } +} + +final List defaultApiSettings = [ + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://api.githubcopilot.com', + apiStyle: 'openai', + providerId: 'copilot', + providerName: 'GitHub Copilot', + icon: 'copilot', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://YOUR_RESOURCE_NAME.openai.azure.com', + apiStyle: 'foundry', + apiVersion: '2025-01-01-preview', + providerId: 'foundry', + providerName: 'Azure AI Foundry', + icon: 'foundry', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://api.openai.com/v1', + apiStyle: 'openai', + providerId: 'openai', + providerName: 'OpenAI', + icon: 'openai', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://api.anthropic.com/v1', + apiStyle: 'claude', + providerId: 'claude', + providerName: 'Claude', + icon: 'claude', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: '', // Not used by CLI mode + apiStyle: 'claude-code', + providerId: 'claude-code', + providerName: 'Claude Code', + icon: 'claude', + custom: false, + link: 'https://docs.anthropic.com/en/docs/claude-code/sdk', + models: ['claude-3-7-sonnet', 'claude-3-opus', 'claude-3-5-sonnet', 'claude-3-5-haiku'], + enabledModels: ['claude-3-7-sonnet', 'claude-3-5-sonnet'], + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://api.deepseek.com', + apiStyle: 'deepseek', + providerId: 'deepseek', + providerName: 'DeepSeek', + icon: 'deepseek', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'http://localhost:11434', + apiStyle: 'openai', + providerId: 'ollama', + providerName: 'Ollama', + icon: 'ollama', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://generativelanguage.googleapis.com/v1beta', + apiStyle: 'gemini', + providerId: 'gemini', + providerName: 'Gemini', + icon: 'gemini', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://openrouter.ai/api/v1', + apiStyle: 'openai', + providerId: 'openrouter', + providerName: 'OpenRouter', + icon: 'openrouter', + custom: false, + ), + LLMProviderSetting( + apiKey: '', + apiEndpoint: 'https://api.302.ai/v1', + apiStyle: 'openai', + providerId: '302.AI', + providerName: '302.AI', + icon: '302ai', + custom: false, + link: 'https://share.302.ai/euPaZh', + priority: 1, + ), +]; + +final apiSettingsKey = 'apiSettings_v6'; + +class SettingsProvider extends ChangeNotifier { + static final SettingsProvider _instance = SettingsProvider._internal(); + factory SettingsProvider() => _instance; + SettingsProvider._internal(); + + List _apiSettings = []; + + GeneralSetting _generalSetting = GeneralSetting(theme: 'light', systemPrompt: defaultSystemPrompt); + + ChatSetting _modelSetting = ChatSetting(); + + List get apiSettings => _apiSettings; + + LLMProviderSetting getProviderSetting(String providerId) => _apiSettings.firstWhere((element) => element.providerId == providerId); + + GeneralSetting get generalSetting => _generalSetting; + + ChatSetting get modelSetting => _modelSetting; + + int sandboxServerPort = 0; + + Future updateSandboxServerPort({required int port}) async { + sandboxServerPort = port; + notifyListeners(); + } + + List _availableModels = []; + + List get availableModels => _availableModels; + + Future updateAvailableModels({required List models}) async { + _availableModels = models; + notifyListeners(); + } + + Future> getAvailableModels() async { + final models = []; + for (var setting in _apiSettings) { + // 只有启用的提供商才加入模型列表(null 表示启用,只有 false 为禁用) + final isEnabled = setting.enable ?? true; + if (!isEnabled) continue; + + for (var model in setting.enabledModels ?? []) { + var m = llm_model.Model( + name: model, + label: model, + providerId: setting.providerId ?? '', + icon: setting.icon, + providerName: setting.providerName ?? '', + apiStyle: setting.apiStyle ?? '', + priority: setting.priority ?? 0, + ); + + if (LLMFactoryHelper.isChatModel(m)) { + models.add(m); + } + } + } + return models; + } + + Future> loadSettings() async { + final prefs = await SharedPreferences.getInstance(); + final String? settingsJson = prefs.getString(apiSettingsKey); + + List settings = []; + + if (settingsJson != null) { + try { + final List decoded = jsonDecode(settingsJson); + settings = decoded.map((value) => LLMProviderSetting.fromJson(value as Map)).toList(); + } catch (e) { + Logger.root.severe('Error parsing $apiSettingsKey: $e'); + settings = [..._apiSettings]; + } + } + + for (var setting in defaultApiSettings) { + if (!settings.any((element) => element.providerId == setting.providerId)) { + settings = [...settings, setting]; + } + } + + _apiSettings = settings; + + final String? generalSettingsJson = prefs.getString('generalSettings'); + if (generalSettingsJson != null) { + final Map decoded = jsonDecode(generalSettingsJson); + _generalSetting = GeneralSetting.fromJson(decoded); + } + + final String? modelSettingsJson = prefs.getString('modelSettings'); + if (modelSettingsJson != null) { + final Map decoded = jsonDecode(modelSettingsJson); + _modelSetting = ChatSetting.fromJson(decoded); + } + + final availableModels = await getAvailableModels(); + + updateAvailableModels(models: availableModels); + + notifyListeners(); + + // sort by priority descending _apiSettings + _apiSettings.sort((a, b) => (b.priority ?? 0).compareTo(a.priority ?? 0)); + + return _apiSettings; + } + + Future updateApiSettings({required List apiSettings}) async { + final prefs = await SharedPreferences.getInstance(); + + _apiSettings = apiSettings; + + final encodedSettings = apiSettings.map((value) => value.toJson()).toList(); + + await prefs.setString(apiSettingsKey, jsonEncode(encodedSettings)); + Logger.root.info('updateApiSettings: ${jsonEncode(encodedSettings)}'); + + final availableModels = await getAvailableModels(); + updateAvailableModels(models: availableModels); + + notifyListeners(); + } + + Future updateGeneralSettingsPartially({ + String? theme, + bool? showAssistantAvatar, + bool? showUserAvatar, + String? systemPrompt, + String? locale, + int? maxMessages, + int? maxLoops, + bool? enableProxy, + String? proxyType, + String? proxyHost, + int? proxyPort, + String? proxyUsername, + String? proxyPassword, + }) async { + final prefs = await SharedPreferences.getInstance(); + + _generalSetting = GeneralSetting( + theme: theme ?? _generalSetting.theme, + showAssistantAvatar: showAssistantAvatar ?? _generalSetting.showAssistantAvatar, + showUserAvatar: showUserAvatar ?? _generalSetting.showUserAvatar, + systemPrompt: systemPrompt ?? _generalSetting.systemPrompt, + locale: locale ?? _generalSetting.locale, + maxMessages: maxMessages ?? _generalSetting.maxMessages, + maxLoops: maxLoops ?? _generalSetting.maxLoops, + enableProxy: enableProxy ?? _generalSetting.enableProxy, + proxyType: proxyType ?? _generalSetting.proxyType, + proxyHost: proxyHost ?? _generalSetting.proxyHost, + proxyPort: proxyPort ?? _generalSetting.proxyPort, + proxyUsername: proxyUsername ?? _generalSetting.proxyUsername, + proxyPassword: proxyPassword ?? _generalSetting.proxyPassword, + ); + await prefs.setString('generalSettings', jsonEncode(_generalSetting.toJson())); + + notifyListeners(); + } + + Future updateGeneralSettings({ + required String theme, + required bool showAssistantAvatar, + required bool showUserAvatar, + required String systemPrompt, + required String locale, + int? maxMessages, + int? maxLoops, + }) async { + final prefs = await SharedPreferences.getInstance(); + _generalSetting = GeneralSetting( + theme: theme, + showAssistantAvatar: showAssistantAvatar, + showUserAvatar: showUserAvatar, + systemPrompt: systemPrompt, + locale: locale, + maxMessages: maxMessages ?? _generalSetting.maxMessages, + maxLoops: maxLoops ?? _generalSetting.maxLoops, + ); + await prefs.setString('generalSettings', jsonEncode(_generalSetting.toJson())); + notifyListeners(); + } + + Future updateModelSettings({ + required double temperature, + required int? maxTokens, + required double topP, + required double frequencyPenalty, + required double presencePenalty, + }) async { + _modelSetting = ChatSetting( + temperature: temperature, + maxTokens: maxTokens, + topP: topP, + frequencyPenalty: frequencyPenalty, + presencePenalty: presencePenalty, + ); + + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('modelSettings', jsonEncode(_modelSetting.toJson())); + notifyListeners(); + } + + Future resetModelSettings() async { + _modelSetting = ChatSetting(); + + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('modelSettings', jsonEncode(_modelSetting.toJson())); + notifyListeners(); + } +} diff --git a/lib/repository/chat_repository.dart b/lib/repository/chat_repository.dart new file mode 100644 index 0000000..98722b4 --- /dev/null +++ b/lib/repository/chat_repository.dart @@ -0,0 +1,31 @@ +import 'package:chatmcp/dao/chat.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:chatmcp/config/pagination_config.dart'; + +class ChatListResult { + final List chats; + final int total; + final bool hasMore; + + ChatListResult({required this.chats, required this.total, required this.hasMore}); +} + +abstract class ChatRepository { + Future getChats({ + int page = 1, // 页码从 1 开始,符合常规分页概念 + int pageSize = PaginationConfig.defaultPageSize, + String? searchKeyword, + }); + Future getChatById(int id); + Future createChat(Chat chat, List messages); + Future updateChat(Chat chat); + Future deleteChat(int id); + Future addChatMessage(int chatId, List messages); + Future> getChatMessages(int chatId); + + @Deprecated('Use getChats() instead') + Future> getAllChats() async { + final result = await getChats(pageSize: PaginationConfig.maxPageSize); + return result.chats; + } +} diff --git a/lib/repository/chat_repository_provider.dart b/lib/repository/chat_repository_provider.dart new file mode 100644 index 0000000..8e9166e --- /dev/null +++ b/lib/repository/chat_repository_provider.dart @@ -0,0 +1,38 @@ +import 'package:chatmcp/repository/chat_repository.dart'; +import 'package:chatmcp/repository/local_chat_repository.dart'; +import 'package:chatmcp/repository/remote_chat_repository.dart'; + +enum RepositoryType { local, remote } + +class ChatRepositoryFactory { + static ChatRepository create(RepositoryType type, {String? baseUrl, String? apiKey}) { + switch (type) { + case RepositoryType.local: + return LocalChatRepository(); + case RepositoryType.remote: + if (baseUrl == null || apiKey == null) { + throw ArgumentError('Remote repository requires baseUrl and apiKey'); + } + return RemoteChatRepository(baseUrl: baseUrl, apiKey: apiKey); + } + } +} + +class ChatRepositoryProvider { + static ChatRepository? _instance; + static RepositoryType _currentType = RepositoryType.local; + + static ChatRepository get instance { + return _instance ??= ChatRepositoryFactory.create(_currentType); + } + + static void configure(RepositoryType type, {String? baseUrl, String? apiKey}) { + _currentType = type; + _instance = ChatRepositoryFactory.create(type, baseUrl: baseUrl, apiKey: apiKey); + } + + static void reset() { + _instance = null; + _currentType = RepositoryType.local; + } +} diff --git a/lib/repository/local_chat_repository.dart b/lib/repository/local_chat_repository.dart new file mode 100644 index 0000000..42b5726 --- /dev/null +++ b/lib/repository/local_chat_repository.dart @@ -0,0 +1,95 @@ +import 'package:chatmcp/dao/chat.dart'; +import 'package:chatmcp/dao/chat_message.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:chatmcp/repository/chat_repository.dart'; +import 'package:chatmcp/config/pagination_config.dart'; + +class LocalChatRepository implements ChatRepository { + final ChatDao _chatDao = ChatDao(); + final ChatMessageDao _chatMessageDao = ChatMessageDao(); + + @override + Future getChats({ + int page = 1, // 页码从 1 开始 + int pageSize = PaginationConfig.defaultPageSize, + String? searchKeyword, + }) async { + // 转换为从 0 开始的 offset 计算 + final offset = (page - 1) * pageSize; + + // Build where clause for search + String? whereClause; + List? whereArgs; + + if (searchKeyword != null && searchKeyword.isNotEmpty) { + whereClause = 'title LIKE ?'; + whereArgs = ['%$searchKeyword%']; + } + + // Get total count + final allChats = await _chatDao.query(where: whereClause, whereArgs: whereArgs); + final total = allChats.length; + + // Get paginated results + final chats = await _chatDao.query(where: whereClause, whereArgs: whereArgs, orderBy: 'updatedAt DESC', limit: pageSize, offset: offset); + + final hasMore = offset + pageSize < total; + + return ChatListResult(chats: chats, total: total, hasMore: hasMore); + } + + @override + Future> getAllChats() async { + return await _chatDao.query(orderBy: 'updatedAt DESC'); + } + + @override + Future getChatById(int id) async { + return await _chatDao.queryById(id.toString()); + } + + @override + Future createChat(Chat chat, List messages) async { + final chatId = await _chatDao.insert(chat); + final newChat = Chat(id: chatId, title: chat.title, createdAt: chat.createdAt, updatedAt: chat.updatedAt); + + if (messages.isNotEmpty) { + await addChatMessage(chatId, messages); + } + + return newChat; + } + + @override + Future updateChat(Chat chat) async { + if (chat.id != null) { + await _chatDao.update(chat, chat.id.toString()); + } + } + + @override + Future deleteChat(int id) async { + await _chatMessageDao.deleteMessages(id); + await _chatDao.delete(id.toString()); + } + + @override + Future addChatMessage(int chatId, List messages) async { + for (final message in messages) { + if (message.role == MessageRole.error) { + continue; + } + final existingMessages = await _chatMessageDao.query(where: 'messageId = ?', whereArgs: [message.messageId]); + if (existingMessages.isNotEmpty) { + continue; + } + await _chatMessageDao.insert(message.toDb(chatId)); + } + } + + @override + Future> getChatMessages(int chatId) async { + final chatMessages = await _chatMessageDao.query(where: 'chatId = ?', whereArgs: [chatId], orderBy: 'createdAt ASC'); + return chatMessages.map((e) => ChatMessage.fromDb(e)).toList(); + } +} diff --git a/lib/repository/remote_chat_repository.dart b/lib/repository/remote_chat_repository.dart new file mode 100644 index 0000000..7cff18f --- /dev/null +++ b/lib/repository/remote_chat_repository.dart @@ -0,0 +1,159 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:chatmcp/dao/chat.dart'; +import 'package:chatmcp/llm/model.dart'; +import 'package:chatmcp/repository/chat_repository.dart'; +import 'package:chatmcp/config/pagination_config.dart'; + +class RemoteChatRepository implements ChatRepository { + final String baseUrl; + final String apiKey; + + RemoteChatRepository({required this.baseUrl, required this.apiKey}); + + Map get _headers => {'Content-Type': 'application/json', 'Authorization': 'Bearer $apiKey'}; + + @override + Future getChats({ + int page = 1, // 页码从 1 开始 + int pageSize = PaginationConfig.defaultPageSize, + String? searchKeyword, + }) async { + var uri = Uri.parse('$baseUrl/chats'); + final queryParams = {'page': page.toString(), 'pageSize': pageSize.toString()}; + + if (searchKeyword != null && searchKeyword.isNotEmpty) { + queryParams['search'] = searchKeyword; + } + + uri = uri.replace(queryParameters: queryParams); + + final response = await http.get(uri, headers: _headers); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + final List chatsData = data['chats'] ?? []; + final chats = chatsData.map((item) => _chatFromJson(item)).toList(); + + return ChatListResult(chats: chats, total: data['total'] ?? chats.length, hasMore: data['hasMore'] ?? false); + } else { + throw Exception('Failed to load chats: ${response.statusCode}'); + } + } + + @override + Future> getAllChats() async { + final response = await http.get(Uri.parse('$baseUrl/chats'), headers: _headers); + + if (response.statusCode == 200) { + final List data = json.decode(response.body); + return data.map((item) => _chatFromJson(item)).toList(); + } else { + throw Exception('Failed to load chats: ${response.statusCode}'); + } + } + + @override + Future getChatById(int id) async { + final response = await http.get(Uri.parse('$baseUrl/chats/$id'), headers: _headers); + + if (response.statusCode == 200) { + final data = json.decode(response.body); + return _chatFromJson(data); + } else if (response.statusCode == 404) { + return null; + } else { + throw Exception('Failed to load chat: ${response.statusCode}'); + } + } + + @override + Future createChat(Chat chat, List messages) async { + final requestBody = { + 'title': chat.title, + 'createdAt': chat.createdAt.toIso8601String(), + 'updatedAt': chat.updatedAt.toIso8601String(), + 'messages': messages.map((m) => _messageToJson(m)).toList(), + }; + + final response = await http.post(Uri.parse('$baseUrl/chats'), headers: _headers, body: json.encode(requestBody)); + + if (response.statusCode == 201) { + final data = json.decode(response.body); + return _chatFromJson(data); + } else { + throw Exception('Failed to create chat: ${response.statusCode}'); + } + } + + @override + Future updateChat(Chat chat) async { + if (chat.id == null) throw ArgumentError('Chat ID cannot be null'); + + final requestBody = {'title': chat.title, 'updatedAt': chat.updatedAt.toIso8601String()}; + + final response = await http.put(Uri.parse('$baseUrl/chats/${chat.id}'), headers: _headers, body: json.encode(requestBody)); + + if (response.statusCode != 200) { + throw Exception('Failed to update chat: ${response.statusCode}'); + } + } + + @override + Future deleteChat(int id) async { + final response = await http.delete(Uri.parse('$baseUrl/chats/$id'), headers: _headers); + + if (response.statusCode != 200 && response.statusCode != 204) { + throw Exception('Failed to delete chat: ${response.statusCode}'); + } + } + + @override + Future addChatMessage(int chatId, List messages) async { + final requestBody = {'messages': messages.map((m) => _messageToJson(m)).toList()}; + + final response = await http.post(Uri.parse('$baseUrl/chats/$chatId/messages'), headers: _headers, body: json.encode(requestBody)); + + if (response.statusCode != 201) { + throw Exception('Failed to add messages: ${response.statusCode}'); + } + } + + @override + Future> getChatMessages(int chatId) async { + final response = await http.get(Uri.parse('$baseUrl/chats/$chatId/messages'), headers: _headers); + + if (response.statusCode == 200) { + final List data = json.decode(response.body); + return data.map((item) => _messageFromJson(item)).toList(); + } else { + throw Exception('Failed to load messages: ${response.statusCode}'); + } + } + + Chat _chatFromJson(Map json) { + return Chat(id: json['id'], title: json['title'], createdAt: DateTime.parse(json['createdAt']), updatedAt: DateTime.parse(json['updatedAt'])); + } + + Map _messageToJson(ChatMessage message) { + return { + 'messageId': message.messageId, + 'parentMessageId': message.parentMessageId, + 'content': message.content, + 'role': message.role.name, + 'name': message.name, + 'toolCallId': message.toolCallId, + }; + } + + ChatMessage _messageFromJson(Map json) { + return ChatMessage( + messageId: json['messageId'] ?? '', + parentMessageId: json['parentMessageId'] ?? '', + content: json['content'], + role: MessageRole.values.firstWhere((e) => e.name == json['role'], orElse: () => MessageRole.user), + name: json['name'], + toolCallId: json['toolCallId'], + ); + } +} diff --git a/lib/services/network_sync_service.dart b/lib/services/network_sync_service.dart new file mode 100644 index 0000000..e5f12c6 --- /dev/null +++ b/lib/services/network_sync_service.dart @@ -0,0 +1,502 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'package:dio/dio.dart' hide Response; +import 'package:shelf/shelf.dart'; +import 'package:shelf/shelf_io.dart' as io; +import 'package:shelf_router/shelf_router.dart'; +import 'package:shelf_cors_headers/shelf_cors_headers.dart'; +import 'package:network_info_plus/network_info_plus.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/dao/init_db.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:chatmcp/utils/platform.dart'; + +class NetworkSyncService { + static final NetworkSyncService _instance = NetworkSyncService._internal(); + factory NetworkSyncService() => _instance; + NetworkSyncService._internal(); + + HttpServer? _server; + int _port = 8080; + String? _ipAddress; + bool _isServerRunning = false; + + // Server state callback + Function(bool isRunning, String? address, int port)? onServerStateChanged; + + // Sync state callback + Function(String status, {bool isLoading, bool isSuccess, String? error})? onSyncStateChanged; + + bool get isServerRunning => _isServerRunning; + String? get serverAddress => _ipAddress; + int get serverPort => _port; + + /// Start HTTP server + Future startServer({int port = 8080}) async { + if (_isServerRunning) return; + + try { + _port = port; + _ipAddress = await _getLocalIPAddress(); + + final router = Router(); + + // Get device info + router.get('/info', _handleDeviceInfo); + + // Export data + router.get('/export', _handleExportData); + + // Import data + router.post('/import', _handleImportData); + + // Health check + router.get('/health', (Request request) { + return Response.ok(json.encode({'status': 'ok', 'timestamp': DateTime.now().toIso8601String(), 'device': Platform.operatingSystem})); + }); + + final handler = Pipeline().addMiddleware(corsHeaders()).addMiddleware(logRequests()).addHandler(router.call); + + _server = await io.serve(handler, InternetAddress.anyIPv4, _port); + _isServerRunning = true; + + Logger.root.info('HTTP sync server started: http://$_ipAddress:$_port'); + onServerStateChanged?.call(true, _ipAddress, _port); + } catch (e) { + Logger.root.severe('Failed to start server: $e'); + rethrow; + } + } + + /// Stop HTTP server + Future stopServer() async { + if (_server != null) { + await _server!.close(); + _server = null; + _isServerRunning = false; + Logger.root.info('HTTP sync server stopped'); + onServerStateChanged?.call(false, null, 0); + } + } + + /// Handle device info request + Future _handleDeviceInfo(Request request) async { + try { + final info = { + 'deviceName': Platform.localHostname, + 'platform': Platform.operatingSystem, + 'version': Platform.operatingSystemVersion, + 'timestamp': DateTime.now().toIso8601String(), + 'appName': 'ChatMcp', + 'serverUrl': 'http://$_ipAddress:$_port', + 'displayName': '${Platform.localHostname} (${Platform.operatingSystem})', + }; + + return Response.ok(json.encode(info), headers: {'Content-Type': 'application/json'}); + } catch (e) { + return Response.internalServerError(body: json.encode({'error': e.toString()})); + } + } + + /// Handle data export request + Future _handleExportData(Request request) async { + try { + final data = await _exportAllData(); + + return Response.ok( + json.encode(data), + headers: {'Content-Type': 'application/json', 'Content-Disposition': 'attachment; filename="chatmcp_backup.json"'}, + ); + } catch (e) { + Logger.root.severe('Failed to export data: $e'); + return Response.internalServerError(body: json.encode({'error': 'Failed to export data: ${e.toString()}'})); + } + } + + /// Handle data import request + Future _handleImportData(Request request) async { + try { + final body = await request.readAsString(); + final data = json.decode(body) as Map; + + await _importAllData(data); + + return Response.ok(json.encode({'success': true, 'message': 'Data imported successfully', 'timestamp': DateTime.now().toIso8601String()})); + } catch (e) { + Logger.root.severe('Failed to import data: $e'); + return Response.badRequest(body: json.encode({'error': 'Failed to import data: ${e.toString()}'})); + } + } + + /// Sync data from remote server + Future syncFromRemote(String serverUrl) async { + try { + onSyncStateChanged?.call('connectingToServer', isLoading: true); + + final dio = Dio(); + + // Check server health first + final healthResponse = await dio.get('$serverUrl/health'); + if (healthResponse.statusCode != 200) { + throw Exception('Failed to connect to server'); + } + + Logger.root.info('Connected to remote server: ${healthResponse.data}'); + onSyncStateChanged?.call('downloadingData', isLoading: true); + + // Get remote data + final exportResponse = await dio.get('$serverUrl/export'); + if (exportResponse.statusCode == 200) { + onSyncStateChanged?.call('importingData', isLoading: true); + await _importAllData(exportResponse.data); + + onSyncStateChanged?.call('reinitializingData', isLoading: true); + // Reinitialize Provider data + await _reinitializeProviders(); + + Logger.root.info('Successfully synced data from remote server'); + onSyncStateChanged?.call('dataSyncSuccess', isSuccess: true); + } else { + throw Exception('Failed to get remote data'); + } + } catch (e) { + Logger.root.severe('Failed to sync from remote server: $e'); + onSyncStateChanged?.call('syncFailed: $e', error: e.toString()); + rethrow; + } + } + + /// Push data to remote server + Future pushToRemote(String serverUrl) async { + try { + onSyncStateChanged?.call('preparingData', isLoading: true); + + final dio = Dio(); + final data = await _exportAllData(); + + onSyncStateChanged?.call('uploadingData', isLoading: true); + + final response = await dio.post( + '$serverUrl/import', + data: json.encode(data), + options: Options(headers: {'Content-Type': 'application/json'}), + ); + + if (response.statusCode == 200) { + Logger.root.info('Successfully pushed data to remote server'); + onSyncStateChanged?.call('dataPushSuccess', isSuccess: true); + } else { + throw Exception('Failed to push data: ${response.data}'); + } + } catch (e) { + Logger.root.severe('Failed to push data to remote server: $e'); + onSyncStateChanged?.call('pushFailed: $e', error: e.toString()); + rethrow; + } + } + + /// Reinitialize all Provider data + Future _reinitializeProviders() async { + try { + // Reload settings + await ProviderManager.settingsProvider.loadSettings(); + + // Reload chat data + await ProviderManager.chatProvider.loadChats(); + + // Reinitialize MCP servers + await ProviderManager.mcpServerProvider.init(); + await ProviderManager.mcpServerProvider.loadInMemoryServers(); + + Logger.root.info('Provider data reinitialization completed'); + } catch (e) { + Logger.root.warning('Failed to reinitialize Provider data: $e'); + } + } + + /// Discover sync servers in local network + Future> discoverServers({int timeoutSeconds = 3}) async { + final List servers = []; + final localIP = await _getLocalIPAddress(); + + if (localIP == null) return servers; + + // Get network segment (e.g.: 192.168.1.xxx) + final ipParts = localIP.split('.'); + if (ipParts.length != 4) return servers; + + final networkBase = '${ipParts[0]}.${ipParts[1]}.${ipParts[2]}'; + + Logger.root.info('Starting to scan local network: $networkBase.xxx'); + + // Simplified scan logic, only scan common IPs + final commonIPs = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110]; + + for (int i in commonIPs) { + final ip = '$networkBase.$i'; + if (ip == localIP) continue; // Skip local IP + + final isActive = await _checkServer(ip, _port, timeoutSeconds); + if (isActive) { + servers.add('http://$ip:$_port'); + Logger.root.info('Discovered sync server: $ip:$_port'); + } + } + + return servers; + } + + /// Check if specified IP is running sync server + Future _checkServer(String ip, int port, int timeoutSeconds) async { + try { + final dio = Dio(); + dio.options.connectTimeout = Duration(seconds: timeoutSeconds); + dio.options.receiveTimeout = Duration(seconds: timeoutSeconds); + + final response = await dio.get('http://$ip:$port/health'); + return response.statusCode == 200 && response.data['status'] == 'ok'; + } catch (e) { + return false; + } + } + + /// Get server device info + Future?> getServerInfo(String serverUrl) async { + try { + final dio = Dio(); + dio.options.connectTimeout = const Duration(seconds: 5); + dio.options.receiveTimeout = const Duration(seconds: 5); + + final response = await dio.get('$serverUrl/info'); + if (response.statusCode == 200) { + return response.data as Map; + } + } catch (e) { + Logger.root.warning('Failed to get server info: $e'); + } + return null; + } + + /// Get local IP address + Future _getLocalIPAddress() async { + try { + final info = NetworkInfo(); + return await info.getWifiIP(); + } catch (e) { + Logger.root.warning('Failed to get IP address: $e'); + return null; + } + } + + /// Export all data + Future> _exportAllData() async { + final db = await DatabaseHelper.instance.database; + final prefs = await SharedPreferences.getInstance(); + + // Export database data + final chatData = await db.query('chat'); + final messageData = await db.query('chat_message'); + + // Export settings + final settings = {}; + for (String key in prefs.getKeys()) { + final value = prefs.get(key); + settings[key] = value; + } + + // Export MCP server config + Map? mcpConfig; + try { + final provider = ProviderManager.mcpServerProvider; + mcpConfig = await provider.loadServersAll(); + } catch (e) { + Logger.root.warning('Failed to export MCP config: $e'); + } + + return { + 'version': '1.0', + 'timestamp': DateTime.now().toIso8601String(), + 'device': {'name': Platform.localHostname, 'platform': Platform.operatingSystem}, + 'chat': chatData, + 'chat_message': messageData, + 'settings': settings, + 'mcp_config': mcpConfig, + }; + } + + /// Import all data + Future _importAllData(Map data) async { + final db = await DatabaseHelper.instance.database; + final prefs = await SharedPreferences.getInstance(); + + try { + await db.transaction((txn) async { + // Import chat data + if (data['chat'] != null) { + for (var chat in data['chat']) { + try { + await txn.insert('chat', chat, conflictAlgorithm: ConflictAlgorithm.replace); + } catch (e) { + // If fields don't match, try to insert only compatible fields + Logger.root.warning('Failed to insert chat with full schema, trying compatible fields: $e'); + final compatibleChat = { + 'id': chat['id'], + 'title': chat['title'], + 'createdAt': chat['createdAt'], + 'updatedAt': chat['updatedAt'], + }; + // Only add model field if it exists + if (chat.containsKey('model')) { + compatibleChat['model'] = chat['model']; + } + await txn.insert('chat', compatibleChat, conflictAlgorithm: ConflictAlgorithm.replace); + } + } + } + + // Import message data + if (data['chat_message'] != null) { + for (var message in data['chat_message']) { + await txn.insert('chat_message', message, conflictAlgorithm: ConflictAlgorithm.replace); + } + } + }); + + // Import settings + if (data['settings'] != null) { + final settings = data['settings'] as Map; + for (var entry in settings.entries) { + if (entry.value is String) { + await prefs.setString(entry.key, entry.value); + } else if (entry.value is int) { + await prefs.setInt(entry.key, entry.value); + } else if (entry.value is double) { + await prefs.setDouble(entry.key, entry.value); + } else if (entry.value is bool) { + await prefs.setBool(entry.key, entry.value); + } else if (entry.value is List) { + await prefs.setStringList(entry.key, entry.value); + } + } + } + + // Import MCP config + if (data['mcp_config'] != null) { + Map? mcpConfig = data['mcp_config']; + + // 如果当前是移动端,过滤掉stdio格式的MCP server + if (kIsMobile && mcpConfig != null && mcpConfig['mcpServers'] != null) { + final servers = mcpConfig['mcpServers'] as Map; + final filteredServers = {}; + + for (var entry in servers.entries) { + final serverConfig = entry.value as Map; + final serverType = serverConfig['type'] as String? ?? ''; + + // 跳过stdio类型的服务器 + if (serverType != 'stdio') { + filteredServers[entry.key] = entry.value; + } else { + Logger.root.info('Filtered out stdio MCP server: ${entry.key} (mobile platform)'); + } + } + + mcpConfig['mcpServers'] = filteredServers; + } + + final provider = ProviderManager.mcpServerProvider; + await provider.saveServers(mcpConfig!); + } + } catch (e) { + Logger.root.severe('Failed to import data: $e'); + rethrow; + } + } +} + +/// Connection history model +class SyncServerHistory { + final String url; + final String deviceName; + final String platform; + final DateTime lastConnected; + final String displayName; + + SyncServerHistory({required this.url, required this.deviceName, required this.platform, required this.lastConnected, required this.displayName}); + + Map toJson() { + return {'url': url, 'deviceName': deviceName, 'platform': platform, 'lastConnected': lastConnected.toIso8601String(), 'displayName': displayName}; + } + + factory SyncServerHistory.fromJson(Map json) { + return SyncServerHistory( + url: json['url'] ?? '', + deviceName: json['deviceName'] ?? '', + platform: json['platform'] ?? '', + lastConnected: DateTime.tryParse(json['lastConnected'] ?? '') ?? DateTime.now(), + displayName: json['displayName'] ?? '', + ); + } +} + +/// Connection history manager +class SyncHistoryManager { + static const String _historyKey = 'sync_server_history'; + static const int _maxHistoryCount = 10; + + /// Save connection history + static Future saveHistory(SyncServerHistory history) async { + final prefs = await SharedPreferences.getInstance(); + final histories = await getHistories(); + + // Remove old records with same URL + histories.removeWhere((h) => h.url == history.url); + + // Add new record to the beginning + histories.insert(0, history); + + // Limit history count + if (histories.length > _maxHistoryCount) { + histories.removeRange(_maxHistoryCount, histories.length); + } + + // Save to SharedPreferences + final jsonList = histories.map((h) => h.toJson()).toList(); + await prefs.setString(_historyKey, json.encode(jsonList)); + } + + /// Get connection history + static Future> getHistories() async { + final prefs = await SharedPreferences.getInstance(); + final historyJson = prefs.getString(_historyKey); + + if (historyJson == null) return []; + + try { + final List jsonList = json.decode(historyJson); + return jsonList.map((json) => SyncServerHistory.fromJson(json)).toList(); + } catch (e) { + Logger.root.warning('Failed to parse connection history: $e'); + return []; + } + } + + /// Remove connection history + static Future removeHistory(String url) async { + final histories = await getHistories(); + histories.removeWhere((h) => h.url == url); + + final prefs = await SharedPreferences.getInstance(); + final jsonList = histories.map((h) => h.toJson()).toList(); + await prefs.setString(_historyKey, json.encode(jsonList)); + } + + /// Clear all history + static Future clearHistory() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_historyKey); + } +} diff --git a/lib/utils/README.md b/lib/utils/README.md new file mode 100644 index 0000000..b4b2a72 --- /dev/null +++ b/lib/utils/README.md @@ -0,0 +1,83 @@ +# Utils 工具类 + +## ToastUtils - Toast 通知工具 + +ToastUtils 提供了统一的 toast 通知功能,支持不同级别的消息提示。 + +### 使用方法 + +``` +import '../utils/toast.dart'; + +// 错误级别 - 红色背景,持续 5 秒 +ToastUtils.error('操作失败,请重试'); + +// 警告级别 - 橙色背景,持续 4 秒 +ToastUtils.warn('网络连接不稳定'); + +// 信息级别 - 蓝色背景,持续 3 秒 +ToastUtils.info('正在处理您的请求'); + +// 成功级别 - 绿色背景,持续 3 秒 +ToastUtils.success('操作成功完成'); + +// 自定义样式 +ToastUtils.custom( + message: '自定义消息', + color: Colors.purple, + duration: Duration(seconds: 2), +); +``` + +### 方法说明 + +#### error(String message, {Duration? duration}) +- **用途**: 显示错误信息 +- **颜色**: 红色 (Colors.red.shade600) +- **默认持续时间**: 5 秒 +- **使用场景**: 操作失败、系统错误、验证失败等 + +#### warn(String message, {Duration? duration}) +- **用途**: 显示警告信息 +- **颜色**: 橙色 (Colors.orange.shade600) +- **默认持续时间**: 4 秒 +- **使用场景**: 网络问题、权限不足、配置问题等 + +#### info(String message, {Duration? duration}) +- **用途**: 显示一般信息 +- **颜色**: 蓝色 (Colors.blue.shade600) +- **默认持续时间**: 3 秒 +- **使用场景**: 状态更新、提示信息、进度通知等 + +#### success(String message, {Duration? duration}) +- **用途**: 显示成功信息 +- **颜色**: 绿色 (Colors.green.shade600) +- **默认持续时间**: 3 秒 +- **使用场景**: 操作成功、保存完成、连接成功等 + +#### custom({required String message, required Color color, Duration? duration, Alignment? align, TextStyle? textStyle}) +- **用途**: 显示自定义样式的 toast +- **参数**: 完全自定义所有样式属性 +- **使用场景**: 需要特殊样式的场合 + +### 特性 + +- 🎨 **颜色编码**: 不同级别使用不同颜色,便于用户快速识别 +- ⏱️ **智能持续时间**: 根据消息重要性自动调整显示时间 +- 📱 **响应式设计**: 自动适配不同屏幕尺寸 +- 🔧 **高度可定制**: 支持自定义样式和行为 +- 🌍 **国际化友好**: 支持中文和其他语言 + +### 注意事项 + +1. 确保在 `main.dart` 中已正确配置 BotToast +2. 所有 toast 默认显示在屏幕顶部中央,距离顶部边缘有适当间距 +3. 文字样式统一为白色,字体大小 14px,中等粗细 +4. 建议根据消息重要性选择合适的级别 + +### 位置说明 + +Toast 通知使用 `Alignment(0.0, -0.8)` 定位: +- `0.0` 表示水平居中 +- `-0.8` 表示垂直方向靠近顶部,但保持适当距离 +- 这样既不会被状态栏遮挡,也不会紧贴屏幕边缘 \ No newline at end of file diff --git a/lib/utils/color.dart b/lib/utils/color.dart new file mode 100644 index 0000000..5fa0926 --- /dev/null +++ b/lib/utils/color.dart @@ -0,0 +1,277 @@ +import 'package:flutter/material.dart'; + +class AppColors { + static const Color white = Colors.white; + static const MaterialColor grey = Colors.grey; + static const Color black = Colors.black; + static const MaterialColor green = Colors.green; + static const MaterialColor red = Colors.red; + static const MaterialColor blue = Colors.blue; + static const Color transparent = Colors.transparent; + + /// Returns the corresponding color based on the theme + static Color getThemeColor(BuildContext context, {Color? lightColor, Color? darkColor}) { + final brightness = Theme.of(context).brightness; + return brightness == Brightness.light ? (lightColor ?? black) : (darkColor ?? white); + } + + /// Gets the background color related to the theme + static Color getThemeBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: grey[200], darkColor: grey[800]); + } + + static Color getThemeTextColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.black87, darkColor: Colors.white); + } + + static Color getLayoutBackgroundColor(BuildContext context) { + return getThemeColor( + context, + lightColor: Colors.white, + darkColor: const Color(0xFF1E1E1E), // 修复Linux透明度问题,使用实心背景 + ); + } + + static Color getSidebarBackgroundColor(BuildContext context) { + return getThemeColor( + context, + lightColor: Colors.grey[200], + darkColor: Colors.grey[850], // 侧边栏使用更深的颜色以区分主区域 + ); + } + + static Color getSidebarActiveConversationColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[300], darkColor: AppColors.grey[700]); + } + + static Color getToolbarBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[100], darkColor: AppColors.grey[900]); + } + + static Color getTextButtonColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.blue[300], darkColor: AppColors.blue[100]); + } + + static Color getCodeTabActiveColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.blue[300], darkColor: AppColors.blue[300]); + } + + static Color getCodeTabInactiveColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.blue[100], darkColor: AppColors.blue[100]); + } + + static Color getCodePreviewBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[200], darkColor: AppColors.grey[800]); + } + + static Color getCodeLanguageTextColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[600], darkColor: AppColors.grey[300]); + } + + static Color getInactiveTextColor(BuildContext context) { + return AppColors.grey[600]!; + } + + static Color getMessageBranchDisabledColor() { + return AppColors.grey[400]!; + } + + static Color getMessageBranchIndicatorTextColor() { + return AppColors.grey[600]!; + } + + // file attachment related colors + static Color getFileAttachmentBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[200], darkColor: AppColors.grey[800]); + } + + // image error icon color + static Color getImageErrorIconColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[600], darkColor: AppColors.grey[400]); + } + + // message bubble background color + static Color getMessageBubbleBackgroundColor(BuildContext context, bool isUserMessage) { + return getThemeColor( + context, + lightColor: AppColors.grey[100], + darkColor: const Color(0xFF2D2D2D), // 深色主题下使用更明显的背景色 + ); + } + + // tool call and tool result text color + static Color getToolCallTextColor() { + return AppColors.grey[600]!; + } + + // chat avatar background color + static Color getChatAvatarBackgroundColor() { + return AppColors.grey; + } + + // chat avatar icon color + static Color getChatAvatarIconColor() { + return AppColors.white; + } + + // welcome message text color + static Color getWelcomeMessageColor() { + return AppColors.grey; + } + + // error hint icon color + static Color getErrorIconColor() { + return AppColors.red; + } + + // error hint text color + static Color getErrorTextColor() { + return AppColors.red; + } + + // bottom menu slider color + static Color getBottomSheetHandleColor(BuildContext context) { + return AppColors.grey.withAlpha(77); + } + + // toolbar bottom border color + static Color getToolbarBottomBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[200], darkColor: AppColors.grey[800]); + } + + // sidebar toggle icon color + static Color getSidebarToggleIconColor() { + return AppColors.grey[700]!; + } + + // markdown related colors + + // artifact component background color + static Color getArtifactBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey[50], darkColor: Colors.grey[800]); + } + + // artifact component border color + static Color getArtifactBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey[300], darkColor: Colors.grey[700]); + } + + // progress indicator color + static Color getProgressIndicatorColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.orange, darkColor: Colors.orange); + } + + // think component background color + static Color getThinkBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[300], darkColor: AppColors.grey[700]); + } + + // think component border color + static Color getThinkBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[200], darkColor: AppColors.grey[700]); + } + + // think icon color + static Color getThinkIconColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.orange, darkColor: Colors.orange); + } + + // think text color + static Color getThinkTextColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[500], darkColor: AppColors.grey[300]); + } + + // expand/collapse icon color + static Color getExpandIconColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[600], darkColor: AppColors.grey[300]); + } + + // function component background color + static Color getFunctionBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[100], darkColor: AppColors.grey[900]); + } + + // function component border color + static Color getFunctionBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[300], darkColor: AppColors.grey[700]); + } + + // function icon color + static Color getFunctionIconColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.orange[200], darkColor: Colors.orange[300]); + } + + // function text color + static Color getFunctionTextColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[500], darkColor: AppColors.grey[300]); + } + + // run button color + static Color getPlayButtonColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.green, darkColor: Colors.green[300]); + } + + // code block toolbar background color + static Color getCodeBlockToolbarBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[300], darkColor: AppColors.grey[900]); + } + + // code block language text color + static Color getCodeBlockLanguageTextColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[700], darkColor: AppColors.grey[300]); + } + + // code preview button background color + static Color getCodePreviewButtonBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: AppColors.grey[100], darkColor: AppColors.grey[900]); + } + + // link color + static Color getLinkColor() { + return Colors.blue; + } + + // input area related colors + static Color getInputAreaBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.white, darkColor: Colors.grey.shade900); + } + + static Color getInputAreaBorderColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade300, darkColor: Colors.grey.shade700); + } + + static Color getInputAreaFileItemBackgroundColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade200, darkColor: Colors.grey.shade800.withAlpha(100)); + } + + static Color getInputAreaHintTextColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade600, darkColor: Colors.grey.shade400); + } + + static Color getInputAreaTextColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.black87, darkColor: Colors.white); + } + + static Color getInputAreaIconColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade600, darkColor: Colors.grey.shade400); + } + + static Color getInputAreaFileIconColor(BuildContext context) { + return Theme.of(context).primaryColor.withAlpha(204); + } + + // InkIcon related colors + static Color getInkIconHoverColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade200, darkColor: Colors.grey.shade700); + } + + // chat loading related colors + static Color getChatLoadingColor(BuildContext context) { + return getThemeColor(context, lightColor: Theme.of(context).primaryColor, darkColor: Colors.white.withAlpha(50)); + } + + // input area cursor color + static Color getInputAreaCursorColor(BuildContext context) { + return getThemeColor(context, lightColor: Colors.grey.shade400, darkColor: Colors.grey.shade400); + } +} diff --git a/lib/utils/event_bus.dart b/lib/utils/event_bus.dart new file mode 100644 index 0000000..e931e28 --- /dev/null +++ b/lib/utils/event_bus.dart @@ -0,0 +1,52 @@ +import 'dart:async'; + +import 'package:event_bus/event_bus.dart'; + +class CodePreviewEvent { + final String hash; + final String textContent; + final Map attributes; + + const CodePreviewEvent(this.hash, this.textContent, this.attributes); +} + +class ToggleCodePreviewEvent { + final bool showCodePreview; + + const ToggleCodePreviewEvent(this.showCodePreview); +} + +class ShareEvent { + final bool share; + + const ShareEvent(this.share); +} + +class RunFunctionEvent { + final String name; + final Map arguments; + + const RunFunctionEvent(this.name, this.arguments); +} + +class ToolCallResultEvent { + final String toolName; + final String result; + + const ToolCallResultEvent(this.toolName, this.result); +} + +/// The global [EventBus] object. +EventBus eventBus = EventBus(); + +Future emit(T data) async { + eventBus.fire(data); +} + +StreamSubscription on(Function(T) callback) { + StreamSubscription loginSubscription = eventBus.on().listen((data) { + callback(data); + }); + + return loginSubscription; +} diff --git a/lib/utils/file_content.dart b/lib/utils/file_content.dart new file mode 100644 index 0000000..347e627 --- /dev/null +++ b/lib/utils/file_content.dart @@ -0,0 +1,170 @@ +import 'dart:io' as io; +import 'dart:convert'; +import 'package:flutter/material.dart'; +import 'package:mime/mime.dart'; +import "package:chatmcp/llm/model.dart"; +import 'package:file_picker/file_picker.dart'; + +File platformFileToFile(PlatformFile platformFile) { + final fileType = lookupMimeType(platformFile.name) ?? platformFile.extension ?? ''; + + if (fileType.startsWith('image/')) { + List fileBytes; + if (platformFile.bytes != null) { + fileBytes = platformFile.bytes!; + } else { + fileBytes = io.File(platformFile.path!).readAsBytesSync(); + } + + return File( + name: platformFile.name, + path: platformFile.path, + size: platformFile.size, + fileType: fileType, + fileContent: base64Encode(fileBytes), + // fileContent: "data:$fileType;base64,${base64Encode(fileBytes)}", + ); + } + + debugPrint('fileType: $fileType'); + + // 判断是否为文本类型文件 + bool isTextFile = + fileType.startsWith('text/') || + fileType.startsWith('application/') && + (fileType.contains('json') || + fileType.contains('javascript') || + fileType.contains('xml') || + fileType.contains('yaml') || + fileType.contains('x-yaml') || + fileType.contains('toml') || + fileType.contains('markdown') || + fileType.contains('x-httpd-php') || + fileType.contains('x-sh') || + fileType.contains('x-python')); + + if (isTextFile) { + List fileBytes; + if (platformFile.bytes != null) { + fileBytes = platformFile.bytes!; + } else { + fileBytes = io.File(platformFile.path!).readAsBytesSync(); + } + return File(name: platformFile.name, path: platformFile.path, size: platformFile.size, fileType: fileType, fileContent: utf8.decode(fileBytes)); + } + + return File(name: platformFile.name, path: platformFile.path, size: platformFile.size, fileType: fileType, fileContent: ''); +} + +bool isTextFile(String fileType) { + return fileType.startsWith('text/') || + fileType.startsWith('application/') && + (fileType.contains('json') || + fileType.contains('javascript') || + fileType.contains('xml') || + fileType.contains('yaml') || + fileType.contains('x-yaml') || + fileType.contains('toml') || + fileType.contains('markdown') || + fileType.contains('x-httpd-php') || + fileType.contains('x-sh') || + fileType.contains('x-python')) || + // 常见文本文件类型 + fileType == 'json' || + fileType == 'javascript' || + fileType == 'xml' || + fileType == 'yaml' || + fileType == 'toml' || + fileType == 'markdown' || + fileType == 'md' || + fileType == 'txt' || + fileType == 'php' || + fileType == 'sh' || + fileType == 'py' || + fileType == 'js' || + fileType == 'ts' || + fileType == 'html' || + fileType == 'css' || + fileType == 'scss' || + fileType == 'less' || + fileType == 'dart' || + // 编程语言 + fileType == 'java' || + fileType == 'c' || + fileType == 'cpp' || + fileType == 'cc' || + fileType == 'h' || + fileType == 'hpp' || + fileType == 'cs' || + fileType == 'go' || + fileType == 'rb' || + fileType == 'rs' || + fileType == 'swift' || + fileType == 'kt' || + fileType == 'jsx' || + fileType == 'tsx' || + fileType == 'd.ts' || + fileType == 'phtml' || + fileType == 'sql' || + fileType == 'bash' || + fileType == 'zsh' || + fileType == 'vue' || + fileType == 'svelte' || + fileType == 'graphql' || + fileType == 'gql' || + fileType == 'proto' || + fileType == 'sol' || + fileType == 'lua' || + fileType == 'ex' || + fileType == 'exs' || + fileType == 'erl' || + fileType == 'hrl' || + fileType == 'clj' || + fileType == 'scala' || + fileType == 'pl' || + fileType == 'pm' || + fileType == 'r' || + fileType == 'rmd' || + // 配置文件 + fileType == 'env' || + fileType == 'ini' || + fileType == 'conf' || + fileType == 'config' || + fileType == 'dockerfile' || + fileType == 'dockerignore' || + fileType == 'gitignore' || + fileType == 'gitconfig' || + fileType == 'editorconfig' || + fileType == 'prettierrc' || + fileType == 'eslintrc' || + fileType == 'babelrc' || + fileType == 'npmrc' || + fileType == 'properties' || + // 文档和标记语言 + fileType == 'adoc' || + fileType == 'rst' || + fileType == 'tex' || + fileType == 'rtf' || + fileType == 'wiki' || + fileType == 'org' || + // 数据文件 + fileType == 'csv' || + fileType == 'tsv' || + fileType == 'svg' || + fileType == 'wat' || + fileType == 'wasm' || + fileType == 'log' || + // 其他常见纯文本文件 + fileType == 'lock' || + fileType == 'license' || + fileType == 'makefile' || + fileType == 'cmake' || + fileType == 'csproj' || + fileType == 'sln' || + fileType == 'gradle' || + fileType == 'pom'; +} + +bool isImageFile(String fileType) { + return fileType.startsWith('image/'); +} diff --git a/lib/utils/inappview.dart b/lib/utils/inappview.dart new file mode 100644 index 0000000..66d8f05 --- /dev/null +++ b/lib/utils/inappview.dart @@ -0,0 +1,17 @@ +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:flutter/foundation.dart'; + +WebViewEnvironment? webViewEnvironment; + +Future configureWebViewDebugging() async { + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { + await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode); + } + + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) { + final availableVersion = await WebViewEnvironment.getAvailableVersion(); + assert(availableVersion != null, 'Failed to find an installed WebView2 Runtime or non-stable Microsoft Edge installation.'); + + webViewEnvironment = await WebViewEnvironment.create(settings: WebViewEnvironmentSettings(userDataFolder: 'YOUR_CUSTOM_PATH')); + } +} diff --git a/lib/utils/init.dart b/lib/utils/init.dart new file mode 100644 index 0000000..fa203b1 --- /dev/null +++ b/lib/utils/init.dart @@ -0,0 +1 @@ +export 'init_stub.dart' if (dart.library.io) 'init_io.dart'; diff --git a/lib/utils/init_io.dart b/lib/utils/init_io.dart new file mode 100644 index 0000000..2d6dac3 --- /dev/null +++ b/lib/utils/init_io.dart @@ -0,0 +1,30 @@ +import 'dart:io'; + +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:logging/logging.dart'; + +import 'platform.dart'; + +Future initNonWeb() async { + if (kIsWeb) { + return; + } + + // Get an available port + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = server.port; + await server.close(); + + if (!kIsDesktop) { + final InAppLocalhostServer localhostServer = InAppLocalhostServer(documentRoot: 'assets/sandbox', port: port); + + ProviderManager.settingsProvider.updateSandboxServerPort(port: port); + + // start the localhost server + await localhostServer.start(); + + Logger.root.info('Sandbox server started @ http://localhost:$port'); + } +} diff --git a/lib/utils/init_stub.dart b/lib/utils/init_stub.dart new file mode 100644 index 0000000..ff3d3e8 --- /dev/null +++ b/lib/utils/init_stub.dart @@ -0,0 +1,3 @@ +Future initNonWeb() async { + // Do nothing on the web. +} diff --git a/lib/utils/modal.dart b/lib/utils/modal.dart new file mode 100644 index 0000000..b5aaa09 --- /dev/null +++ b/lib/utils/modal.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; + +void showModalBottom(BuildContext context, Widget child) { + showModalBottomSheet( + context: context, + isScrollControlled: true, // Allows the modal content to exceed half the screen height + builder: (BuildContext context) { + return DraggableScrollableSheet( + initialChildSize: 0.6, // Initial height is 60% of the screen + minChildSize: 0.3, // Minimum height is 30% of the screen + maxChildSize: 0.9, // Maximum height is 90% of the screen + expand: false, + builder: (context, scrollController) { + return child; + }, + ); + }, + ); +} diff --git a/lib/utils/oauth_discovery.dart b/lib/utils/oauth_discovery.dart new file mode 100644 index 0000000..73657f5 --- /dev/null +++ b/lib/utils/oauth_discovery.dart @@ -0,0 +1,271 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:logging/logging.dart'; + +/// Result of OAuth discovery for an MCP server +class OAuthDiscoveryResult { + /// Whether the server requires OAuth authentication + final bool requiresOAuth; + + /// OAuth authorization endpoint URL + final String? authorizationUrl; + + /// OAuth token endpoint URL + final String? tokenUrl; + + /// OAuth client ID (may be null for public clients) + final String? clientId; + + /// OAuth scope string + final String? scope; + + /// OAuth redirect URI + final String? redirectUri; + + const OAuthDiscoveryResult({ + required this.requiresOAuth, + this.authorizationUrl, + this.tokenUrl, + this.clientId, + this.scope, + this.redirectUri, + }); +} + +/// Service for automatically discovering OAuth configuration from MCP servers +/// +/// Implements RFC 8414 (OAuth 2.0 Authorization Server Metadata) and RFC 7591 +/// (OAuth 2.0 Dynamic Client Registration) for automatic OAuth discovery. +class OAuthDiscoveryService { + static final Logger _logger = Logger('OAuthDiscoveryService'); + + /// Automatically discovers OAuth configuration for an MCP server URL + static Future discoverOAuth(String serverUrl) async { + try { + _logger.info('Discovering OAuth configuration for: $serverUrl'); + + final baseUri = Uri.parse(serverUrl); + final baseUrl = '${baseUri.scheme}://${baseUri.host}:${baseUri.port}'; + + // Try multiple discovery methods + var result = await _tryWellKnownEndpoint(baseUrl); + if (result.requiresOAuth) return result; + + result = await _tryDirectServerProbe(serverUrl); + if (result.requiresOAuth) return result; + + result = await _tryOAuthMetadataEndpoint(baseUrl); + if (result.requiresOAuth) return result; + + // No OAuth required + return OAuthDiscoveryResult(requiresOAuth: false); + + } catch (e) { + _logger.warning('OAuth discovery failed: $e'); + return OAuthDiscoveryResult(requiresOAuth: false); + } + } + + /// Try RFC 8414 OAuth 2.0 Authorization Server Metadata + static Future _tryWellKnownEndpoint(String baseUrl) async { + try { + final wellKnownUrl = '$baseUrl/.well-known/oauth-authorization-server'; + _logger.info('Trying well-known endpoint: $wellKnownUrl'); + + final response = await http.get( + Uri.parse(wellKnownUrl), + headers: {'Accept': 'application/json'}, + ).timeout(const Duration(seconds: 5)); + + if (response.statusCode == 200) { + final metadata = json.decode(response.body) as Map; + + final authorizationEndpoint = metadata['authorization_endpoint'] as String?; + final tokenEndpoint = metadata['token_endpoint'] as String?; + + if (authorizationEndpoint != null && tokenEndpoint != null) { + _logger.info('Found OAuth metadata via well-known endpoint'); + + // Check if dynamic client registration is available + final registrationEndpoint = metadata['registration_endpoint'] as String?; + String? clientId = metadata['client_id'] as String?; + + // For servers like Notion that support dynamic registration and public clients, + // we'll try to register a client dynamically if no client_id is provided + if (clientId == null && registrationEndpoint != null) { + clientId = await _tryDynamicClientRegistration(registrationEndpoint); + } + + return OAuthDiscoveryResult( + requiresOAuth: true, + authorizationUrl: authorizationEndpoint, + tokenUrl: tokenEndpoint, + clientId: clientId, // May be null for public clients + scope: metadata['scope'] as String? ?? 'read write', + redirectUri: _generateRedirectUri(), + ); + } + } + } catch (e) { + _logger.fine('Well-known endpoint not available: $e'); + } + + return OAuthDiscoveryResult(requiresOAuth: false); + } + + /// Try probing the MCP server directly for OAuth requirements + static Future _tryDirectServerProbe(String serverUrl) async { + try { + _logger.info('Probing MCP server directly: $serverUrl'); + + // For SSE endpoints, try connecting and check for auth requirements + if (serverUrl.contains('/sse') || serverUrl.contains('/mcp')) { + final response = await http.get( + Uri.parse(serverUrl), + headers: {'Accept': 'text/event-stream'}, + ).timeout(const Duration(seconds: 5)); + + // Check for OAuth challenge in response headers or body + final authHeader = response.headers['www-authenticate']; + if (authHeader != null && authHeader.toLowerCase().contains('bearer')) { + _logger.info('Server requires OAuth authentication'); + + // Try to extract OAuth endpoints from response headers or body + final authEndpoint = response.headers['x-oauth-authorization-url']; + final tokenEndpoint = response.headers['x-oauth-token-url']; + + if (authEndpoint != null && tokenEndpoint != null) { + return OAuthDiscoveryResult( + requiresOAuth: true, + authorizationUrl: authEndpoint, + tokenUrl: tokenEndpoint, + clientId: response.headers['x-oauth-client-id'], + scope: response.headers['x-oauth-scope'] ?? 'read write', + redirectUri: _generateRedirectUri(), + ); + } + } + + // Check for 401 Unauthorized response + if (response.statusCode == 401) { + _logger.info('Server returned 401, may require OAuth'); + + // Try to parse OAuth challenge from response body + try { + final body = response.body; + if (body.contains('oauth') || body.contains('authorization')) { + final bodyJson = json.decode(body) as Map?; + if (bodyJson != null) { + final authUrl = bodyJson['authorization_url'] as String?; + final tokenUrl = bodyJson['token_url'] as String?; + + if (authUrl != null && tokenUrl != null) { + return OAuthDiscoveryResult( + requiresOAuth: true, + authorizationUrl: authUrl, + tokenUrl: tokenUrl, + clientId: bodyJson['client_id'] as String?, + scope: bodyJson['scope'] as String? ?? 'read write', + redirectUri: _generateRedirectUri(), + ); + } + } + } + } catch (e) { + _logger.fine('Could not parse OAuth info from response body: $e'); + } + } + } + } catch (e) { + _logger.fine('Direct server probe failed: $e'); + } + + return OAuthDiscoveryResult(requiresOAuth: false); + } + + /// Try OAuth metadata endpoint + static Future _tryOAuthMetadataEndpoint(String baseUrl) async { + try { + final metadataUrl = '$baseUrl/oauth/metadata'; + _logger.info('Trying OAuth metadata endpoint: $metadataUrl'); + + final response = await http.get( + Uri.parse(metadataUrl), + headers: {'Accept': 'application/json'}, + ).timeout(const Duration(seconds: 5)); + + if (response.statusCode == 200) { + final metadata = json.decode(response.body) as Map; + + final authUrl = metadata['authorization_url'] as String?; + final tokenUrl = metadata['token_url'] as String?; + + if (authUrl != null && tokenUrl != null) { + _logger.info('Found OAuth metadata via /oauth/metadata endpoint'); + + return OAuthDiscoveryResult( + requiresOAuth: true, + authorizationUrl: authUrl, + tokenUrl: tokenUrl, + clientId: metadata['client_id'] as String?, + scope: metadata['scope'] as String? ?? 'read write', + redirectUri: _generateRedirectUri(), + ); + } + } + } catch (e) { + _logger.fine('OAuth metadata endpoint not available: $e'); + } + + return OAuthDiscoveryResult(requiresOAuth: false); + } + + /// Generate appropriate redirect URI for current platform + static String _generateRedirectUri() { + // Get current page URL and construct redirect URI + final currentUrl = Uri.base; + return '${currentUrl.origin}/oauth_callback.html'; + } + + /// Try dynamic client registration (RFC 7591) + static Future _tryDynamicClientRegistration(String registrationEndpoint) async { + try { + _logger.info('Attempting dynamic client registration at: $registrationEndpoint'); + + final clientMetadata = { + 'client_name': 'ChatMCP Client', + 'redirect_uris': [_generateRedirectUri()], + 'grant_types': ['authorization_code', 'refresh_token'], + 'response_types': ['code'], + 'token_endpoint_auth_method': 'none', // Public client + 'application_type': 'web', + 'scope': 'read write', + }; + + final response = await http.post( + Uri.parse(registrationEndpoint), + headers: { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + }, + body: json.encode(clientMetadata), + ).timeout(const Duration(seconds: 10)); + + if (response.statusCode == 200 || response.statusCode == 201) { + final registrationResponse = json.decode(response.body) as Map; + final clientId = registrationResponse['client_id'] as String?; + + if (clientId != null) { + _logger.info('Dynamic client registration successful, client_id: $clientId'); + return clientId; + } + } else { + _logger.warning('Dynamic client registration failed: ${response.statusCode} - ${response.body}'); + } + } catch (e) { + _logger.warning('Dynamic client registration error: $e'); + } + + return null; + } +} diff --git a/lib/utils/oauth_stub.dart b/lib/utils/oauth_stub.dart new file mode 100644 index 0000000..a35586c --- /dev/null +++ b/lib/utils/oauth_stub.dart @@ -0,0 +1,32 @@ +// Stub for non-web platforms +class WebOAuthHandler { + static Future> startOAuthFlow({ + required String authorizationUrl, + String? clientId, + required String redirectUri, + required String scope, + String? state, + }) async { + throw UnsupportedError('OAuth is only supported on web platform'); + } + + static Future> exchangeCodeForToken({ + required String tokenUrl, + String? clientId, + String? clientSecret, + required String code, + required String codeVerifier, + required String redirectUri, + }) async { + throw UnsupportedError('OAuth is only supported on web platform'); + } + + static Future> refreshToken({ + required String tokenUrl, + String? clientId, + String? clientSecret, + required String refreshToken, + }) async { + throw UnsupportedError('OAuth is only supported on web platform'); + } +} diff --git a/lib/utils/oauth_web.dart b/lib/utils/oauth_web.dart new file mode 100644 index 0000000..5f58f9b --- /dev/null +++ b/lib/utils/oauth_web.dart @@ -0,0 +1,362 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:html' as html; +import 'dart:math'; +import 'package:crypto/crypto.dart'; +import 'package:logging/logging.dart'; +import 'package:http/http.dart' as http; + +/// Web-based OAuth 2.0 + PKCE handler for MCP servers +/// +/// Handles OAuth authorization flows in web environments using popup windows +/// and cross-origin messaging. Supports both public clients (no client_id) +/// and confidential clients with PKCE (RFC 7636) for security. +class WebOAuthHandler { + static const String _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; + static final Random _rng = Random(); + + /// Generates a random string for PKCE code verifier + static String _generateRandomString(int length) { + return String.fromCharCodes( + Iterable.generate(length, (_) => _chars.codeUnitAt(_rng.nextInt(_chars.length))), + ); + } + + /// Generates PKCE code challenge from verifier + static String _generateCodeChallenge(String codeVerifier) { + final bytes = utf8.encode(codeVerifier); + final digest = sha256.convert(bytes); + return base64Url.encode(digest.bytes).replaceAll('=', ''); + } + + /// Starts OAuth flow with Authorization Code + PKCE + static Future> startOAuthFlow({ + required String authorizationUrl, + String? clientId, // Made nullable for public clients + required String redirectUri, + required String scope, + String? state, + }) async { + try { + // Debug log the parameters + Logger.root.info('OAuth Parameters:'); + Logger.root.info(' authorizationUrl: $authorizationUrl'); + Logger.root.info(' clientId: $clientId'); + Logger.root.info(' redirectUri: $redirectUri'); + Logger.root.info(' scope: $scope'); + + // Generate PKCE parameters + final codeVerifier = _generateRandomString(128); + final codeChallenge = _generateCodeChallenge(codeVerifier); + final stateParam = state ?? _generateRandomString(32); + + // Build authorization URL + final authUri = Uri.parse(authorizationUrl).replace(queryParameters: { + 'response_type': 'code', + 'redirect_uri': redirectUri, + 'scope': scope, + 'state': stateParam, + 'code_challenge': codeChallenge, + 'code_challenge_method': 'S256', + // Only include client_id if provided (some servers support public clients) + if (clientId != null && clientId.isNotEmpty) 'client_id': clientId, + }); + + Logger.root.info('Starting OAuth flow with URL: $authUri'); + + // Open popup window for authorization + final popup = html.window.open( + authUri.toString(), + 'oauth_popup', + 'width=600,height=700,scrollbars=yes,resizable=yes,status=yes,location=yes', + ); + + // Check if popup opened successfully + Timer? timer; + timer = Timer(const Duration(milliseconds: 100), () { + if (popup.closed == true) { + timer?.cancel(); + throw Exception('Popup was closed immediately. This may be due to popup blocker settings.'); + } + }); + + try { + // Listen for the callback + final result = await _waitForCallback(popup, redirectUri, stateParam); + timer.cancel(); + + // Extract authorization code from callback + final code = result['code']; + if (code == null) { + throw Exception('Authorization code not received'); + } + + return { + 'code': code, + 'code_verifier': codeVerifier, + 'state': result['state'], + }; + } catch (e) { + timer.cancel(); + popup.close(); + rethrow; + } + } catch (e) { + Logger.root.severe('OAuth flow failed: $e'); + rethrow; + } + } + + /// Exchanges authorization code for access token + static Future> exchangeCodeForToken({ + required String tokenUrl, + String? clientId, // Made nullable for public clients + String? clientSecret, + required String code, + required String codeVerifier, + required String redirectUri, + }) async { + try { + final headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json', + }; + + final body = { + 'grant_type': 'authorization_code', + 'code': code, + 'redirect_uri': redirectUri, + 'code_verifier': codeVerifier, + }; + + // Only include client_id if it's provided and not the default fallback + // Some OAuth servers (like Notion MCP) work with public clients (no client_id) + if (clientId != null && clientId.isNotEmpty && clientId != 'mcp-client') { + body['client_id'] = clientId; + } + + if (clientSecret != null && clientSecret.isNotEmpty) { + body['client_secret'] = clientSecret; + } + + Logger.root.info('Exchanging code for token at: $tokenUrl'); + + final response = await http.post( + Uri.parse(tokenUrl), + headers: headers, + body: body.entries.map((e) => '${e.key}=${Uri.encodeComponent(e.value)}').join('&'), + ); + + if (response.statusCode == 200) { + final tokenData = json.decode(response.body) as Map; + + // Calculate token expiry if expires_in is provided + if (tokenData['expires_in'] != null) { + final expiresIn = tokenData['expires_in'] as int; + tokenData['expires_at'] = DateTime.now().add(Duration(seconds: expiresIn)).toIso8601String(); + } + + Logger.root.info('Token exchange successful'); + return tokenData; + } else { + final errorBody = response.body; + Logger.root.severe('Token exchange failed: ${response.statusCode} - $errorBody'); + throw Exception('Token exchange failed: ${response.statusCode} - $errorBody'); + } + } catch (e) { + Logger.root.severe('Token exchange error: $e'); + rethrow; + } + } + + /// Refreshes an expired access token + static Future> refreshToken({ + required String tokenUrl, + String? clientId, // Made nullable for public clients + String? clientSecret, + required String refreshToken, + }) async { + try { + final headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Accept': 'application/json', + }; + + final body = { + 'grant_type': 'refresh_token', + 'refresh_token': refreshToken, + }; + + // Only include client_id if provided + if (clientId != null && clientId.isNotEmpty) { + body['client_id'] = clientId; + } + + if (clientSecret != null && clientSecret.isNotEmpty) { + body['client_secret'] = clientSecret; + } + + Logger.root.info('Refreshing token at: $tokenUrl'); + + final response = await http.post( + Uri.parse(tokenUrl), + headers: headers, + body: body.entries.map((e) => '${e.key}=${Uri.encodeComponent(e.value)}').join('&'), + ); + + if (response.statusCode == 200) { + final tokenData = json.decode(response.body) as Map; + + // Calculate token expiry if expires_in is provided + if (tokenData['expires_in'] != null) { + final expiresIn = tokenData['expires_in'] as int; + tokenData['expires_at'] = DateTime.now().add(Duration(seconds: expiresIn)).toIso8601String(); + } + + Logger.root.info('Token refresh successful'); + return tokenData; + } else { + final errorBody = response.body; + Logger.root.severe('Token refresh failed: ${response.statusCode} - $errorBody'); + throw Exception('Token refresh failed: ${response.statusCode} - $errorBody'); + } + } catch (e) { + Logger.root.severe('Token refresh error: $e'); + rethrow; + } + } + + /// Waits for OAuth callback in popup window + static Future> _waitForCallback( + html.WindowBase popup, + String redirectUri, + String expectedState, + ) async { + final completer = Completer>(); + + Logger.root.info('Waiting for OAuth callback...'); + Logger.root.info('Expected redirect URI: $redirectUri'); + Logger.root.info('Expected state: $expectedState'); + + // Set up message listener for cross-origin communication + late StreamSubscription subscription; + + subscription = html.window.onMessage.listen((html.MessageEvent event) { + try { + Logger.root.info('Received OAuth message from: ${event.origin}'); + Logger.root.info('Message data: ${event.data}'); + + final data = event.data; + + // Filter out browser extension messages + if (data is Map) { + final messageMap = Map.from(data); + + // Check for known browser extension message patterns + if (messageMap.containsKey('source') && + (messageMap['source'].toString().contains('devtools') || + messageMap['source'].toString().contains('extension') || + messageMap['source'].toString().contains('react-devtools'))) { + Logger.root.info('Ignoring browser extension message from: ${messageMap['source']}'); + return; + } + + // Check for other extension-like messages + if (messageMap.containsKey('hello') && messageMap['hello'] == true) { + Logger.root.info('Ignoring extension hello message'); + return; + } + + // Check for webpack/dev server messages + if (messageMap.containsKey('type') && + (messageMap['type'].toString().contains('webpack') || + messageMap['type'].toString().contains('devserver'))) { + Logger.root.info('Ignoring webpack/dev server message'); + return; + } + } + + // Verify origin for security - must match redirect URI host + final redirectHost = Uri.parse(redirectUri).host; + if (!event.origin.contains(redirectHost)) { + Logger.root.warning('Ignoring message from untrusted origin: ${event.origin} (expected: $redirectHost)'); + return; + } + + if (data is Map) { + final result = Map.from(data.map((k, v) => MapEntry(k.toString(), v?.toString()))); + + Logger.root.info('Processing OAuth result: $result'); + + // Only process messages that look like OAuth responses + if (!result.containsKey('code') && !result.containsKey('error') && !result.containsKey('state')) { + Logger.root.info('Ignoring non-OAuth message (missing OAuth parameters)'); + return; + } + + // Verify state parameter + if (result['state'] != expectedState) { + Logger.root.severe('State mismatch - expected: $expectedState, got: ${result['state']}'); + completer.completeError(Exception('Invalid state parameter')); + return; + } + + if (result['error'] != null) { + Logger.root.severe('OAuth error received: ${result['error']}'); + completer.completeError(Exception('OAuth error: ${result['error']} - ${result['error_description'] ?? ''}')); + return; + } + + if (result['code'] != null) { + Logger.root.info('Authorization code received successfully'); + subscription.cancel(); + popup.close(); + // Filter out null values before completing + final filteredResult = {}; + result.forEach((key, value) { + if (value != null) { + filteredResult[key] = value; + } + }); + completer.complete(filteredResult); + } + } + } catch (e) { + Logger.root.severe('Error processing OAuth callback: $e'); + completer.completeError(e); + } + }); + + // Check if popup is closed manually + final timer = Timer.periodic(const Duration(seconds: 1), (timer) { + if (popup.closed == true) { + Logger.root.warning('OAuth popup was closed by user'); + timer.cancel(); + subscription.cancel(); + if (!completer.isCompleted) { + completer.completeError(Exception('OAuth popup was closed by user')); + } + } + }); + + try { + final result = await completer.future.timeout( + const Duration(minutes: 10), + onTimeout: () { + subscription.cancel(); + timer.cancel(); + popup.close(); + throw Exception('OAuth flow timed out'); + }, + ); + + timer.cancel(); + return result; + } catch (e) { + timer.cancel(); + subscription.cancel(); + popup.close(); + rethrow; + } + } +} diff --git a/lib/utils/platform.dart b/lib/utils/platform.dart new file mode 100644 index 0000000..3d5db7b --- /dev/null +++ b/lib/utils/platform.dart @@ -0,0 +1,27 @@ +import 'dart:io' show Platform; +import 'package:flutter/foundation.dart' show kIsWeb; + +final bool kIsDebug = (() { + bool isDebug = false; + assert(() { + isDebug = true; + return true; + }()); + return isDebug; +}()); + +final bool kIsLinux = !kIsWeb && Platform.isLinux; +final bool kIsWindows = !kIsWeb && Platform.isWindows; +final bool kIsMacOS = !kIsWeb && Platform.isMacOS; +final bool kIsDesktop = !kIsWeb && (kIsLinux || kIsWindows || kIsMacOS); +final bool kIsMobile = !kIsWeb && (Platform.isAndroid || Platform.isIOS); +final bool kIsAndroid = !kIsWeb && Platform.isAndroid; +final bool kIsIOS = !kIsWeb && Platform.isIOS; +final bool kIsBrowser = kIsWeb; + +String? getPlatformPath() { + if (kIsWeb) { + return null; + } + return Platform.environment['PATH']; +} diff --git a/lib/utils/process.dart b/lib/utils/process.dart new file mode 100644 index 0000000..faee0d6 --- /dev/null +++ b/lib/utils/process.dart @@ -0,0 +1,228 @@ +import 'dart:io'; +import 'package:logging/logging.dart'; + +Future getDefaultPath([String? additionalPath]) async { + final List defaultPaths = []; + + if (Platform.isWindows) { + defaultPaths.addAll(['C:\\Windows\\System32', 'C:\\Windows', 'C:\\Windows\\System32\\Wbem', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0']); + } else if (Platform.isMacOS) { + defaultPaths.addAll(['/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']); + } else { + defaultPaths.addAll(['/usr/local/bin', '/usr/bin', '/bin', '/usr/sbin', '/sbin']); + } + + final String pathSeparator = Platform.isWindows ? ';' : ':'; + final String systemPath = Platform.environment['PATH'] ?? ''; + + // Combine default paths, system PATH, and additional paths + final List allPaths = [...defaultPaths, ...systemPath.split(pathSeparator)]; + + // If additional paths are provided, add them to the list + if (additionalPath != null && additionalPath.isNotEmpty) { + allPaths.addAll(additionalPath.split(pathSeparator)); + } + + // Remove empty paths and deduplicate + return allPaths.where((path) => path.isNotEmpty).toSet().join(pathSeparator); +} + +Future isCommandAvailable(String command) async { + try { + final String whichCommand = Platform.isWindows ? 'where' : 'which'; + final Map env = Map.of(Platform.environment); + env['PATH'] = await getDefaultPath(); + + final result = await Process.run(whichCommand, [command], environment: env, includeParentEnvironment: true); + + return result.exitCode == 0; + } catch (e) { + return false; + } +} + +Map? _cachedEnv; + +Future> _loadShellEnv() async { + if (!Platform.isMacOS && !Platform.isLinux) { + return {}; + } + + try { + // Get the user's default shell + final String shell = Platform.environment['SHELL'] ?? '/bin/bash'; + final String homeDir = Platform.environment['HOME'] ?? ''; + final String user = Platform.environment['USER'] ?? ''; + + // Create a temporary script to load environment variables + final tempDir = await Directory.systemTemp.createTemp('env_loader'); + final scriptFile = File('${tempDir.path}/load_env.sh'); + + // Write the environment loading script + await scriptFile.writeAsString(''' +#!$shell +# Set basic environment +export HOME="$homeDir" +export USER="$user" +export SHELL="$shell" +export TERM="xterm-256color" +export LANG="en_US.UTF-8" +export ENV_PREPARED=1 + +# Load system-level configuration +if [ -f /etc/profile ]; then + . /etc/profile +fi + +# Load configuration based on the shell type +if [[ "$shell" == *"/bash" ]]; then + # Bash shell + if [ -f "\$HOME/.bash_profile" ]; then + . "\$HOME/.bash_profile" + elif [ -f "\$HOME/.bash_login" ]; then + . "\$HOME/.bash_login" + elif [ -f "\$HOME/.profile" ]; then + . "\$HOME/.profile" + fi +elif [[ "$shell" == *"/zsh" ]]; then + # Zsh shell + if [ -f "\$HOME/.zprofile" ]; then + . "\$HOME/.zprofile" + fi + if [ -f "\$HOME/.zshrc" ]; then + . "\$HOME/.zshrc" + fi + + # Attempt to load common Python version managers + # pyenv + if [ -d "\$HOME/.pyenv" ]; then + export PYENV_ROOT="\$HOME/.pyenv" + export PATH="\$PYENV_ROOT/bin:\$PATH" + eval "\$(pyenv init --path 2>/dev/null || true)" + eval "\$(pyenv init - 2>/dev/null || true)" + fi + + # conda/miniconda + for conda_path in "\$HOME/miniconda3" "\$HOME/anaconda3" "\$HOME/.conda"; do + if [ -f "\$conda_path/etc/profile.d/conda.sh" ]; then + . "\$conda_path/etc/profile.d/conda.sh" + break + fi + done +fi + +# Output all environment variables +env +'''); + + // Set script permissions + await Process.run('chmod', ['+x', scriptFile.path]); + + // Execute the script to get environment variables + final result = await Process.run( + shell, + [ + '-l', // Run in login mode to ensure all configuration files are loaded + scriptFile.path, + ], + environment: { + 'HOME': homeDir, + 'USER': user, + 'SHELL': shell, + 'TERM': 'xterm-256color', + 'PATH': '/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', + }, + ); + + // Clean up temporary files + await tempDir.delete(recursive: true); + + if (result.exitCode != 0) { + Logger.root.warning('Failed to load shell environment: ${result.stderr}'); + return {}; + } + + // Parse environment variables + final Map env = {}; + final lines = result.stdout.toString().split('\n'); + for (final line in lines) { + final parts = line.split('='); + if (parts.length >= 2) { + final key = parts[0]; + final value = parts.sublist(1).join('='); + env[key] = value; + } + } + + Logger.root.info('Loaded shell environment: $env'); + + return env; + } catch (e) { + Logger.root.severe('Error loading shell environment: $e'); + return {}; + } +} + +Future> getDefaultEnv() async { + // If the environment variables are already loaded, return the cached version + if (_cachedEnv != null) { + return Map.of(_cachedEnv!); + } + final Map env = Map.of(Platform.environment); + if (Platform.isWindows) { + env['PYTHONIOENCODING'] = 'utf-8'; + env['PYTHONLEGACYWINDOWSSTDIO'] = 'utf-8'; + } else if (Platform.isMacOS || Platform.isLinux) { + // Mark environment variables as prepared + env['ENV_PREPARED'] = '1'; + + final Map shellEnv = await _loadShellEnv(); + if (shellEnv.containsKey('PATH')) { + final String newPath = shellEnv['PATH']!; + Logger.root.info('Loaded PATH from shell: $newPath'); + env['PATH'] = newPath; + } else { + final String defaultPath = await getDefaultPath(); + Logger.root.info('Using default PATH: $defaultPath'); + env['PATH'] = defaultPath; + } + + // Merge other environment variables + shellEnv.forEach((key, value) { + if (key != 'PATH' && !env.containsKey(key)) { + env[key] = value; + } + }); + } + Logger.root.info('Default environment: $env'); + + // Cache the environment variables + _cachedEnv = Map.of(env); + + return env; +} + +Future startProcess(String command, List args, Map environment) async { + final Map env = await getDefaultEnv(); + env.addAll(environment); // Add user-provided environment variables + + // Validate command exists before starting process + if (!await isCommandAvailable(command)) { + throw ProcessException(command, args, 'Command not found: $command. Please check if the command exists and is in PATH.'); + } + + return Process.start( + command, + args, + environment: env, + includeParentEnvironment: true, + // Windows needs this to run properly; keep other platforms as default (false). + runInShell: Platform.isWindows, + ); +} + +/// Clear the environment variable cache to force reloading next time +void clearEnvironmentCache() { + _cachedEnv = null; + Logger.root.info('Environment cache cleared, will reload next time'); +} diff --git a/lib/utils/storage_manager.dart b/lib/utils/storage_manager.dart new file mode 100644 index 0000000..16ef96b --- /dev/null +++ b/lib/utils/storage_manager.dart @@ -0,0 +1,60 @@ +import 'dart:io'; +import 'package:path/path.dart' as path; +import 'package:chatmcp/utils/platform.dart'; +import 'package:path_provider/path_provider.dart'; + +class StorageManager { + static const String _appName = 'ChatMcp'; + static String? _appDataDirectory; + + /// 获取应用数据目录 + static Future getAppDataDirectory() async { + if (_appDataDirectory != null) return _appDataDirectory!; + + if (kIsMobile) { + try { + final appDir = await getApplicationDocumentsDirectory(); + _appDataDirectory = path.join(appDir.path, _appName); + } catch (e) { + // 如果获取应用目录失败,使用临时目录作为备选 + final tempDir = await getTemporaryDirectory(); + _appDataDirectory = path.join(tempDir.path, _appName); + } + } else if (kIsLinux) { + // Linux: 遵循 XDG Base Directory Specification + final homeDir = Platform.environment['HOME'] ?? ''; + final xdgDataHome = Platform.environment['XDG_DATA_HOME'] ?? path.join(homeDir, '.local', 'share'); + _appDataDirectory = path.join(xdgDataHome, _appName); + } else if (kIsWindows) { + final appDataDir = Platform.environment['APPDATA'] ?? ''; + _appDataDirectory = path.join(appDataDir, _appName); + } else if (kIsMacOS) { + final homeDir = Platform.environment['HOME'] ?? ''; + _appDataDirectory = path.join(homeDir, 'Library', 'Application Support', _appName); + } else { + // 其他平台:使用 path_provider 作为回退方案 + try { + final appDir = await getApplicationDocumentsDirectory(); + _appDataDirectory = path.join(appDir.path, _appName); + } catch (e) { + // 如果获取应用目录失败,使用临时目录作为备选 + final tempDir = await getTemporaryDirectory(); + _appDataDirectory = path.join(tempDir.path, _appName); + } + } + + // 确保目录存在 + final dir = Directory(_appDataDirectory!); + if (!await dir.exists()) { + await dir.create(recursive: true); + } + + return _appDataDirectory!; + } + + /// Get database file path + static Future getDatabasePath() async { + final appDir = await getAppDataDirectory(); + return path.join(appDir, 'chatmcp.db'); + } +} diff --git a/lib/utils/stream.dart b/lib/utils/stream.dart new file mode 100644 index 0000000..af53581 --- /dev/null +++ b/lib/utils/stream.dart @@ -0,0 +1,9 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +Stream asStream(ChangeNotifier notifier, T Function() value) { + final controller = StreamController(); + notifier.addListener(() => controller.add(value())); + return controller.stream; +} diff --git a/lib/utils/toast.dart b/lib/utils/toast.dart new file mode 100644 index 0000000..00a8e92 --- /dev/null +++ b/lib/utils/toast.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:bot_toast/bot_toast.dart'; + +class ToastUtils { + /// 显示错误级别的 toast 通知 + /// [message] 错误信息 + /// [duration] 显示持续时间,默认 5 秒 + static void error(String message, {Duration? duration}) { + BotToast.showText( + text: message, + duration: duration ?? Duration(seconds: 5), + align: Alignment(0.0, -0.7), + contentColor: Colors.red.shade600, + textStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500), + ); + } + + /// 显示警告级别的 toast 通知 + /// [message] 警告信息 + /// [duration] 显示持续时间,默认 4 秒 + static void warn(String message, {Duration? duration}) { + BotToast.showText( + text: message, + duration: duration ?? Duration(seconds: 4), + align: Alignment(0.0, -0.7), + contentColor: Colors.orange.shade600, + textStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500), + ); + } + + /// 显示信息级别的 toast 通知 + /// [message] 信息内容 + /// [duration] 显示持续时间,默认 3 秒 + static void info(String message, {Duration? duration}) { + BotToast.showText( + text: message, + duration: duration ?? Duration(seconds: 3), + align: Alignment(0.0, -0.7), + contentColor: Colors.blue.shade600, + textStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500), + ); + } + + /// 显示成功级别的 toast 通知 + /// [message] 成功信息 + /// [duration] 显示持续时间,默认 3 秒 + static void success(String message, {Duration? duration}) { + BotToast.showText( + text: message, + duration: duration ?? Duration(seconds: 3), + align: Alignment(0.0, -0.7), + contentColor: Colors.green.shade600, + textStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500), + ); + } + + /// 显示自定义样式的 toast 通知 + /// [message] 消息内容 + /// [color] 背景颜色 + /// [duration] 显示持续时间 + /// [align] 对齐方式 + static void custom({required String message, required Color color, Duration? duration, Alignment? align, TextStyle? textStyle}) { + BotToast.showText( + text: message, + duration: duration ?? Duration(seconds: 3), + align: align ?? Alignment(0.0, -0.7), + contentColor: color, + textStyle: textStyle ?? TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500), + ); + } +} diff --git a/lib/widgets/browser/browser.dart b/lib/widgets/browser/browser.dart new file mode 100644 index 0000000..776c7f1 --- /dev/null +++ b/lib/widgets/browser/browser.dart @@ -0,0 +1,183 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:flutter/foundation.dart'; +import 'package:logging/logging.dart'; +import 'package:chatmcp/utils/inappview.dart'; +import 'dart:convert'; +import 'package:flutter/services.dart' show rootBundle; +import 'package:html2md/html2md.dart' as html2md; +import 'package:chatmcp/generated/app_localizations.dart'; + +class SearchResult { + final String title; + final String url; + final String snippet; + String content = ''; + + SearchResult({required this.title, required this.url, required this.snippet, this.content = ''}); + + factory SearchResult.fromJson(Map json) { + return SearchResult(title: json['title'] ?? '', url: json['url'] ?? '', snippet: json['snippet'] ?? '', content: json['content'] ?? ''); + } +} + +class BrowserView extends StatefulWidget { + final String url; + + const BrowserView({super.key, required this.url}); + + @override + State createState() => BrowserViewState(); +} + +class BrowserViewState extends State { + final browser = MyInAppBrowser(webViewEnvironment: webViewEnvironment); + List searchResults = []; + + final settings = InAppBrowserClassSettings( + browserSettings: InAppBrowserSettings(hideUrlBar: true), + webViewSettings: InAppWebViewSettings( + userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + javaScriptEnabled: true, + isInspectable: kDebugMode, + ), + ); + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + return IconButton( + icon: const Icon(Icons.open_in_browser), + tooltip: t.openBrowser, + onPressed: () { + browser.openUrlRequest( + urlRequest: URLRequest(url: WebUri('http://google.com/search?q=${widget.url}')), + settings: settings, + ); + debugPrint(t.openingBrowser); + }, + ); + } +} + +class MyInAppBrowser extends InAppBrowser { + MyInAppBrowser({super.webViewEnvironment}); + List searchResults = []; + HeadlessInAppWebView? contentWebView; + String? turndownJs; + + @override + Future onBrowserCreated() async { + debugPrint("Browser Created!"); + // initialize headless browser for extracting content + contentWebView = HeadlessInAppWebView( + initialSettings: InAppWebViewSettings( + userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', + javaScriptEnabled: true, + ), + ); + await contentWebView?.run(); + + // load turndown.js file + turndownJs = await rootBundle.loadString('assets/js/turndown.js'); + } + + @override + Future onLoadStart(url) async { + debugPrint("Started $url"); + } + + @override + Future onLoadStop(url) async { + debugPrint("Stopped $url"); + final pageDataList = await extractSearchResults(); + debugPrint('pageDataList: $pageDataList'); + } + + Future extractContent(String url) async { + try { + final controller = contentWebView?.webViewController; + if (controller == null) { + return ''; + } + + await controller.loadUrl(urlRequest: URLRequest(url: WebUri(url))); + + await Future.delayed(const Duration(seconds: 3)); + + // check page content + final pageContent = await controller.evaluateJavascript(source: 'document.documentElement.outerHTML'); + + final md = html2md.convert(pageContent); + return md; + } catch (e) { + debugPrint('extract content error: $e'); + debugPrint('error stack: ${StackTrace.current}'); + return ''; + } + } + + Future>> extractSearchResults() async { + final js = ''' + function extractResults() { + const results = []; + document.querySelectorAll('.g').forEach(item => { + const titleEl = item.querySelector('.LC20lb'); + const linkEl = item.querySelector('a'); + const snippetEl = item.querySelector('.VwiC3b'); + + if(titleEl && linkEl && snippetEl) { + results.push({ + title: titleEl.innerText, + url: linkEl.href, + snippet: snippetEl.innerText + }); + } + }); + return JSON.stringify(results); + } + extractResults(); + '''; + + final result = await webViewController?.evaluateJavascript(source: js); + if (result != null) { + try { + final List parsed = jsonDecode(result); + searchResults = parsed.map((item) => SearchResult.fromJson(item)).toList(); + + List> pageDataList = []; + // iterate to get content of each result + for (var result in searchResults) { + Map paegData = { + 'title': result.title, + 'url': result.url, + 'snippet': result.snippet, + 'content': await extractContent(result.url), + }; + pageDataList.add(paegData); + } + + return pageDataList; + } catch (e) { + Logger.root.severe('parse search results error: $e'); + } + } + return []; + } + + @override + void onReceivedError(WebResourceRequest request, WebResourceError error) { + debugPrint("Can't load ${request.url}.. Error: ${error.description}"); + } + + @override + void onProgressChanged(progress) { + debugPrint("Progress: $progress"); + } + + @override + Future onExit() async { + debugPrint("Browser closed!"); + await contentWebView?.dispose(); + } +} diff --git a/lib/widgets/cache_image.dart b/lib/widgets/cache_image.dart new file mode 100644 index 0000000..6cefeda --- /dev/null +++ b/lib/widgets/cache_image.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:logging/logging.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:flutter_cache_manager/flutter_cache_manager.dart'; +import 'dart:io' show Platform; + +class CacheImage extends StatelessWidget { + final String imageUrl; + + const CacheImage({super.key, required this.imageUrl}); + + Future _downloadImage(BuildContext context) async { + // 获取全局上下文 + final scaffoldContext = Navigator.of(context).context; + try { + if (!scaffoldContext.mounted) return; + ScaffoldMessenger.of(scaffoldContext).showSnackBar(const SnackBar(content: Text('start to save image...'))); + + // 从缓存中获取文件 + var fileInfo = await DefaultCacheManager().getFileFromCache(imageUrl); + fileInfo ??= await DefaultCacheManager().downloadFile(imageUrl); + + if (Platform.isAndroid || Platform.isIOS) { + // todo + } else { + // 获取下载目录 + final dir = await getDownloadsDirectory(); + if (dir == null) { + throw Exception('cannot get download directory'); + } + + // 从URL中提取文件扩展名 + final extension = imageUrl.split('.').last.split('?').first; + final fileName = 'image_${DateTime.now().millisecondsSinceEpoch}.$extension'; + final savePath = '${dir.path}/$fileName'; + + // 复制文件 + await fileInfo.file.copy(savePath); + + if (!scaffoldContext.mounted) return; + ScaffoldMessenger.of(scaffoldContext).showSnackBar( + SnackBar( + content: Text('image saved to download directory: $fileName'), + action: SnackBarAction( + label: 'ok', + onPressed: () { + ScaffoldMessenger.of(scaffoldContext).hideCurrentSnackBar(); + }, + ), + ), + ); + } + } catch (e) { + if (!scaffoldContext.mounted) return; + Logger.root.severe('save image failed: $e'); + ScaffoldMessenger.of(scaffoldContext).showSnackBar( + SnackBar( + content: Text('save image failed: ${e.toString()}'), + backgroundColor: Colors.red, + action: SnackBarAction(label: 'retry', textColor: Colors.white, onPressed: () => _downloadImage(scaffoldContext)), + ), + ); + } + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () => _showImagePreview(context), + child: CachedNetworkImage( + height: 200, + imageUrl: imageUrl, + placeholder: (context, url) => Container(height: 200, alignment: Alignment.center, child: const CircularProgressIndicator()), + errorWidget: (context, url, error) => Container(height: 200, alignment: Alignment.center, child: const Icon(Icons.error)), + fit: BoxFit.cover, + ), + ); + } + + void _showImagePreview(BuildContext context) { + showDialog( + context: context, + builder: (context) => Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)), + child: Stack( + children: [ + CachedNetworkImage(imageUrl: imageUrl, fit: BoxFit.contain), + Positioned( + right: 8, + top: 8, + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.download, color: Colors.white), + onPressed: () => _downloadImage(context), + ), + IconButton( + icon: const Icon(Icons.close, color: Colors.white), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/collapsible_section.dart b/lib/widgets/collapsible_section.dart new file mode 100644 index 0000000..ac35548 --- /dev/null +++ b/lib/widgets/collapsible_section.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/utils/color.dart'; + +class CollapsibleSection extends StatefulWidget { + final Widget title; + final Widget content; + final EdgeInsetsGeometry? padding; + final bool initiallyExpanded; + + const CollapsibleSection({super.key, required this.title, required this.content, this.padding, this.initiallyExpanded = false}); + + @override + State createState() => _CollapsibleSectionState(); +} + +class _CollapsibleSectionState extends State { + late bool _isExpanded; + + @override + void initState() { + super.initState(); + _isExpanded = widget.initiallyExpanded; + } + + @override + Widget build(BuildContext context) { + return SizedBox( + width: double.infinity, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InkWell( + onTap: () => setState(() => _isExpanded = !_isExpanded), + child: Row( + children: [ + Icon(_isExpanded ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_right, size: 16, color: AppColors.grey[600]), + Expanded(child: widget.title), + ], + ), + ), + if (_isExpanded) Padding(padding: widget.padding ?? const EdgeInsets.only(top: 4.0, left: 8.0), child: widget.content), + ], + ), + ); + } +} diff --git a/lib/widgets/expandable_widget.dart b/lib/widgets/expandable_widget.dart new file mode 100644 index 0000000..8082e34 --- /dev/null +++ b/lib/widgets/expandable_widget.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; + +/// 单行展示的组件 +class ExpandableRow extends StatelessWidget { + final List children; + final bool isExpanded; + final EdgeInsetsGeometry? padding; + + const ExpandableRow({super.key, required this.children, required this.isExpanded, this.padding}); + + @override + Widget build(BuildContext context) { + return Row( + children: [ + ...children, + Icon(isExpanded ? Icons.expand_less : Icons.expand_more, color: Theme.of(context).iconTheme.color?.withAlpha(128)), + ], + ); + } +} + +/// 可展开的组件 +class ExpandableWidget extends StatefulWidget { + final Widget header; + final Widget expandedContent; + final Color? backgroundColor; + final double borderRadius; + final EdgeInsetsGeometry margin; + final bool initiallyExpanded; + final VoidCallback? onExpandChanged; + final EdgeInsetsGeometry contentPadding; + + const ExpandableWidget({ + super.key, + required this.header, + required this.expandedContent, + this.backgroundColor, + this.borderRadius = 8.0, + this.margin = const EdgeInsets.symmetric(vertical: 4.0), + this.initiallyExpanded = false, + this.onExpandChanged, + this.contentPadding = const EdgeInsets.all(8.0), + }); + + @override + State createState() => _ExpandableWidgetState(); +} + +class _ExpandableWidgetState extends State { + late bool _isExpanded; + + @override + void initState() { + super.initState(); + _isExpanded = widget.initiallyExpanded; + } + + void _toggleExpanded() { + setState(() { + _isExpanded = !_isExpanded; + }); + widget.onExpandChanged?.call(); + } + + @override + Widget build(BuildContext context) { + return Container( + margin: widget.margin, + decoration: BoxDecoration( + color: widget.backgroundColor ?? Theme.of(context).cardColor, + borderRadius: BorderRadius.circular(widget.borderRadius), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Material( + color: Colors.transparent, + child: InkWell( + onTap: _toggleExpanded, + borderRadius: BorderRadius.circular(widget.borderRadius), + hoverColor: Theme.of(context).hoverColor, + splashColor: Theme.of(context).splashColor, + mouseCursor: SystemMouseCursors.click, + child: widget.header, + ), + ), + if (_isExpanded) + DefaultTextStyle( + style: DefaultTextStyle.of(context).style.copyWith(color: Theme.of(context).textTheme.bodyMedium?.color?.withAlpha(179)), + child: Padding(padding: widget.contentPadding, child: widget.expandedContent), + ), + ], + ), + ); + } +} diff --git a/lib/widgets/ink_icon.dart b/lib/widgets/ink_icon.dart new file mode 100644 index 0000000..733001e --- /dev/null +++ b/lib/widgets/ink_icon.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'dart:io' show Platform; +import 'package:flutter/foundation.dart' show kIsWeb; + +class InkIcon extends StatelessWidget { + final IconData icon; + final void Function()? onTap; + final bool disabled; + final Color? hoverColor; + final String? tooltip; + final Color? color; + final double? size; + final String? text; + final Widget? child; + const InkIcon({ + super.key, + required this.icon, + this.onTap, + this.disabled = false, + this.hoverColor, + this.tooltip, + this.color, + this.size = 16, + this.text, + this.child, + }); + + @override + Widget build(BuildContext context) { + final double effectiveSize = size != 16 + ? size! + : (kIsWeb + ? 16.0 + : (Platform.isAndroid || Platform.isIOS) + ? 24.0 + : 16.0); + + final Widget iconWidget = Material( + color: Colors.transparent, + child: InkWell( + onTap: disabled ? null : onTap, + hoverColor: hoverColor ?? AppColors.getInkIconHoverColor(context), + borderRadius: BorderRadius.circular(4), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), + child: Row( + children: [ + Icon(icon, size: effectiveSize, color: color), + if (text != null) Text(text!), + if (child != null) child!, + ], + ), + ), + ), + ); + + if (tooltip == null) { + return iconWidget; + } + + return Tooltip(message: tooltip!, child: iconWidget); + } +} diff --git a/lib/widgets/markdown/markit_widget.dart b/lib/widgets/markdown/markit_widget.dart new file mode 100644 index 0000000..3d31738 --- /dev/null +++ b/lib/widgets/markdown/markit_widget.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import './widgets/latex.dart'; +import './widgets/link.dart'; +import './widgets/code.dart'; +import './widgets/details.dart'; +import 'widgets/think.dart'; +import './widgets/artifact.dart'; +import './widgets/image.dart'; +import './widgets/inline_code.dart'; +import './widgets/function.dart'; +import './widgets/function_result.dart'; + +class MarkitTestPage extends StatelessWidget { + const MarkitTestPage({super.key}); + + @override + Widget build(BuildContext context) { + String testMarkdown = + r''' +This image is a math problem, involving the calculation of the cost of anti-slip tiles in a school building. The problem description is as follows: + +# test + + +33333 +## test + + +33333 + +''' + '\n${DateTime.now().toIso8601String()}'; + + return Scaffold( + appBar: AppBar(title: const Text('Markit Test')), + body: Markit(data: testMarkdown), + ); + } +} + +class Markit extends StatefulWidget { + final String data; + final TextStyle? textStyle; + + const Markit({super.key, required this.data, this.textStyle}); + + @override + State createState() => _MarkitState(); +} + +class _MarkitState extends State { + String _cachedData = ''; + Widget? _cachedMarkdown; + Brightness? _cachedBrightness; + + @override + Widget build(BuildContext context) { + final currentBrightness = Theme.of(context).brightness; + if (widget.data != _cachedData || _cachedMarkdown == null || _cachedBrightness != currentBrightness) { + _cachedData = widget.data; + _cachedBrightness = currentBrightness; + + final isDark = currentBrightness == Brightness.dark; + final textStyle = widget.textStyle; + final data = _cachedData; + _cachedMarkdown = MarkdownBlock( + data: data, + config: MarkdownConfig( + configs: [ + PConfig(textStyle: textStyle ?? const TextStyle(fontSize: 14, height: 20 / 14)), + H1Config(style: const TextStyle(fontSize: 24, height: 24 / 24)), + H2Config(style: const TextStyle(fontSize: 20, height: 20 / 20)), + H3Config(style: const TextStyle(fontSize: 16, height: 16 / 16)), + H4Config(style: const TextStyle(fontSize: 12, height: 12 / 12)), + H5Config(style: const TextStyle(fontSize: 14, height: 14 / 14)), + H6Config(style: const TextStyle(fontSize: 14, height: 14 / 14)), + TableConfig(), + CodeConfig(), + LinkConfig( + style: const TextStyle(color: Colors.yellow, decoration: TextDecoration.underline), + ), + isDark ? PreConfig.darkConfig.copy(textStyle: const TextStyle(fontSize: 12)) : PreConfig().copy(textStyle: const TextStyle(fontSize: 12)), + DetailConfig(), + ], + ), + generator: MarkdownGenerator( + linesMargin: const EdgeInsets.symmetric(vertical: 4), + generators: [ + linkGenerator, + latexGenerator, + codeBlockGenerator, + artifactAntThinkingGenerator, + artifactAntArtifactGenerator, + thinkGenerator, + detailsGenerator, + imageGenerator, + inlineCodeGenerator, + functionResultGenerator, + functionGenerator, + ], + inlineSyntaxList: [ + ArtifactAntThinkingInlineSyntax(), + ArtifactAntArtifactInlineSyntax(), + DetailsSyntax(), + LinkSyntax(), + LatexSyntax(), + ThinkInlineSyntax(), + FunctionInlineSyntax(), + FunctionResultInlineSyntax(), + ], + blockSyntaxList: [ + DetailsBlockSyntax(), + LatexBlockSyntax(), + ThinkBlockSyntax(), + ArtifactAntThinkingBlockSyntax(), + ArtifactAntArtifactBlockSyntax(), + FunctionBlockSyntax(), + FunctionResultBlockSyntax(), + FencedCodeBlockSyntax(), + ], + ), + ); + } + return _cachedMarkdown ?? const SizedBox(); + } +} diff --git a/lib/widgets/markdown/widgets/artifact.dart b/lib/widgets/markdown/widgets/artifact.dart new file mode 100644 index 0000000..6e88293 --- /dev/null +++ b/lib/widgets/markdown/widgets/artifact.dart @@ -0,0 +1,134 @@ +import 'package:chatmcp/provider/provider_manager.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'think.dart'; +import 'package:chatmcp/utils/event_bus.dart'; + +import 'tag.dart'; + +SpanNodeGeneratorWithTag artifactAntThinkingGenerator = SpanNodeGeneratorWithTag( + tag: _artifactAntThinkingTag, + generator: (e, config, visitor) => ArtifactAntThinkingNode(e.attributes, e.textContent, config), +); + +const _artifactAntThinkingTag = 'antThinking'; + +class ArtifactAntThinkingInlineSyntax extends TagInlineSyntax { + static const tagName = _artifactAntThinkingTag; + ArtifactAntThinkingInlineSyntax() : super(tag: tagName, caseSensitive: false); +} + +class ArtifactAntThinkingBlockSyntax extends TagBlockSyntax { + static const tagName = _artifactAntThinkingTag; + ArtifactAntThinkingBlockSyntax() : super(tag: tagName); +} + +class ArtifactAntThinkingNode extends ThinkNode { + ArtifactAntThinkingNode(super.attributes, super.textContent, super.config); + @override + InlineSpan build() { + return WidgetSpan(child: ArtifactAntThinkingWidget(textContent, attributes)); + } +} + +class ArtifactAntThinkingWidget extends StatelessWidget { + final String textContent; + final Map attributes; + + const ArtifactAntThinkingWidget(this.textContent, this.attributes, {super.key}); + + @override + Widget build(BuildContext context) { + return SelectableText(textContent); + } +} + +SpanNodeGeneratorWithTag artifactAntArtifactGenerator = SpanNodeGeneratorWithTag( + tag: _artifactAntArtifactTag, + generator: (e, config, visitor) => ArtifactAntArtifactNode(e.attributes, e.textContent, config), +); + +const _artifactAntArtifactTag = 'antArtifact'; + +class ArtifactAntArtifactInlineSyntax extends TagInlineSyntax { + static const tagName = _artifactAntArtifactTag; + ArtifactAntArtifactInlineSyntax() : super(tag: tagName, caseSensitive: false); +} + +class ArtifactAntArtifactBlockSyntax extends TagBlockSyntax { + static const tagName = _artifactAntArtifactTag; + ArtifactAntArtifactBlockSyntax() : super(tag: tagName); +} + +class ArtifactAntArtifactNode extends ThinkNode { + ArtifactAntArtifactNode(super.attributes, super.textContent, super.config); + @override + InlineSpan build() { + return WidgetSpan(child: ArtifactAntArtifactWidget(textContent, attributes)); + } +} + +class ArtifactAntArtifactWidget extends StatefulWidget { + final String textContent; + final Map attributes; + + const ArtifactAntArtifactWidget(this.textContent, this.attributes, {super.key}); + + @override + State createState() => _ArtifactAntArtifactWidgetState(); +} + +class _ArtifactAntArtifactWidgetState extends State { + @override + void initState() { + super.initState(); + String hash = widget.attributes['hash'] ?? ''; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + ProviderManager.chatProvider.setPreviewEvent(CodePreviewEvent(hash, widget.textContent, widget.attributes)); + } + }); + } + + @override + Widget build(BuildContext context) { + String title = widget.attributes['title'] ?? ''; + bool isClosed = widget.attributes['closed'] == 'true'; + String hash = widget.attributes['hash'] ?? ''; + + return InkWell( + onTap: () { + debugPrint('onTap: $hash'); + ProviderManager.chatProvider.setPreviewEvent(CodePreviewEvent(hash, widget.textContent, widget.attributes)); + ProviderManager.chatProvider.setShowCodePreview(hash, true); + }, + child: Container( + width: 300, + height: 40, + decoration: BoxDecoration( + color: AppColors.getArtifactBackgroundColor(context), + border: Border.all(color: AppColors.getArtifactBorderColor(context), width: 1.0), + borderRadius: BorderRadius.circular(8.0), + ), + padding: const EdgeInsets.all(8.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text(title, overflow: TextOverflow.ellipsis, maxLines: 1, style: TextStyle(fontSize: 14)), + ), + if (isClosed) + Icon(Icons.check_circle, color: Colors.green) + else + SizedBox( + width: 12, + height: 12, + child: CircularProgressIndicator(color: AppColors.getProgressIndicatorColor(context), strokeWidth: 1.5), + ), + ], + ), + ), + ); + } +} diff --git a/lib/widgets/markdown/widgets/code.dart b/lib/widgets/markdown/widgets/code.dart new file mode 100644 index 0000000..86d77fc --- /dev/null +++ b/lib/widgets/markdown/widgets/code.dart @@ -0,0 +1,316 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:markdown/markdown.dart' as m; +import 'package:chatmcp/utils/color.dart'; +import 'package:flutter/services.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:flutter_highlight/flutter_highlight.dart'; + +import 'mermaid_diagram_view.dart' show MermaidDiagramView; +import 'html_view.dart'; +import './artifact.dart'; + +SpanNodeGeneratorWithTag codeBlockGenerator = SpanNodeGeneratorWithTag( + tag: "pre", + generator: (e, config, visitor) => CodeBlockNode(e, config.pre, visitor), +); + +class CodeBlockNode extends ElementNode { + CodeBlockNode(this.element, this.preConfig, this.visitor); + + String get content => element.textContent; + final PreConfig preConfig; + final m.Element element; + final WidgetVisitor visitor; + + @override + InlineSpan build() { + // m.ExtensionSet + String? language = preConfig.language; + try { + final firstChild = element.children?.firstOrNull; + if (firstChild is m.Element) { + language = firstChild.attributes['class']?.split('-').lastOrNull; + } + } catch (e) { + language = null; + debugPrint('get language error:$e'); + } + final splitContents = content.trim().split(visitor.splitRegExp ?? WidgetVisitor.defaultSplitRegExp); + if (splitContents.last.isEmpty) splitContents.removeLast(); + + final codeBuilder = preConfig.builder; + if (codeBuilder != null) { + return WidgetSpan(child: codeBuilder.call(content, language ?? '')); + } + + bool isClosed = element.attributes['isClosed'] == 'true'; + + final widget = SizedBox( + width: double.infinity, + child: _CodeBlock( + code: content, + language: language ?? '', + isClosed: isClosed, + preConfig: preConfig, + splitContents: splitContents, + visitor: visitor, + ), + ); + + if (language != 'html') { + return WidgetSpan(child: preConfig.wrapper?.call(widget, content, language ?? '') ?? widget); + } + + final widget1 = ArtifactAntArtifactWidget(content, { + 'title': content.length > 20 ? content.substring(0, 20) : content, + 'closed': isClosed.toString(), + 'type': language ?? '', + }); + return WidgetSpan(child: preConfig.wrapper?.call(widget1, content, language ?? '') ?? widget1); + } + + @override + TextStyle get style => preConfig.textStyle.merge(parentStyle); +} + +class _CodeBlock extends StatefulWidget { + final String code; + final String language; + final bool isClosed; + final PreConfig preConfig; + final WidgetVisitor visitor; + final List splitContents; + + const _CodeBlock({ + required this.code, + required this.language, + required this.isClosed, + required this.preConfig, + required this.splitContents, + required this.visitor, + }); + + @override + State<_CodeBlock> createState() => _CodeBlockState(); +} + +class _CodeBlockState extends State<_CodeBlock> with AutomaticKeepAliveClientMixin { + // whether to show preview + bool _isPreviewVisible = false; + // whether to support preview + bool _isSupportPreview = false; + // preview component + Widget? _previewWidget; + + // supported languages for preview + static const List _supportedLanguages = ['mermaid', 'html', 'svg']; + // HTML related languages + static const List _htmlLanguages = ['html', 'svg']; + + @override + bool get wantKeepAlive => true; + + @override + void initState() { + super.initState(); + _initializePreviewState(); + } + + /// initialize preview state + void _initializePreviewState() { + final bool supportPreview = _supportedLanguages.contains(widget.language); + + if (supportPreview) { + _previewWidget = _buildPreviewWidget(); + } + + debugPrint('widget.isClosed: ${widget.isClosed}'); + + setState(() { + _isSupportPreview = supportPreview; + // if support preview and code block is completed, default to show preview + _isPreviewVisible = supportPreview && widget.isClosed; + }); + } + + /// build preview component + Widget? _buildPreviewWidget() { + if (widget.language == 'mermaid') { + return MermaidDiagramView(key: ValueKey(widget.code), code: widget.code); + } else if (_htmlLanguages.contains(widget.language)) { + return HtmlView(key: ValueKey(widget.code), html: widget.code); + } + return null; + } + + /// toggle preview/code view + void _togglePreviewVisibility() { + setState(() { + _isPreviewVisible = !_isPreviewVisible; + }); + } + + /// copy code to clipboard + void _copyCodeToClipboard(BuildContext context, AppLocalizations t) { + Clipboard.setData(ClipboardData(text: widget.code)); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.codeCopiedToClipboard), duration: const Duration(seconds: 2))); + } + + @override + Widget build(BuildContext context) { + final t = AppLocalizations.of(context)!; + super.build(context); + + return Container( + width: double.infinity, + decoration: widget.preConfig.decoration, + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [_buildToolBar(t), _buildContentSection()]), + ); + } + + /// build content section (code or preview) + Widget _buildContentSection() { + if (_isSupportPreview && _isPreviewVisible && _previewWidget != null) { + return _previewWidget!; + } else { + return HighlightView(widget.code, language: widget.language, theme: widget.preConfig.theme, padding: const EdgeInsets.all(5)); + } + } + + /// build toolbar + Widget _buildToolBar(AppLocalizations t) { + return Container( + height: 30, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + decoration: BoxDecoration( + color: AppColors.getCodeBlockToolbarBackgroundColor(context), + borderRadius: const BorderRadius.vertical(top: Radius.circular(8)), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + children: [_buildLanguageLabel(), const Spacer(), _buildToolbarActions(t)], + ), + ); + } + + /// build language label + Widget _buildLanguageLabel() { + return Text( + widget.language.isEmpty ? 'text' : widget.language, + style: TextStyle(color: AppColors.getCodeBlockLanguageTextColor(context), fontSize: 12, fontWeight: FontWeight.bold), + ); + } + + /// build toolbar actions + Widget _buildToolbarActions(AppLocalizations t) { + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + GestureDetector(child: const Icon(Icons.copy, size: 14), onTap: () => _copyCodeToClipboard(context, t)), + if (_isSupportPreview) ...[Gap(size: 8), _buildPreviewToggleButton()], + ], + ); + } + + /// build preview toggle button + Widget _buildPreviewToggleButton() { + return TextButton( + style: TextButton.styleFrom( + minimumSize: Size(20, 20), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + backgroundColor: AppColors.getCodePreviewButtonBackgroundColor(context), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(11)), + ), + onPressed: _togglePreviewVisibility, + child: Text(_isPreviewVisible ? 'Code' : 'Preview', style: const TextStyle(fontSize: 9, height: 1)), + ); + } + + /// build code block list + List buildCodeBlockList() { + return List.generate(widget.splitContents.length, (index) { + final currentContent = widget.splitContents[index]; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: ProxyRichText( + TextSpan( + children: highLightSpans( + currentContent, + language: widget.preConfig.language, + theme: widget.preConfig.theme, + textStyle: widget.preConfig.textStyle, + styleNotMatched: widget.preConfig.styleNotMatched, + ), + ), + richTextBuilder: widget.visitor.richTextBuilder, + ), + ); + }); + } +} + +class FencedCodeBlockSyntax extends m.BlockSyntax { + static final _pattern = RegExp(r'^[ ]{0,3}(~{3,}|`{3,})(.*)$'); + + @override + RegExp get pattern => _pattern; + + const FencedCodeBlockSyntax(); + + @override + m.Node parse(m.BlockParser parser) { + // get start mark and language + final match = pattern.firstMatch(parser.current.content)!; + final openingFence = match.group(1)!; + final infoString = match.group(2)!.trim(); + + bool isClosed = false; + final lines = []; + + // advance to content line + parser.advance(); + + // collect content until find end mark + while (!parser.isDone) { + final currentLine = parser.current.content; + final closingMatch = pattern.firstMatch(currentLine); + + // check if it is end mark + if (closingMatch != null && closingMatch.group(1)!.startsWith(openingFence) && closingMatch.group(2)!.trim().isEmpty) { + isClosed = true; + parser.advance(); + break; + } + + lines.add(currentLine); + parser.advance(); + } + + // if last line is empty and end mark is not found, remove it + if (!isClosed && lines.isNotEmpty && lines.last.trim().isEmpty) { + lines.removeLast(); + } + + // create code element + final code = m.Element.text('code', '${lines.join('\n')}\n'); + + // if there is language mark, add class + if (infoString.isNotEmpty) { + code.attributes['class'] = 'language-$infoString'; + } + + // add is closed mark + code.attributes['isClosed'] = isClosed.toString(); + + // create pre element + final pre = m.Element('pre', [code]); + pre.attributes['isClosed'] = isClosed.toString(); + + return pre; + } +} diff --git a/lib/widgets/markdown/widgets/details.dart b/lib/widgets/markdown/widgets/details.dart new file mode 100644 index 0000000..c2085c7 --- /dev/null +++ b/lib/widgets/markdown/widgets/details.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:markdown/markdown.dart' as md; +import 'package:chatmcp/widgets/markdown/markit_widget.dart'; + +const _detailsTag = 'details'; + +class DetailConfig extends WidgetConfig { + @override + String get tag => _detailsTag; + + final TextStyle? summaryStyle; + final TextStyle? contentStyle; + + DetailConfig({this.summaryStyle = const TextStyle(fontSize: 14, fontWeight: FontWeight.bold), this.contentStyle = const TextStyle(fontSize: 14)}); +} + +class DetailsWidget extends StatefulWidget { + final String textContent; + final Map attributes; + + const DetailsWidget(this.textContent, this.attributes, {super.key}); + + @override + State createState() => _DetailsWidgetState(); +} + +class _DetailsWidgetState extends State { + bool _isExpanded = true; + + @override + Widget build(BuildContext context) { + final summary = widget.attributes['summary'] ?? ''; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InkWell( + onTap: () => setState(() => _isExpanded = !_isExpanded), + child: Row( + children: [ + Icon(_isExpanded ? Icons.arrow_drop_down : Icons.arrow_right, size: 20), + Expanded(child: Text(summary)), + ], + ), + ), + if (_isExpanded) + Padding( + padding: const EdgeInsets.only(left: 20), + child: Markit(data: widget.textContent), + ), + ], + ); + } +} + +class DetailsNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + DetailsNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + return WidgetSpan(child: DetailsWidget(textContent, attributes)); + } +} + +SpanNodeGeneratorWithTag detailsGenerator = SpanNodeGeneratorWithTag( + tag: _detailsTag, + generator: (e, config, visitor) => DetailsNode(e.attributes, e.textContent, config), +); + +class DetailsSyntax extends md.InlineSyntax { + DetailsSyntax() : super(r']*)>([^<]*)(.*?)(.*?)'); + + @override + bool onMatch(md.InlineParser parser, Match match) { + final summary = match[3]!.trim(); + final content = match[4]!.trim(); + + final element = md.Element(_detailsTag, [md.Text(content)]); + element.attributes['summary'] = summary; + element.attributes['content'] = content; + + parser.addNode(element); + return true; + } +} + +class DetailsBlockSyntax extends md.BlockSyntax { + static final _startPattern = RegExp(r'^]*)>$'); + static final _summaryPattern = RegExp(r'^(.*?)$'); + static final _endPattern = RegExp(r'^$'); + + @override + RegExp get pattern => _startPattern; + + @override + bool canParse(md.BlockParser parser) { + final match = pattern.firstMatch(parser.current.content); + return match != null; + } + + @override + md.Node parse(md.BlockParser parser) { + parser.advance(); + + String? summary; + if (!parser.isDone) { + final summaryMatch = _summaryPattern.firstMatch(parser.current.content); + if (summaryMatch != null) { + summary = summaryMatch[1]?.trim(); + parser.advance(); + } + } + + final lines = []; + while (!parser.isDone) { + final line = parser.current.content; + if (_endPattern.hasMatch(line)) { + parser.advance(); + break; + } + lines.add(line); + parser.advance(); + } + + final content = lines.join('\n'); + final element = md.Element(_detailsTag, [md.Text(content)]); + if (summary != null) { + element.attributes['summary'] = summary; + } + element.attributes['content'] = content; + + return element; + } +} diff --git a/lib/widgets/markdown/widgets/function.dart b/lib/widgets/markdown/widgets/function.dart new file mode 100644 index 0000000..83e1efa --- /dev/null +++ b/lib/widgets/markdown/widgets/function.dart @@ -0,0 +1,94 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:flutter/material.dart'; +import 'dart:convert'; + +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'tag.dart'; +import 'package:chatmcp/utils/event_bus.dart'; +import 'package:chatmcp/widgets/expandable_widget.dart'; + +const _functionTag = 'function'; + +class FunctionInlineSyntax extends TagInlineSyntax { + FunctionInlineSyntax() : super(tag: _functionTag); +} + +class FunctionBlockSyntax extends TagBlockSyntax { + FunctionBlockSyntax() : super(tag: _functionTag); +} + +SpanNodeGeneratorWithTag functionGenerator = SpanNodeGeneratorWithTag( + tag: _functionTag, + generator: (e, config, visitor) => FunctionNode(e.attributes, e.textContent, config), +); + +class FunctionNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + FunctionNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + bool isClosed = attributes['closed'] == 'true'; + return WidgetSpan(child: FunctionWidget(textContent, isClosed, attributes)); + } +} + +class FunctionWidget extends StatefulWidget { + final String textContent; + final bool isClosed; + final Map attributes; + + const FunctionWidget(this.textContent, this.isClosed, this.attributes, {super.key}); + + @override + State createState() => _FunctionWidgetState(); +} + +class _FunctionWidgetState extends State { + bool _isExpanded = false; + + @override + Widget build(BuildContext context) { + return ExpandableWidget( + backgroundColor: AppColors.getFunctionBackgroundColor(context), + onExpandChanged: () { + setState(() { + _isExpanded = !_isExpanded; + }); + }, + header: ExpandableRow( + isExpanded: _isExpanded, + children: [ + Icon(Icons.build_outlined, size: 14, color: AppColors.getFunctionIconColor(context)), + Gap(size: 4), + Expanded( + child: Text( + "${widget.attributes['name']}: ${widget.textContent}", + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: AppColors.getFunctionTextColor(context)), + ), + ), + if (!widget.isClosed) + SizedBox(width: 12, height: 12, child: CircularProgressIndicator(color: AppColors.getProgressIndicatorColor(context), strokeWidth: 1.5)) + else if (widget.attributes['done'] != 'true') + IconButton( + padding: EdgeInsets.zero, + constraints: const BoxConstraints(), + icon: Icon(Icons.play_arrow, color: AppColors.getPlayButtonColor(context)), + onPressed: () { + final content = widget.attributes['content'] ?? ''; + final arguments = content.isEmpty ? {} : (jsonDecode(content) as Map).cast(); + emit(RunFunctionEvent(widget.attributes['name'] ?? '', arguments)); + }, + ), + ], + ), + expandedContent: Text(widget.textContent), + ); + } +} diff --git a/lib/widgets/markdown/widgets/function_result.dart b/lib/widgets/markdown/widgets/function_result.dart new file mode 100644 index 0000000..0446b13 --- /dev/null +++ b/lib/widgets/markdown/widgets/function_result.dart @@ -0,0 +1,94 @@ +import 'package:chatmcp/components/widgets/base.dart'; +import 'package:flutter/material.dart'; + +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'tag.dart'; +import 'package:chatmcp/widgets/expandable_widget.dart'; + +const _functionResultTag = 'call_function_result'; + +class FunctionResultInlineSyntax extends TagInlineSyntax { + FunctionResultInlineSyntax() : super(tag: _functionResultTag); +} + +class FunctionResultBlockSyntax extends TagBlockSyntax { + FunctionResultBlockSyntax() : super(tag: _functionResultTag); +} + +SpanNodeGeneratorWithTag functionResultGenerator = SpanNodeGeneratorWithTag( + tag: _functionResultTag, + generator: (e, config, visitor) => FunctionResultNode(e.attributes, e.textContent, config), +); + +class FunctionResultNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + FunctionResultNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + bool isClosed = attributes['closed'] == 'true'; + return WidgetSpan(child: FunctionResultWidget(textContent, isClosed, attributes)); + } +} + +class FunctionResultWidget extends StatefulWidget { + final String textContent; + final bool isClosed; + final Map attributes; + + const FunctionResultWidget(this.textContent, this.isClosed, this.attributes, {super.key}); + + @override + State createState() => _FunctionResultWidgetState(); +} + +class _FunctionResultWidgetState extends State { + bool _isExpanded = false; + + IconData _getToolIcon() { + final toolName = widget.attributes['name']?.toLowerCase() ?? ''; + + if (toolName == 'fetch') { + return Icons.cloud_download; + } else if (toolName.contains('search')) { + return Icons.search; + } else if (toolName.contains('google') || toolName.contains('sheet')) { + return Icons.table_chart; + } + return Icons.build_outlined; + } + + @override + Widget build(BuildContext context) { + return ExpandableWidget( + backgroundColor: AppColors.getFunctionBackgroundColor(context), + onExpandChanged: () { + setState(() { + _isExpanded = !_isExpanded; + }); + }, + header: ExpandableRow( + isExpanded: _isExpanded, + children: [ + Icon(_getToolIcon(), size: 14, color: AppColors.getFunctionIconColor(context)), + Gap(size: 4), + Expanded( + child: Text( + "${widget.attributes['name']} result: ${widget.textContent}", + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: AppColors.getFunctionTextColor(context)), + ), + ), + if (!widget.isClosed) + SizedBox(width: 12, height: 12, child: CircularProgressIndicator(color: AppColors.getProgressIndicatorColor(context), strokeWidth: 1.5)), + ], + ), + expandedContent: Text(widget.textContent), + ); + } +} diff --git a/lib/widgets/markdown/widgets/html_view.dart b/lib/widgets/markdown/widgets/html_view.dart new file mode 100644 index 0000000..d141e18 --- /dev/null +++ b/lib/widgets/markdown/widgets/html_view.dart @@ -0,0 +1,81 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:flutter/foundation.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +class HtmlView extends StatefulWidget { + final String html; + + const HtmlView({super.key, required this.html}); + + @override + State createState() => _HtmlViewState(); +} + +class _HtmlViewState extends State { + double _height = 300; + InAppWebViewController? controller; + bool _hasError = false; + int _retryCount = 0; + static const int maxRetries = 3; + + Key _webViewKey = UniqueKey(); + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } + + Future _initWebView(InAppWebViewController controller) async { + this.controller = controller; + try { + await controller.loadData(data: widget.html); + } catch (e) { + debugPrint('Error loading WebView data: $e'); + _handleError(); + } + } + + void _handleError() { + if (_retryCount < maxRetries) { + _retryCount++; + _resetWebView(); + } else { + setState(() => _hasError = true); + } + } + + void _resetWebView() { + controller?.dispose(); + controller = null; + setState(() => _webViewKey = UniqueKey()); + } + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + if (_hasError) { + return const SizedBox(height: 100, child: Center(child: Text('加载内容失败,请重试'))); + } + + return SizedBox( + height: _height, + child: InAppWebView( + key: _webViewKey, + initialSettings: InAppWebViewSettings(javaScriptEnabled: true, transparentBackground: true, isInspectable: kDebugMode), + onWebViewCreated: (controller) => _initWebView(controller), + onLoadStop: (controller, url) async { + try { + final height = await controller.evaluateJavascript(source: 'document.body.scrollHeight'); + if (mounted) setState(() => _height = (height as num).toDouble()); + } catch (e) { + debugPrint('Error on load stop: $e'); + _handleError(); + } + }, + onCreateWindow: (controller, request) => Future.value(false), + ), + ); + } +} diff --git a/lib/widgets/markdown/widgets/image.dart b/lib/widgets/markdown/widgets/image.dart new file mode 100644 index 0000000..e1ea14e --- /dev/null +++ b/lib/widgets/markdown/widgets/image.dart @@ -0,0 +1,24 @@ +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:markdown/markdown.dart' as m; + +import "package:chatmcp/widgets/cache_image.dart"; + +SpanNodeGeneratorWithTag imageGenerator = SpanNodeGeneratorWithTag(tag: "img", generator: (e, config, visitor) => ImageNode(e, config.img, visitor)); + +class ImageNode extends ElementNode { + ImageNode(this.element, this.imgConfig, this.visitor); + + final m.Element element; + final ImgConfig imgConfig; + final WidgetVisitor visitor; + + @override + InlineSpan build() { + final src = element.attributes['src']; + if (src == null) { + return WidgetSpan(child: Text('')); + } + return WidgetSpan(child: CacheImage(imageUrl: src)); + } +} diff --git a/lib/widgets/markdown/widgets/inline_code.dart b/lib/widgets/markdown/widgets/inline_code.dart new file mode 100644 index 0000000..8315b3c --- /dev/null +++ b/lib/widgets/markdown/widgets/inline_code.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:chatmcp/utils/color.dart'; + +SpanNodeGeneratorWithTag inlineCodeGenerator = SpanNodeGeneratorWithTag( + tag: _code, + generator: (e, config, visitor) => InlineCodeNode(e.attributes, e.textContent, config), +); + +const _code = 'code'; + +class InlineCodeNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + InlineCodeNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + return WidgetSpan( + child: Builder( + builder: (context) => Container( + padding: const EdgeInsets.symmetric(horizontal: 3.0, vertical: 1.0), + decoration: BoxDecoration( + color: AppColors.getThemeColor(context, lightColor: AppColors.grey[200], darkColor: AppColors.grey[800]), + borderRadius: BorderRadius.circular(4.0), + ), + child: Text( + textContent, + style: TextStyle( + fontFamily: 'monospace', + fontSize: config.p.textStyle.fontSize, + color: config.p.textStyle.color ?? AppColors.getThemeTextColor(context), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/markdown/widgets/latex.dart b/lib/widgets/markdown/widgets/latex.dart new file mode 100644 index 0000000..96e6fd1 --- /dev/null +++ b/lib/widgets/markdown/widgets/latex.dart @@ -0,0 +1,126 @@ +import 'package:flutter/material.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:flutter_math_fork/flutter_math.dart'; +import 'package:markdown/markdown.dart' as m; + +SpanNodeGeneratorWithTag latexGenerator = SpanNodeGeneratorWithTag( + tag: _latexTag, + generator: (e, config, visitor) => LatexNode(e.attributes, e.textContent, config), +); + +const _latexTag = 'latex'; + +class LatexSyntax extends m.InlineSyntax { + LatexSyntax() : super(r'(\$\$[\s\S]*?[\s\S]+?[\s\S]*?\$\$)|(\$.+?\$)|(\\\([\s\S]+?\\\))|(\\\[[\s\S]+?\\\])|(\[[\s\S]+?\])'); + + @override + bool onMatch(m.InlineParser parser, Match match) { + final input = match.input; + final matchValue = input.substring(match.start, match.end); + String content = ''; + bool isInline = true; + const blockSyntax = '\$\$'; + const inlineSyntax = '\$'; + + if (matchValue.startsWith(blockSyntax) && matchValue.endsWith(blockSyntax) && (matchValue != blockSyntax) && matchValue.length > 4) { + content = matchValue.substring(2, matchValue.length - 2).trim(); + isInline = false; + } else if (matchValue.startsWith(inlineSyntax) && matchValue.endsWith(inlineSyntax) && matchValue != inlineSyntax && matchValue.length > 2) { + content = matchValue.substring(1, matchValue.length - 1); + } else if (matchValue.startsWith(r'\[') && matchValue.endsWith(r'\]') && matchValue.length > 4) { + content = matchValue.substring(2, matchValue.length - 2); + isInline = false; + } else if (matchValue.startsWith(r'\(') && matchValue.endsWith(r'\)') && matchValue.length > 4) { + content = matchValue.substring(2, matchValue.length - 2); + isInline = true; + } else if (matchValue.startsWith('[') && matchValue.endsWith(']') && matchValue.length > 2) { + content = matchValue.substring(1, matchValue.length - 1); + isInline = false; + } + + m.Element el = m.Element.text(_latexTag, matchValue); + el.attributes['content'] = content; + el.attributes['isInline'] = '$isInline'; + parser.addNode(el); + return true; + } +} + +class LatexBlockSyntax extends m.BlockSyntax { + @override + RegExp get pattern => RegExp(r'^(?:(\${1,2})(?:\n|$))|(?:(?:\\\[(.+)\\\])(?:\n|$))', multiLine: true); + + LatexBlockSyntax() : super(); + + @override + List parseChildLines(m.BlockParser parser) { + final match = pattern.firstMatch(parser.current.content); + if (match?[2] != null) { + parser.advance(); + return [m.Line(match?[2] ?? '')]; + } + + final childLines = []; + parser.advance(); + + while (!parser.isDone) { + final match = pattern.hasMatch(parser.current.content); + if (!match) { + childLines.add(parser.current); + parser.advance(); + } else { + parser.advance(); + break; + } + } + + return childLines; + } + + @override + m.Node parse(m.BlockParser parser) { + final lines = parseChildLines(parser); + final content = lines.map((e) => e.content).join('\n').trim(); + final el = m.Element.text('latex', content); + el.attributes['MathStyle'] = 'display'; + el.attributes['content'] = content; + + return m.Element('p', [el]); + } +} + +class LatexNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + LatexNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + final content = attributes['content'] ?? ''; + final isInline = attributes['isInline'] == 'true'; + final style = parentStyle ?? config.p.textStyle; + + if (content.isEmpty) return TextSpan(style: style, text: textContent); + + return WidgetSpan( + alignment: isInline ? PlaceholderAlignment.middle : PlaceholderAlignment.aboveBaseline, + baseline: TextBaseline.alphabetic, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 800), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Math.tex( + content, + mathStyle: isInline ? MathStyle.text : MathStyle.display, + textStyle: style.copyWith( + fontSize: style.fontSize != null ? (isInline ? style.fontSize : style.fontSize! * 1.2) : (isInline ? 14.0 : 16.8), + ), + onErrorFallback: (error) => Text('LaTeX Error: $error', style: style.copyWith(color: Colors.red)), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/markdown/widgets/link.dart b/lib/widgets/markdown/widgets/link.dart new file mode 100644 index 0000000..564c2be --- /dev/null +++ b/lib/widgets/markdown/widgets/link.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:markdown/markdown.dart' as md; +import 'package:url_launcher/url_launcher.dart'; +import 'package:chatmcp/utils/color.dart'; + +SpanNodeGeneratorWithTag linkGenerator = SpanNodeGeneratorWithTag( + tag: _linkTag, + generator: (e, config, visitor) => MyLinkNode(e.attributes, e.textContent, config), +); + +const _linkTag = 'a'; + +class MyLinkNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + MyLinkNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + final href = attributes['href'] ?? ''; + final content = attributes['content'] ?? href; + return TextSpan( + text: content, + style: TextStyle(color: AppColors.getLinkColor(), decoration: TextDecoration.none), + recognizer: TapGestureRecognizer() + ..onTap = () { + final url = href; + if (url.startsWith("#")) { + return; + } + launchUrl(Uri.parse(url)); + }, + ); + } +} + +class LinkSyntax extends md.InlineSyntax { + LinkSyntax() : super(r'\[([^\]]*)\]\(([^\)]+)\)'); + + @override + bool onMatch(md.InlineParser parser, Match match) { + final element = md.Element.text('a', match.group(1) ?? ''); + element.attributes['href'] = match.group(2) ?? ''; + element.attributes['content'] = match.group(1) ?? ''; + parser.addNode(element); + return true; + } +} diff --git a/lib/widgets/markdown/widgets/mermaid_diagram_view.dart b/lib/widgets/markdown/widgets/mermaid_diagram_view.dart new file mode 100644 index 0000000..7159c50 --- /dev/null +++ b/lib/widgets/markdown/widgets/mermaid_diagram_view.dart @@ -0,0 +1,207 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_inappwebview/flutter_inappwebview.dart'; +import 'package:flutter/foundation.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +// todo: fix this error + +// [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: PlatformException(recreating_view, trying to create an already created view, view id: '0', null) +// #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:646:7) +// #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18) +// +// #2 PlatformViewsService.initAppKitView (package:flutter/src/services/platform_views.dart:294:5) +// +// #3 _DarwinViewState._createNewUiKitView (package:flutter/src/widgets/platform_view.dart:921:36) +// + +class MermaidDiagramView extends StatefulWidget { + final String code; + + const MermaidDiagramView({super.key, required this.code}); + + @override + State createState() => _MermaidDiagramViewState(); +} + +class _MermaidDiagramViewState extends State { + double _height = 100; + InAppWebViewController? controller; + Uint8List? _screenshot; + double _progress = 0; + bool _isLoaded = false; + bool _hasError = false; + int _retryCount = 0; + static const int maxRetries = 3; + + @override + void dispose() { + controller?.dispose(); + super.dispose(); + } + + Future _initWebView(InAppWebViewController controller) async { + this.controller = controller; + try { + await controller.loadData( + data: + ''' + + + + + + + + + +
+
+ ${widget.code} +
+
+ + + ''', + ); + } catch (e) { + debugPrint('Error loading WebView data: $e'); + _handleError(); + } + } + + void _handleError() { + if (_retryCount < maxRetries) { + _retryCount++; + setState(() { + _hasError = false; + }); + } else { + setState(() { + _hasError = true; + }); + } + } + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + if (_hasError) { + return const SizedBox(height: 100, child: Center(child: Text('load diagram failed, please try again'))); + } + + return SizedBox( + height: _height, + child: Stack( + children: [ + InAppWebView( + initialSettings: InAppWebViewSettings(javaScriptEnabled: true, transparentBackground: true, isInspectable: kDebugMode), + onWebViewCreated: _initWebView, + onLoadStop: (controller, url) async { + try { + final height = await controller.evaluateJavascript(source: 'document.body.scrollHeight'); + if (mounted) { + setState(() { + _height = (height as num).toDouble(); + _isLoaded = true; + }); + debugPrint('takeScreenshot'); + await takeScreenshot(); + } + } catch (e) { + debugPrint('Error on load stop: $e'); + _handleError(); + } + }, + onProgressChanged: (controller, progress) { + if (mounted) { + setState(() { + _progress = progress / 100; + }); + } + }, + ), + _progress < 1.0 ? LinearProgressIndicator(value: _progress) : Container(), + if (_screenshot != null) Image.memory(_screenshot!), + ], + ), + ); + } + + Future takeScreenshot() async { + try { + if (!_isLoaded) { + await Future.delayed(const Duration(milliseconds: 1000)); + } + + await Future.delayed(const Duration(milliseconds: 500)); + final result = await controller!.takeScreenshot(); + + if (result != null) { + _screenshot = result; + if (mounted) { + setState(() {}); + } + } + return null; + } catch (e) { + debugPrint('Failed to take screenshot: $e'); + return null; + } + } +} diff --git a/lib/widgets/markdown/widgets/tag.dart b/lib/widgets/markdown/widgets/tag.dart new file mode 100644 index 0000000..d90ad11 --- /dev/null +++ b/lib/widgets/markdown/widgets/tag.dart @@ -0,0 +1,125 @@ +import 'package:flutter/material.dart'; +import 'package:markdown/markdown.dart' as md; + +// 属性匹配正则表达式 +final attributeRegex = RegExp(r'''([\w-]+)\s*=\s*(?:["']([^"'>]+)["']|([^\s>"']+))'''); + +class TagInlineSyntax extends md.InlineSyntax { + final String tag; + + TagInlineSyntax({required this.tag, bool caseSensitive = false}) : super(_getPattern(tag), caseSensitive: caseSensitive); + + static String _getPattern(String tag) => r'<' + tag + r'\s*([^>]*)>\s*([^<]*)(?:]*)>\s*)?'; + + Map _parseAttributes(String attributeString) { + final attributes = {}; + final matches = attributeRegex.allMatches(attributeString); + + for (final match in matches) { + if (match.groupCount >= 1) { + final key = match.group(1) ?? ''; + // 值可能在引号组或无引号组中 + final value = match.group(2) ?? match.group(3) ?? ''; + if (key.isNotEmpty) { + attributes[key] = value; + } + } + } + return attributes; + } + + @override + bool onMatch(md.InlineParser parser, Match match) { + final openingAttributes = _parseAttributes(match[1] ?? ''); + final content = match[2]!.trim(); + final closingAttributes = match[3] != null ? _parseAttributes(match[3]!) : {}; + + final element = md.Element(tag, [md.Text(content)]); + + // 合并开始和结束标签的属性 + element.attributes.addAll(openingAttributes); + element.attributes.addAll(closingAttributes); + + element.attributes['content'] = content; + element.attributes['isInline'] = 'true'; + element.attributes['closed'] = match[3] != null ? 'true' : 'false'; + + parser.addNode(element); + return true; + } +} + +class TagBlockSyntax extends md.BlockSyntax { + final String tag; + + TagBlockSyntax({required this.tag}); + + @protected + RegExp get startPattern => RegExp(r'^<' + tag + r'\s*([^>]*)>\s*$'); + + @protected + RegExp get endPattern => RegExp(r'^]*)>\s*$'); + + @override + RegExp get pattern => startPattern; + + Map _parseAttributes(String attributeString) { + final attributes = {}; + final matches = attributeRegex.allMatches(attributeString); + + for (final match in matches) { + if (match.groupCount >= 1) { + final key = match.group(1) ?? ''; + // 值可能在引号组或无引号组中 + final value = match.group(2) ?? match.group(3) ?? ''; + if (key.isNotEmpty) { + attributes[key] = value; + } + } + } + return attributes; + } + + @override + bool canParse(md.BlockParser parser) { + final match = startPattern.firstMatch(parser.current.content); + return match != null; + } + + @override + md.Node parse(md.BlockParser parser) { + final startMatch = startPattern.firstMatch(parser.current.content); + final openingAttributes = startMatch != null ? _parseAttributes(startMatch[1] ?? '') : {}; + + final lines = []; + parser.advance(); // Skip the opening tag + + bool isClosed = false; + Map closingAttributes = {}; + + while (!parser.isDone) { + final line = parser.current.content; + final endMatch = endPattern.firstMatch(line); + if (endMatch != null) { + isClosed = true; + closingAttributes = _parseAttributes(endMatch[1] ?? ''); + parser.advance(); + break; + } + lines.add(line); + parser.advance(); + } + + final content = lines.join('\n'); + md.Element el = md.Element.text(tag, content); + + // 合并开始和结束标签的属性 + el.attributes.addAll(openingAttributes); + el.attributes.addAll(closingAttributes); + + el.attributes['content'] = content; + el.attributes['isInline'] = 'false'; + el.attributes['closed'] = isClosed ? 'true' : 'false'; + return el; + } +} diff --git a/lib/widgets/markdown/widgets/think.dart b/lib/widgets/markdown/widgets/think.dart new file mode 100644 index 0000000..501fd42 --- /dev/null +++ b/lib/widgets/markdown/widgets/think.dart @@ -0,0 +1,114 @@ +import 'package:flutter/material.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; + +import 'package:markdown_widget/markdown_widget.dart'; +import 'package:chatmcp/utils/color.dart'; +import '../markit_widget.dart'; +import 'tag.dart'; +import 'package:chatmcp/widgets/expandable_widget.dart'; + +class ThinkInlineSyntax extends TagInlineSyntax { + ThinkInlineSyntax() : super(tag: "think"); +} + +class ThinkBlockSyntax extends TagBlockSyntax { + ThinkBlockSyntax() : super(tag: "think"); +} + +SpanNodeGeneratorWithTag thinkGenerator = SpanNodeGeneratorWithTag( + tag: _thinkTag, + generator: (e, config, visitor) => ThinkNode(e.attributes, e.textContent, config), +); + +const _thinkTag = 'think'; + +class ThinkNode extends SpanNode { + final Map attributes; + final String textContent; + final MarkdownConfig config; + + ThinkNode(this.attributes, this.textContent, this.config); + + @override + InlineSpan build() { + bool isClosed = attributes['closed'] == 'true'; + return WidgetSpan(child: ThinkWidget(textContent, isClosed, attributes)); + } +} + +class ThinkWidget extends StatefulWidget { + final String textContent; + final bool isClosed; + final Map attributes; + + const ThinkWidget(this.textContent, this.isClosed, this.attributes, {super.key}); + + @override + State createState() => _ThinkWidgetState(); +} + +class _ThinkWidgetState extends State { + bool _isExpanded = true; + + @override + Widget build(BuildContext context) { + var t = AppLocalizations.of(context)!; + String startTime = widget.attributes['start-time'] ?? ''; + String endTime = widget.attributes['end-time'] ?? ''; + + String prefix = t.thinkingProcess; + String durationTips = ''; + if (startTime.isNotEmpty) { + if (endTime.isEmpty) { + endTime = DateTime.now().toIso8601String(); + prefix = t.thinkingProcessWithDuration; + } else { + prefix = t.thinkingEndWithDuration; + } + Duration duration = DateTime.parse(endTime).difference(DateTime.parse(startTime)); + durationTips = " ${t.seconds(duration.inSeconds)}"; + } + + if (widget.isClosed) { + prefix = t.thinkingEndComplete; + if (durationTips.isNotEmpty) { + prefix += ', '; + } + } + + return ExpandableWidget( + backgroundColor: AppColors.getFunctionBackgroundColor(context), + initiallyExpanded: true, + onExpandChanged: () { + setState(() { + _isExpanded = !_isExpanded; + }); + }, + header: ExpandableRow( + isExpanded: _isExpanded, + children: [ + Icon(Icons.lightbulb_outline, size: 14, color: AppColors.getThinkIconColor(context)), + const SizedBox(width: 4), + Expanded( + child: Text( + "$prefix$durationTips", + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: AppColors.getThinkTextColor(context)), + ), + ), + if (!widget.isClosed) + SizedBox(width: 12, height: 12, child: CircularProgressIndicator(color: AppColors.getProgressIndicatorColor(context), strokeWidth: 1.5)), + ], + ), + expandedContent: Container( + decoration: BoxDecoration( + border: Border(left: BorderSide(color: AppColors.getThinkIconColor(context).withAlpha(128), width: 3)), + ), + padding: const EdgeInsets.only(left: 12), + child: Markit(data: widget.textContent), + ), + contentPadding: const EdgeInsets.only(left: 5), + ); + } +} diff --git a/lib/widgets/tabs.dart b/lib/widgets/tabs.dart new file mode 100644 index 0000000..b42c821 --- /dev/null +++ b/lib/widgets/tabs.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; + +class MyTab { + final String text; + final IconData? icon; + final Widget? child; + + MyTab({required this.text, this.icon, this.child}); +} + +class Tabs extends StatefulWidget { + final List tabs; + final int selectedIndex; + final void Function(int) onTap; + + const Tabs({super.key, required this.tabs, required this.selectedIndex, required this.onTap}); + + @override + State createState() => _TabsState(); +} + +class _TabsState extends State { + int _selectedIndex = 0; + + @override + void initState() { + super.initState(); + _selectedIndex = widget.selectedIndex; + } + + @override + Widget build(BuildContext context) { + return Row( + children: [ + // 左侧选项卡列表 + SizedBox( + width: 200, + child: ListView.builder( + itemCount: widget.tabs.length, + itemBuilder: (context, index) { + return ListTile( + leading: widget.tabs[index].icon != null + ? Icon(widget.tabs[index].icon as IconData, color: _selectedIndex == index ? Colors.blue : Colors.grey) + : null, + title: Text(widget.tabs[index].text ?? '', style: TextStyle(color: _selectedIndex == index ? Colors.blue : Colors.grey)), + selected: _selectedIndex == index, + selectedTileColor: Colors.blue.withAlpha(26), + selectedColor: Colors.blue, + onTap: () { + setState(() { + _selectedIndex = index; + }); + }, + ); + }, + ), + ), + // 右侧配置内容 + Expanded(child: widget.tabs[_selectedIndex].child ?? Container()), + ], + ); + } +} diff --git a/lib/widgets/upgrade.dart b/lib/widgets/upgrade.dart new file mode 100644 index 0000000..26267e7 --- /dev/null +++ b/lib/widgets/upgrade.dart @@ -0,0 +1,363 @@ +import 'package:flutter/foundation.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/utils/platform.dart'; +import 'package:flutter/material.dart'; +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'dart:async'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:chatmcp/widgets/markdown/markit_widget.dart'; + +class UpgradeNotice extends StatefulWidget { + final Duration checkInterval; + final bool showOnlyOnce; + final String owner; + final String repo; + final List enablePlatforms; + final bool showCheckUpdate; + final bool autoCheck; + const UpgradeNotice({ + super.key, + this.checkInterval = const Duration(minutes: 60 * 24), + this.showOnlyOnce = true, + this.owner = 'daodao97', + this.repo = 'chatmcp', + this.enablePlatforms = const ["android", "macos", "windows", "linux"], + this.showCheckUpdate = false, + this.autoCheck = true, + }); + + @override + State createState() => _UpgradeNoticeState(); +} + +class _UpgradeNoticeState extends State { + bool _hasNewVersion = false; + String _newVersion = ''; + String _releaseUrl = ''; + String _releaseNotes = ''; + Timer? _checkTimer; + bool _isChecking = false; + final String _dismissPrefix = '_update_dismissed_'; + @override + void initState() { + super.initState(); + + // 如果启用了自动检查,则延迟初始检查并设置定时器 + if (widget.autoCheck) { + // 延迟初始检查,避免应用启动时的性能影响 + Future.delayed(const Duration(seconds: 3), () { + if (mounted) { + _checkForUpdates(); + } + }); + _checkTimer = Timer.periodic(widget.checkInterval, (_) => _checkForUpdates()); + } + } + + @override + void dispose() { + _checkTimer?.cancel(); + super.dispose(); + } + + Future _checkForUpdates() async { + // 防止多次同时检查 + if (_isChecking) return; + + setState(() { + _isChecking = true; + }); + + try { + // 获取本地存储 + final prefs = await SharedPreferences.getInstance(); + + // 获取当前应用版本 + final packageInfo = await PackageInfo.fromPlatform(); + final currentVersion = packageInfo.version; + debugPrint('Current application version: $currentVersion'); + + // 检查是否已经通知过用户 + final lastNotifiedVersion = prefs.getString('last_shown_version'); + if (widget.showOnlyOnce && lastNotifiedVersion != null && prefs.getBool('$_dismissPrefix$lastNotifiedVersion') == true) { + setState(() { + _isChecking = false; + }); + return; + } + + // 获取GitHub最新release版本 + final apiUrl = 'https://api.github.com/repos/${widget.owner}/${widget.repo}/releases/latest'; + + final response = await http.get(Uri.parse(apiUrl), headers: {'Accept': 'application/vnd.github.v3+json'}).timeout(const Duration(seconds: 10)); + + if (response.statusCode == 200) { + final data = jsonDecode(response.body); + final latestVersion = data['tag_name'].toString().replaceAll(RegExp(r'[^0-9.]'), ''); + final htmlUrl = data['html_url'] as String; + final body = data['body'] as String?; + + debugPrint('Detected latest GitHub version: $latestVersion'); + + if (_isNewerVersion(currentVersion, latestVersion)) { + if (mounted) { + setState(() { + _hasNewVersion = true; + _newVersion = latestVersion; + _releaseUrl = htmlUrl; + _releaseNotes = body ?? ''; + }); + + // 记录最新通知的版本 + await prefs.setString('last_shown_version', latestVersion); + } + } else if (!widget.autoCheck && mounted) { + // 手动检查模式下,如果没有新版本也要显示提示 + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("已是最新版本"), duration: const Duration(seconds: 2))); + } + } else { + debugPrint('GitHub API请求失败,状态码: ${response.statusCode}'); + if (!widget.autoCheck && mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("检查更新失败"), duration: const Duration(seconds: 2))); + } + } + } catch (e) { + debugPrint('检查更新出错: $e'); + if (!widget.autoCheck && mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("检查更新失败"), duration: const Duration(seconds: 2))); + } + } finally { + if (mounted) { + setState(() { + _isChecking = false; + }); + } + } + } + + bool _isNewerVersion(String current, String latest) { + try { + final currentParts = current.split('.').map(int.parse).toList(); + final latestParts = latest.split('.').map(int.parse).toList(); + + // 确保两个列表的长度相同 + while (currentParts.length < 3) { + currentParts.add(0); + } + while (latestParts.length < 3) { + latestParts.add(0); + } + + // 逐位比较版本号 + for (var i = 0; i < 3; i++) { + if (latestParts[i] > currentParts[i]) { + return true; + } else if (latestParts[i] < currentParts[i]) { + return false; + } + } + + return false; + } catch (e) { + debugPrint('版本比较错误: $e'); + return false; + } + } + + Future _openReleaseUrl() async { + if (_releaseUrl.isNotEmpty) { + final url = Uri.parse(_releaseUrl); + try { + if (await canLaunchUrl(url)) { + await launchUrl(url, mode: LaunchMode.externalApplication); + } else { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.openUrlFailed))); + } + } + } catch (e) { + debugPrint('打开URL错误: $e'); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.openUrlFailed))); + } + } + } + } + + void _dismissUpdate() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool('$_dismissPrefix$_newVersion', true); + + if (mounted) { + setState(() { + _hasNewVersion = false; + }); + } + } + + @override + Widget build(BuildContext context) { + if (kIsWeb && !widget.enablePlatforms.contains("web")) { + return const SizedBox.shrink(); + } + if (kIsIOS && !widget.enablePlatforms.contains("ios")) { + return const SizedBox.shrink(); + } + if (kIsAndroid && !widget.enablePlatforms.contains("android")) { + return const SizedBox.shrink(); + } + if (kIsMacOS && !widget.enablePlatforms.contains("macos")) { + return const SizedBox.shrink(); + } + if (kIsWindows && !widget.enablePlatforms.contains("windows")) { + return const SizedBox.shrink(); + } + if (kIsLinux && !widget.enablePlatforms.contains("linux")) { + return const SizedBox.shrink(); + } + + final l10n = AppLocalizations.of(context)!; + final MediaQueryData mediaQuery = MediaQuery.of(context); + final bool isVeryNarrow = mediaQuery.size.width < 400; + final bool isNarrow = mediaQuery.size.width < 600 && !isVeryNarrow; + + // 如果有新版本,显示更新通知 + if (_hasNewVersion) { + return GestureDetector( + onTap: () => _showUpdateDialog(context), + child: Container( + decoration: BoxDecoration( + color: Colors.red[50], + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.red.shade200), + ), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (isVeryNarrow) + const Icon(Icons.new_releases, size: 14, color: Colors.red) + else ...[ + const Icon(Icons.arrow_downward, size: 16, color: Colors.red), + const SizedBox(width: 4), + if (isNarrow) + const Icon(Icons.new_releases, size: 12, color: Colors.red) + else + Flexible( + child: Text( + l10n.newVersionFound(_newVersion), + style: const TextStyle(color: Colors.red, fontSize: 12, fontWeight: FontWeight.bold), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), + ], + ], + ), + ), + ); + } + + // 如果启用手动检查更新,且没有新版本,显示检查更新按钮 + if (widget.showCheckUpdate) { + return GestureDetector( + onTap: _isChecking ? null : () => _checkForUpdates(), + child: Container( + decoration: BoxDecoration( + color: AppColors.getInkIconHoverColor(context), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.grey.shade300), + ), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _isChecking + ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.update, size: 14, color: Colors.grey), + if (!isVeryNarrow) ...[ + const SizedBox(width: 4), + Text( + _isChecking ? l10n.checkingForUpdates : l10n.checkUpdate, + style: TextStyle(color: AppColors.getThemeTextColor(context), fontSize: 12), + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ], + ], + ), + ), + ); + } + + return const SizedBox.shrink(); + } + + Future _showUpdateDialog(BuildContext context) async { + final l10n = AppLocalizations.of(context)!; + + return showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: Row( + children: [ + const Icon(Icons.new_releases, color: Colors.red), + const SizedBox(width: 8), + Text(l10n.newVersionFound(_newVersion)), + ], + ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.newVersionAvailable), + if (_releaseNotes.isNotEmpty) ...[ + const SizedBox(height: 16), + Text(l10n.releaseNotes, style: const TextStyle(fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(4), + border: Border.all(color: Theme.of(context).dividerColor), + ), + child: Markit(data: _releaseNotes, textStyle: const TextStyle(fontSize: 12)), + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () { + _dismissUpdate(); + Navigator.of(context).pop(); + }, + child: Text(l10n.ignoreThisVersion), + ), + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: Text(l10n.updateLater), + ), + FilledButton( + onPressed: () { + _openReleaseUrl(); + Navigator.of(context).pop(); + }, + child: Text(l10n.updateNow), + ), + ], + ); + }, + ); + } +} diff --git a/lib/widgets/upload_menu.dart b/lib/widgets/upload_menu.dart new file mode 100644 index 0000000..576f68b --- /dev/null +++ b/lib/widgets/upload_menu.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:chatmcp/generated/app_localizations.dart'; +import 'package:chatmcp/widgets/ink_icon.dart'; +import 'package:chatmcp/utils/color.dart'; +import 'package:chatmcp/components/widgets/custom_popup.dart'; + +class UploadMenu extends StatelessWidget { + final bool disabled; + final VoidCallback onPickImages; + final VoidCallback onPickFiles; + + const UploadMenu({super.key, required this.disabled, required this.onPickImages, required this.onPickFiles}); + + @override + Widget build(BuildContext context) { + final t = AppLocalizations.of(context)!; + + return BasePopup( + showArrow: true, + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + InkWell( + onTap: disabled + ? null + : () { + Navigator.of(context).pop(); + onPickImages(); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + InkIcon(icon: CupertinoIcons.photo), + const SizedBox(width: 12), + Expanded( + child: Text( + t.selectFromGallery, + style: TextStyle(color: AppColors.getThemeTextColor(context)), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + InkWell( + onTap: disabled + ? null + : () { + Navigator.of(context).pop(); + onPickFiles(); + }, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + InkIcon(icon: CupertinoIcons.doc), + const SizedBox(width: 12), + Expanded( + child: Text( + t.selectFile, + style: TextStyle(color: AppColors.getThemeTextColor(context)), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ], + ), + maxWidth: 200, + child: InkIcon( + icon: CupertinoIcons.plus_app, + onTap: disabled ? null : null, + disabled: disabled, + hoverColor: Theme.of(context).hoverColor, + tooltip: t.uploadFile, + ), + ); + } +} diff --git a/lib/widgets/widgets_to_image/utils.dart b/lib/widgets/widgets_to_image/utils.dart new file mode 100644 index 0000000..60005c4 --- /dev/null +++ b/lib/widgets/widgets_to_image/utils.dart @@ -0,0 +1,26 @@ +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'dart:ui' as ui; + +class WidgetsToImageController { + GlobalKey containerKey = GlobalKey(); + + /// to capture widget to image by GlobalKey in RenderRepaintBoundary + Future capture({double pixelRatio = 6}) async { + try { + /// boundary widget by GlobalKey + RenderRepaintBoundary? boundary = containerKey.currentContext?.findRenderObject() as RenderRepaintBoundary?; + + /// convert boundary to image + final image = await boundary!.toImage(pixelRatio: pixelRatio); + + /// set ImageByteFormat + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + final pngBytes = byteData?.buffer.asUint8List(); + return pngBytes; + } catch (e) { + rethrow; + } + } +} diff --git a/lib/widgets/widgets_to_image/widgets_to_image.dart b/lib/widgets/widgets_to_image/widgets_to_image.dart new file mode 100644 index 0000000..0f2c7cc --- /dev/null +++ b/lib/widgets/widgets_to_image/widgets_to_image.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; +import 'utils.dart'; + +class WidgetsToImage extends StatelessWidget { + final Widget? child; + final WidgetsToImageController controller; + // 添加新的属性 + final bool captureAll; + + const WidgetsToImage({ + super.key, + required this.child, + required this.controller, + this.captureAll = false, // 默认为false + }); + + @override + Widget build(BuildContext context) { + if (!captureAll) { + return RepaintBoundary(key: controller.containerKey, child: child); + } + + // 使用SingleChildScrollView包装,确保所有内容都被渲染 + return RepaintBoundary( + key: controller.containerKey, + child: SingleChildScrollView(physics: const NeverScrollableScrollPhysics(), child: child), + ); + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..1d8843b --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,145 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "chatmcp") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "run.daodao.chatmcp") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..faea87d --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,23 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) screen_retriever_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverLinuxPlugin"); + screen_retriever_linux_plugin_register_with_registrar(screen_retriever_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); + g_autoptr(FlPluginRegistrar) window_manager_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "WindowManagerPlugin"); + window_manager_plugin_register_with_registrar(window_manager_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..4f427dd --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + screen_retriever_linux + url_launcher_linux + window_manager +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/main.cc b/linux/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/my_application.cc b/linux/my_application.cc new file mode 100644 index 0000000..b41daad --- /dev/null +++ b/linux/my_application.cc @@ -0,0 +1,133 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" +#include +using namespace std; +using namespace std::filesystem; + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + const string iconFilename = "assets/logo_256.png"; + path execDir = canonical(read_symlink("/proc/self/exe")).parent_path(); + path iconPath = execDir / "data/flutter_assets" / iconFilename; + g_print("Icon path: %s\n", iconPath.c_str()); + gtk_window_set_icon_from_file(GTK_WINDOW(window), iconPath.c_str(), NULL); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "chatmcp"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "chatmcp"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/linux/my_application.h b/linux/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/linux/packaging/appimage/make_config.yaml b/linux/packaging/appimage/make_config.yaml new file mode 100644 index 0000000..abc1c2b --- /dev/null +++ b/linux/packaging/appimage/make_config.yaml @@ -0,0 +1,39 @@ +display_name: ChatMCP + +icon: assets/logo.png + +keywords: + - ChatMCP + - AI + - Chat + - MCP + +generic_name: AI Chat Application + +categories: + - Office + - Utility + +startup_notify: true + +# You can specify the shared libraries to bundle with your app +# +# fastforge will automatically detect the shared libraries your app depends on, but you can also specify them here. +# +# For SQLite-related libraries, you may need to include the following library files: +include: + - libsqlite3.so.0 + - libsqlite3.so + +# Avoid bundling core system libraries that must be provided by the host. +# Bundling these can introduce newer GLIBC symbol requirements (e.g. 2.36/2.38) +# and break compatibility with Pop!_OS 22.04 (glibc 2.35). +exclude: + - libc.so.6 + - libpthread.so.0 + - libdl.so.2 + - libm.so.6 + - libresolv.so.2 + - librt.so.1 + - libstdc++.so.6 + - libgcc_s.so.1 \ No newline at end of file diff --git a/linux/packaging/deb/make_config.yaml b/linux/packaging/deb/make_config.yaml new file mode 100644 index 0000000..ccc5832 --- /dev/null +++ b/linux/packaging/deb/make_config.yaml @@ -0,0 +1,36 @@ +display_name: ChatMCP +package_name: chatmcp + +maintainer: + name: "daodao97" + email: "" + +priority: optional + +section: x11 + +installed_size: 20000 + +dependencies: + - libgtk-3-0 + - libsqlite3-0 + - libsqlite3-dev + +essential: false + +icon: assets/logo.png + +postuninstall_scripts: + - echo "Sorry to see you go." + +keywords: + - Chat + - AI + +generic_name: Chat Client + +categories: + - Development + - Utility + +startup_notify: true diff --git a/linux/packaging/rpm/make_config.yaml b/linux/packaging/rpm/make_config.yaml new file mode 100644 index 0000000..a6b29d5 --- /dev/null +++ b/linux/packaging/rpm/make_config.yaml @@ -0,0 +1,35 @@ +display_name: ChatMCP +package_name: chatmcp +license: Apache-2.0 license + +maintainer: + name: "" + email: "" + +priority: optional + +section: x11 + +installed_size: 20000 + +dependencies: + - libgtk-3-0 + +essential: false + +icon: assets/logo.png + +postuninstall_scripts: + - echo "Sorry to see you go." + +keywords: + - Chat + - AI + +generic_name: Chat Client + +categories: + - Development + - Utility + +startup_notify: true diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..4b81f9b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..5caa9d1 --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..588c40f --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,34 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import file_picker +import flutter_inappwebview_macos +import mobile_scanner +import network_info_plus +import package_info_plus +import path_provider_foundation +import screen_retriever_macos +import share_plus +import shared_preferences_foundation +import sqflite_darwin +import url_launcher_macos +import window_manager + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin")) + InAppWebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "InAppWebViewFlutterPlugin")) + MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) + NetworkInfoPlusPlugin.register(with: registry.registrar(forPlugin: "NetworkInfoPlusPlugin")) + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin")) + SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) + WindowManagerPlugin.register(with: registry.registrar(forPlugin: "WindowManagerPlugin")) +} diff --git a/macos/Podfile b/macos/Podfile new file mode 100644 index 0000000..c795730 --- /dev/null +++ b/macos/Podfile @@ -0,0 +1,43 @@ +platform :osx, '10.14' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/macos/Podfile.lock b/macos/Podfile.lock new file mode 100644 index 0000000..1b41bd7 --- /dev/null +++ b/macos/Podfile.lock @@ -0,0 +1,99 @@ +PODS: + - file_picker (0.0.1): + - FlutterMacOS + - flutter_inappwebview_macos (0.0.1): + - FlutterMacOS + - OrderedSet (~> 6.0.3) + - FlutterMacOS (1.0.0) + - mobile_scanner (7.0.0): + - Flutter + - FlutterMacOS + - network_info_plus (0.0.1): + - FlutterMacOS + - OrderedSet (6.0.3) + - package_info_plus (0.0.1): + - FlutterMacOS + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - screen_retriever_macos (0.0.1): + - FlutterMacOS + - share_plus (0.0.1): + - FlutterMacOS + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + - sqflite_darwin (0.0.4): + - Flutter + - FlutterMacOS + - url_launcher_macos (0.0.1): + - FlutterMacOS + - window_manager (0.5.0): + - FlutterMacOS + +DEPENDENCIES: + - file_picker (from `Flutter/ephemeral/.symlinks/plugins/file_picker/macos`) + - flutter_inappwebview_macos (from `Flutter/ephemeral/.symlinks/plugins/flutter_inappwebview_macos/macos`) + - FlutterMacOS (from `Flutter/ephemeral`) + - mobile_scanner (from `Flutter/ephemeral/.symlinks/plugins/mobile_scanner/darwin`) + - network_info_plus (from `Flutter/ephemeral/.symlinks/plugins/network_info_plus/macos`) + - package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`) + - path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`) + - screen_retriever_macos (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos`) + - share_plus (from `Flutter/ephemeral/.symlinks/plugins/share_plus/macos`) + - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`) + - sqflite_darwin (from `Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin`) + - url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`) + - window_manager (from `Flutter/ephemeral/.symlinks/plugins/window_manager/macos`) + +SPEC REPOS: + trunk: + - OrderedSet + +EXTERNAL SOURCES: + file_picker: + :path: Flutter/ephemeral/.symlinks/plugins/file_picker/macos + flutter_inappwebview_macos: + :path: Flutter/ephemeral/.symlinks/plugins/flutter_inappwebview_macos/macos + FlutterMacOS: + :path: Flutter/ephemeral + mobile_scanner: + :path: Flutter/ephemeral/.symlinks/plugins/mobile_scanner/darwin + network_info_plus: + :path: Flutter/ephemeral/.symlinks/plugins/network_info_plus/macos + package_info_plus: + :path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos + path_provider_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin + screen_retriever_macos: + :path: Flutter/ephemeral/.symlinks/plugins/screen_retriever_macos/macos + share_plus: + :path: Flutter/ephemeral/.symlinks/plugins/share_plus/macos + shared_preferences_foundation: + :path: Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin + sqflite_darwin: + :path: Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin + url_launcher_macos: + :path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos + window_manager: + :path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos + +SPEC CHECKSUMS: + file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a + flutter_inappwebview_macos: c2d68649f9f8f1831bfcd98d73fd6256366d9d1d + FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 + mobile_scanner: 9157936403f5a0644ca3779a38ff8404c5434a93 + network_info_plus: f52abf61c7a311ecf3ac1b482be8a28908b4604d + OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94 + package_info_plus: f0052d280d17aa382b932f399edf32507174e870 + path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564 + screen_retriever_macos: 452e51764a9e1cdb74b3c541238795849f21557f + share_plus: 510bf0af1a42cd602274b4629920c9649c52f4cc + shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7 + sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0 + url_launcher_macos: 0fba8ddabfc33ce0a9afe7c5fef5aab3d8d2d673 + window_manager: b729e31d38fb04905235df9ea896128991cad99e + +PODFILE CHECKSUM: 236401fc2c932af29a9fcf0e97baeeb2d750d367 + +COCOAPODS: 1.16.2 diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4c0a3f5 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,812 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 61B81AD62C894F0293AB0F15 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA53A1F47E1517B998547581 /* Pods_RunnerTests.framework */; }; + DF482B0799466ED9B9545721 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 04677F4BD6582B74447092DB /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 04677F4BD6582B74447092DB /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 117AC91DEB364BD9686D6FEB /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* chatmcp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = chatmcp.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 5380C913963AF159EF91BDC5 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 88A00C474539623A8A54839F /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + ABC43EA9F3C6447FB024BF89 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + B1E40F40AC4A41CE627AD67D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + B46BFD91F19A432847E0B506 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + EA53A1F47E1517B998547581 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 61B81AD62C894F0293AB0F15 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DF482B0799466ED9B9545721 /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + 5B4AA72F4030B2DE52C551DE /* Pods */, + 7751640111E255CBD30CE25E /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* chatmcp.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + 5B4AA72F4030B2DE52C551DE /* Pods */ = { + isa = PBXGroup; + children = ( + B1E40F40AC4A41CE627AD67D /* Pods-Runner.debug.xcconfig */, + 5380C913963AF159EF91BDC5 /* Pods-Runner.release.xcconfig */, + ABC43EA9F3C6447FB024BF89 /* Pods-Runner.profile.xcconfig */, + 117AC91DEB364BD9686D6FEB /* Pods-RunnerTests.debug.xcconfig */, + 88A00C474539623A8A54839F /* Pods-RunnerTests.release.xcconfig */, + B46BFD91F19A432847E0B506 /* Pods-RunnerTests.profile.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 7751640111E255CBD30CE25E /* Frameworks */ = { + isa = PBXGroup; + children = ( + 04677F4BD6582B74447092DB /* Pods_Runner.framework */, + EA53A1F47E1517B998547581 /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 198AA5E6701386ABD90C551E /* [CP] Check Pods Manifest.lock */, + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 7503EDCB07431C4740D05652 /* [CP] Check Pods Manifest.lock */, + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + 950B03F0C67D9DF3AC415544 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* chatmcp.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 198AA5E6701386ABD90C551E /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; + 7503EDCB07431C4740D05652 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 950B03F0C67D9DF3AC415544 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 117AC91DEB364BD9686D6FEB /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/chatmcp.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/chatmcp"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 88A00C474539623A8A54839F /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/chatmcp.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/chatmcp"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B46BFD91F19A432847E0B506 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/chatmcp.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/chatmcp"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + DEVELOPMENT_TEAM = XNDA84PBM3; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + DEVELOPMENT_TEAM = XNDA84PBM3; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + DEVELOPMENT_TEAM = XNDA84PBM3; + INFOPLIST_FILE = Runner/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = ChatMCP; + INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..1924c97 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..96d3fee --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "info": { + "version": 1, + "author": "xcode" + }, + "images": [ + { + "size": "16x16", + "idiom": "mac", + "filename": "app_icon_16.png", + "scale": "1x" + }, + { + "size": "16x16", + "idiom": "mac", + "filename": "app_icon_32.png", + "scale": "2x" + }, + { + "size": "32x32", + "idiom": "mac", + "filename": "app_icon_32.png", + "scale": "1x" + }, + { + "size": "32x32", + "idiom": "mac", + "filename": "app_icon_64.png", + "scale": "2x" + }, + { + "size": "128x128", + "idiom": "mac", + "filename": "app_icon_128.png", + "scale": "1x" + }, + { + "size": "128x128", + "idiom": "mac", + "filename": "app_icon_256.png", + "scale": "2x" + }, + { + "size": "256x256", + "idiom": "mac", + "filename": "app_icon_256.png", + "scale": "1x" + }, + { + "size": "256x256", + "idiom": "mac", + "filename": "app_icon_512.png", + "scale": "2x" + }, + { + "size": "512x512", + "idiom": "mac", + "filename": "app_icon_512.png", + "scale": "1x" + }, + { + "size": "512x512", + "idiom": "mac", + "filename": "app_icon_1024.png", + "scale": "2x" + } + ] +} \ No newline at end of file diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..6702361 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..53da534 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..7b5b2be Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..489719c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..b60c058 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..ee8ffdd Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..36ba6ca Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@1x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@1x.png new file mode 100644 index 0000000..2459d4d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@1x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@2x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@2x.png new file mode 100644 index 0000000..bcdca0e Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_128@2x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@1x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@1x.png new file mode 100644 index 0000000..59ad12f Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@1x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@2x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@2x.png new file mode 100644 index 0000000..d8e570b Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_16@2x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@1x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@1x.png new file mode 100644 index 0000000..bcdca0e Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@1x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@2x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@2x.png new file mode 100644 index 0000000..a19a11c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_256@2x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@1x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@1x.png new file mode 100644 index 0000000..d8e570b Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@1x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@2x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@2x.png new file mode 100644 index 0000000..d6e833e Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_32@2x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@1x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@1x.png new file mode 100644 index 0000000..a19a11c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@1x.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@2x.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@2x.png new file mode 100644 index 0000000..0216386 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/icon_512@2x.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..b15540d --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,344 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..ee6685a --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,18 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = chatmcp + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = run.daodao.chatmcp + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2024 run.daodao. All rights reserved. + +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig" diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..40d05f4 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,22 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.temporary-exception.files.absolute-path.read-write + + / + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..792c80a --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,41 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + ChatMCP + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSApplicationQueriesSchemes + + http + https + + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSDownloadsFolderUsageDescription + 需要访问下载文件夹来处理文件 + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..da21820 --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,36 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.disable-library-validation + + com.apple.security.files.user-selected.read-write + + com.apple.security.files.downloads.read-write + + com.apple.security.files.user-selected.executable + + com.apple.security.temporary-exception.files.absolute-path.read-write + + / + /opt/homebrew/ + /opt/homebrew/bin/ + + com.apple.security.temporary-exception.mach-lookup.global-name + + com.apple.coresymbolicationd + + com.apple.security.temporary-exception.sbpl + + (allow process-exec) + (allow process-fork) + (allow process-exec-interpreter) + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/build-request.json b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/build-request.json new file mode 100644 index 0000000..851be67 --- /dev/null +++ b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/build-request.json @@ -0,0 +1,27 @@ +{ + "buildCommand" : { + "command" : "build", + "skipDependencies" : false, + "style" : "buildOnly" + }, + "configuredTargets" : [ + + ], + "continueBuildingAfterErrors" : false, + "dependencyScope" : "workspace", + "enableIndexBuildArena" : false, + "hideShellScriptEnvironment" : false, + "parameters" : { + "action" : "build", + "overrides" : { + + } + }, + "qos" : "default", + "schemeCommand" : "launch", + "showNonLoggedProgress" : true, + "useDryRun" : false, + "useImplicitDependencies" : false, + "useLegacyBuildLocations" : false, + "useParallelTargets" : true +} \ No newline at end of file diff --git a/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/description.msgpack b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/description.msgpack new file mode 100644 index 0000000..04fe0d3 Binary files /dev/null and b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/description.msgpack differ diff --git a/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/manifest.json b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/manifest.json new file mode 100644 index 0000000..7391713 --- /dev/null +++ b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/manifest.json @@ -0,0 +1 @@ +{"client":{"name":"basic","version":0,"file-system":"device-agnostic","perform-ownership-analysis":"no"},"targets":{"":[""]},"commands":{"":{"tool":"phony","inputs":[""],"outputs":[""]},"P0:::Gate WorkspaceHeaderMapVFSFilesWritten":{"tool":"phony","inputs":[],"outputs":[""]}}} \ No newline at end of file diff --git a/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/target-graph.txt b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/target-graph.txt new file mode 100644 index 0000000..b83b158 --- /dev/null +++ b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/target-graph.txt @@ -0,0 +1 @@ +Target dependency graph (0 target) \ No newline at end of file diff --git a/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/task-store.msgpack b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/task-store.msgpack new file mode 100644 index 0000000..6cef3fe Binary files /dev/null and b/macos/build/XCBuildData/40bf5d09e75968e9280b6abfebdd44d3.xcbuilddata/task-store.msgpack differ diff --git a/macos/packaging/dmg/make_config.yaml b/macos/packaging/dmg/make_config.yaml new file mode 100644 index 0000000..00dec20 --- /dev/null +++ b/macos/packaging/dmg/make_config.yaml @@ -0,0 +1,10 @@ +title: ChatMcp +contents: + - x: 448 + y: 344 + type: link + path: '/Applications' + - x: 192 + y: 344 + type: file + path: chatmcp.app \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..e9592e8 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1631 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f + url: "https://pub.dev" + source: hosted + version: "85.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d" + url: "https://pub.dev" + source: hosted + version: "7.7.1" + archive: + dependency: transitive + description: + name: archive + sha256: "2fde1607386ab523f7a36bb3e7edb43bd58e6edaf2ffb29d8a6d578b297fdbbd" + url: "https://pub.dev" + source: hosted + version: "4.0.7" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + bot_toast: + dependency: "direct main" + description: + name: bot_toast + sha256: "6b93030a99a98335b8827ecd83021e92e885ffc61d261d3825ffdecdd17f3bdf" + url: "https://pub.dev" + source: hosted + version: "4.1.3" + build: + dependency: transitive + description: + name: build + sha256: "7d95cbbb1526ab5ae977df9b4cc660963b9b27f6d1075c0b34653868911385e4" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + build_config: + dependency: transitive + description: + name: build_config + sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "8e928697a82be082206edb0b9c99c5a4ad6bc31c9e9b8b2f291ae65cd4a25daa" + url: "https://pub.dev" + source: hosted + version: "4.0.4" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: "38c9c339333a09b090a638849a4c56e70a404c6bdd3b511493addfbc113b60c2" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: b971d4a1c789eba7be3e6fe6ce5e5b50fd3719e3cb485b3fad6d04358304351d + url: "https://pub.dev" + source: hosted + version: "2.6.0" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: c04e612ca801cd0928ccdb891c263a2b1391cb27940a5ea5afcf9ba894de5d62 + url: "https://pub.dev" + source: hosted + version: "9.2.0" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: ba95c961bafcd8686d1cf63be864eb59447e795e124d98d6a27d91fcd13602fb + url: "https://pub.dev" + source: hosted + version: "8.11.1" + cached_network_image: + dependency: "direct main" + description: + name: cached_network_image + sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + cached_network_image_platform_interface: + dependency: transitive + description: + name: cached_network_image_platform_interface + sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829" + url: "https://pub.dev" + source: hosted + version: "4.1.1" + cached_network_image_web: + dependency: transitive + description: + name: cached_network_image_web + sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" + url: "https://pub.dev" + source: hosted + version: "4.10.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + url: "https://pub.dev" + source: hosted + version: "1.15.0" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" + url: "https://pub.dev" + source: hosted + version: "0.3.4+2" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "8a0e5fba27e8ee025d2ffb4ee820b4e6e2cf5e4246a6b1a477eb66866947e0bb" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + dbus: + dependency: transitive + description: + name: dbus + sha256: "79e0c23480ff85dc68de79e2cd6334add97e48f7f4865d17686dd6ea81a47e8c" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + dev_build: + dependency: transitive + description: + name: dev_build + sha256: fda8a54458b2a873a84e0cd1513f4323a1fb0599ed5455245359bc0398bad9ee + url: "https://pub.dev" + source: hosted + version: "1.1.2+11" + dio: + dependency: "direct main" + description: + name: dio + sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9 + url: "https://pub.dev" + source: hosted + version: "5.9.0" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + event_bus: + dependency: "direct main" + description: + name: event_bus + sha256: "1a55e97923769c286d295240048fc180e7b0768902c3c2e869fe059aafa15304" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + eventflux: + dependency: "direct main" + description: + name: eventflux + sha256: f6da4534c84b11531ae84546fbd0202b743ca7ef6bc92c84c0f50d7a1c487a12 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: "97a943524074a1e8e858aa154d09e38a4168a9ad765d6cac66606fd906b86875" + url: "https://pub.dev" + source: hosted + version: "10.2.2" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_cache_manager: + dependency: "direct main" + description: + name: flutter_cache_manager + sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + flutter_client_sse: + dependency: "direct main" + description: + name: flutter_client_sse + sha256: "4ce0297206473dfc064b255fe086713240002e149f52519bd48c21423e4aa5d2" + url: "https://pub.dev" + source: hosted + version: "2.0.3" + flutter_form_builder: + dependency: "direct main" + description: + name: flutter_form_builder + sha256: db01493da4ef0f9ca1b2367fd1653569e933052eb06d6fbd944be97c76764fb8 + url: "https://pub.dev" + source: hosted + version: "10.1.0" + flutter_highlight: + dependency: "direct main" + description: + name: flutter_highlight + sha256: "7b96333867aa07e122e245c033b8ad622e4e3a42a1a2372cbb098a2541d8782c" + url: "https://pub.dev" + source: hosted + version: "0.7.0" + flutter_inappwebview: + dependency: "direct main" + description: + name: flutter_inappwebview + sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + flutter_inappwebview_android: + dependency: transitive + description: + name: flutter_inappwebview_android + sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" + url: "https://pub.dev" + source: hosted + version: "1.1.3" + flutter_inappwebview_internal_annotations: + dependency: transitive + description: + name: flutter_inappwebview_internal_annotations + sha256: "787171d43f8af67864740b6f04166c13190aa74a1468a1f1f1e9ee5b90c359cd" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + flutter_inappwebview_ios: + dependency: transitive + description: + name: flutter_inappwebview_ios + sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_macos: + dependency: transitive + description: + name: flutter_inappwebview_macos + sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_platform_interface: + dependency: transitive + description: + name: flutter_inappwebview_platform_interface + sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 + url: "https://pub.dev" + source: hosted + version: "1.3.0+1" + flutter_inappwebview_web: + dependency: transitive + description: + name: flutter_inappwebview_web + sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_windows: + dependency: transitive + description: + name: flutter_inappwebview_windows + sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + flutter_keyboard_visibility: + dependency: "direct main" + description: + name: flutter_keyboard_visibility + sha256: "98664be7be0e3ffca00de50f7f6a287ab62c763fc8c762e0a21584584a3ff4f8" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_keyboard_visibility_linux: + dependency: transitive + description: + name: flutter_keyboard_visibility_linux + sha256: "6fba7cd9bb033b6ddd8c2beb4c99ad02d728f1e6e6d9b9446667398b2ac39f08" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_macos: + dependency: transitive + description: + name: flutter_keyboard_visibility_macos + sha256: c5c49b16fff453dfdafdc16f26bdd8fb8d55812a1d50b0ce25fc8d9f2e53d086 + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_keyboard_visibility_platform_interface: + dependency: transitive + description: + name: flutter_keyboard_visibility_platform_interface + sha256: e43a89845873f7be10cb3884345ceb9aebf00a659f479d1c8f4293fcb37022a4 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_keyboard_visibility_web: + dependency: transitive + description: + name: flutter_keyboard_visibility_web + sha256: d3771a2e752880c79203f8d80658401d0c998e4183edca05a149f5098ce6e3d1 + url: "https://pub.dev" + source: hosted + version: "2.0.0" + flutter_keyboard_visibility_windows: + dependency: transitive + description: + name: flutter_keyboard_visibility_windows + sha256: fc4b0f0b6be9b93ae527f3d527fb56ee2d918cd88bbca438c478af7bcfd0ef73 + url: "https://pub.dev" + source: hosted + version: "1.0.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" + url: "https://pub.dev" + source: hosted + version: "0.14.4" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_math_fork: + dependency: "direct main" + description: + name: flutter_math_fork + sha256: "6d5f2f1aa57ae539ffb0a04bb39d2da67af74601d685a161aff7ce5bda5fa407" + url: "https://pub.dev" + source: hosted + version: "0.7.4" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "6382ce712ff69b0f719640ce957559dde459e55ecd433c767e06d139ddf16cab" + url: "https://pub.dev" + source: hosted + version: "2.0.29" + flutter_popup: + dependency: "direct main" + description: + name: flutter_popup + sha256: "08e554be1173f4e7bb5eda2ae2e5addd565873026a3ac9b64c38ea86dfd4dc9d" + url: "https://pub.dev" + source: hosted + version: "3.3.9" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: cd57f7969b4679317c17af6fd16ee233c1e60a82ed209d8a475c54fd6fd6f845 + url: "https://pub.dev" + source: hosted + version: "2.2.0" + flutter_switch: + dependency: "direct main" + description: + name: flutter_switch + sha256: b91477f926bba135d2d203d7b24367492662d8d9c3aa6adb960b14c1087d3c41 + url: "https://pub.dev" + source: hosted + version: "0.3.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.dev" + source: hosted + version: "2.1.3" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + highlight: + dependency: transitive + description: + name: highlight + sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21" + url: "https://pub.dev" + source: hosted + version: "0.7.0" + html: + dependency: transitive + description: + name: html + sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" + url: "https://pub.dev" + source: hosted + version: "0.15.6" + html2md: + dependency: "direct main" + description: + name: html2md + sha256: "465cf8ffa1b510fe0e97941579bf5b22e2d575f2cecb500a9c0254efe33a8036" + url: "https://pub.dev" + source: hosted + version: "1.3.2" + http: + dependency: "direct main" + description: + name: http + sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007 + url: "https://pub.dev" + source: hosted + version: "1.5.0" + http_methods: + dependency: transitive + description: + name: http_methods + sha256: "6bccce8f1ec7b5d701e7921dca35e202d425b57e317ba1a37f2638590e29e566" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "4e973fcf4caae1a4be2fa0a13157aa38a8f9cb049db6529aa00b4d71abc4d928" + url: "https://pub.dev" + source: hosted + version: "4.5.4" + intl: + dependency: "direct main" + description: + name: intl + sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5" + url: "https://pub.dev" + source: hosted + version: "0.20.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + json_serializable: + dependency: "direct main" + description: + name: json_serializable + sha256: ce2cf974ccdee13be2a510832d7fba0b94b364e0b0395dee42abaa51b855be27 + url: "https://pub.dev" + source: hosted + version: "6.10.0" + keyboard_dismisser: + dependency: "direct main" + description: + name: keyboard_dismisser + sha256: f67e032581fc3dd1f77e1cb54c421b089e015d122aeba2490ba001cfcc42a181 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + url: "https://pub.dev" + source: hosted + version: "10.0.9" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: a5e2b223cb7c9c8efdc663ef484fdd95bb243bff242ef5b13e26883547fce9a0 + url: "https://pub.dev" + source: hosted + version: "6.0.0" + logging: + dependency: "direct main" + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + markdown: + dependency: "direct main" + description: + name: markdown + sha256: "935e23e1ff3bc02d390bad4d4be001208ee92cc217cb5b5a6c19bc14aaa318c1" + url: "https://pub.dev" + source: hosted + version: "7.3.0" + markdown_widget: + dependency: "direct main" + description: + name: markdown_widget + sha256: b52c13d3ee4d0e60c812e15b0593f142a3b8a2003cde1babb271d001a1dbdc1c + url: "https://pub.dev" + source: hosted + version: "2.3.2+8" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: "direct main" + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + mobile_scanner: + dependency: "direct main" + description: + name: mobile_scanner + sha256: "54005bdea7052d792d35b4fef0f84ec5ddc3a844b250ecd48dc192fb9b4ebc95" + url: "https://pub.dev" + source: hosted + version: "7.0.1" + mockito: + dependency: "direct dev" + description: + name: mockito + sha256: "2314cbe9165bcd16106513df9cf3c3224713087f09723b128928dc11a4379f99" + url: "https://pub.dev" + source: hosted + version: "5.5.0" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + network_info_plus: + dependency: "direct main" + description: + name: network_info_plus + sha256: "5bd4b86e28fed5ed4e6ac7764133c031dfb7d3f46aa2a81b46f55038aa78ecc0" + url: "https://pub.dev" + source: hosted + version: "5.0.3" + network_info_plus_platform_interface: + dependency: transitive + description: + name: network_info_plus_platform_interface + sha256: "7e7496a8a9d8136859b8881affc613c4a21304afeb6c324bcefc4bd0aff6b94b" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + nm: + dependency: transitive + description: + name: nm + sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" + url: "https://pub.dev" + source: hosted + version: "0.5.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + octo_image: + dependency: transitive + description: + name: octo_image + sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.dev" + source: hosted + version: "2.2.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "7976bfe4c583170d6cdc7077e3237560b364149fcd268b5f53d95a991963b191" + url: "https://pub.dev" + source: hosted + version: "8.3.0" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: "6c935fb612dff8e3cc9632c2b301720c77450a126114126ffaafe28d2e87956c" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: d0d310befe2c8ab9e7f393288ccbb11b60c019c6b5afc21973eeee4dda2b35e9 + url: "https://pub.dev" + source: hosted + version: "2.2.17" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "07c8f0b1913bcde1ff0d26e57ace2f3012ccbf2b204e070290dad3bb22797646" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + posix: + dependency: transitive + description: + name: posix + sha256: "6323a5b0fa688b6a010df4905a56b00181479e6d10534cecfecede2aa55add61" + url: "https://pub.dev" + source: hosted + version: "6.0.3" + process_run: + dependency: transitive + description: + name: process_run + sha256: "6ec839cdd3e6de4685318e7686cd4abb523c3d3a55af0e8d32a12ae19bc66622" + url: "https://pub.dev" + source: hosted + version: "1.2.4" + provider: + dependency: "direct main" + description: + name: provider + sha256: "4abbd070a04e9ddc287673bf5a030c7ca8b685ff70218720abab8b092f53dd84" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + qr_flutter: + dependency: "direct main" + description: + name: qr_flutter + sha256: "5095f0fc6e3f71d08adef8feccc8cea4f12eec18a2e31c2e8d82cb6019f4b097" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + screen_retriever: + dependency: transitive + description: + name: screen_retriever + sha256: "570dbc8e4f70bac451e0efc9c9bb19fa2d6799a11e6ef04f946d7886d2e23d0c" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + screen_retriever_linux: + dependency: transitive + description: + name: screen_retriever_linux + sha256: f7f8120c92ef0784e58491ab664d01efda79a922b025ff286e29aa123ea3dd18 + url: "https://pub.dev" + source: hosted + version: "0.2.0" + screen_retriever_macos: + dependency: transitive + description: + name: screen_retriever_macos + sha256: "71f956e65c97315dd661d71f828708bd97b6d358e776f1a30d5aa7d22d78a149" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + screen_retriever_platform_interface: + dependency: transitive + description: + name: screen_retriever_platform_interface + sha256: ee197f4581ff0d5608587819af40490748e1e39e648d7680ecf95c05197240c0 + url: "https://pub.dev" + source: hosted + version: "0.2.0" + screen_retriever_windows: + dependency: transitive + description: + name: screen_retriever_windows + sha256: "449ee257f03ca98a57288ee526a301a430a344a161f9202b4fcc38576716fe13" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + screenshot: + dependency: "direct main" + description: + name: screenshot + sha256: "63817697a7835e6ce82add4228e15d233b74d42975c143ad8cfe07009fab866b" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + scroll_to_index: + dependency: transitive + description: + name: scroll_to_index + sha256: b707546e7500d9f070d63e5acf74fd437ec7eeeb68d3412ef7b0afada0b4f176 + url: "https://pub.dev" + source: hosted + version: "3.0.1" + share_plus: + dependency: "direct main" + description: + name: share_plus + sha256: b2961506569e28948d75ec346c28775bb111986bb69dc6a20754a457e3d97fa0 + url: "https://pub.dev" + source: hosted + version: "11.0.0" + share_plus_platform_interface: + dependency: transitive + description: + name: share_plus_platform_interface + sha256: "1032d392bc5d2095a77447a805aa3f804d2ae6a4d5eef5e6ebb3bd94c1bc19ef" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5" + url: "https://pub.dev" + source: hosted + version: "2.5.3" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "5bcf0772a761b04f8c6bf814721713de6f3e5d9d89caf8d3fe031b02a342379e" + url: "https://pub.dev" + source: hosted + version: "2.4.11" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: "direct main" + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_cors_headers: + dependency: "direct main" + description: + name: shelf_cors_headers + sha256: a127c80f99bbef3474293db67a7608e3a0f1f0fcdb171dad77fa9bd2cd123ae4 + url: "https://pub.dev" + source: hosted + version: "0.1.5" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_router: + dependency: "direct main" + description: + name: shelf_router + sha256: f5e5d492440a7fb165fe1e2e1a623f31f734d3370900070b2b1e0d0428d59864 + url: "https://pub.dev" + source: hosted + version: "1.1.4" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: fc787b1f89ceac9580c3616f899c9a447413cbdac1df071302127764c023a134 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + source_helper: + dependency: transitive + description: + name: source_helper + sha256: "4f81479fe5194a622cdd1713fe1ecb683a6e6c85cd8cec8e2e35ee5ab3fdf2a1" + url: "https://pub.dev" + source: hosted + version: "1.3.6" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + url: "https://pub.dev" + source: hosted + version: "0.10.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + sprintf: + dependency: transitive + description: + name: sprintf + sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + sqflite: + dependency: "direct main" + description: + name: sqflite + sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "2b3070c5fa881839f8b402ee4a39c1b4d561704d4ebbbcfb808a119bc2a1701b" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + sqflite_common_ffi: + dependency: "direct main" + description: + name: sqflite_common_ffi + sha256: "9faa2fedc5385ef238ce772589f7718c24cdddd27419b609bb9c6f703ea27988" + url: "https://pub.dev" + source: hosted + version: "2.3.6" + sqflite_common_ffi_web: + dependency: "direct main" + description: + name: sqflite_common_ffi_web + sha256: "33495e9172c958d907c48fd43fbea0b9c0a2ec2e36a548ebd07672fde61b6497" + url: "https://pub.dev" + source: hosted + version: "1.0.1+1" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + sqlite3: + dependency: transitive + description: + name: sqlite3 + sha256: f393d92c71bdcc118d6203d07c991b9be0f84b1a6f89dd4f7eed348131329924 + url: "https://pub.dev" + source: hosted + version: "2.9.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: "direct main" + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test: + dependency: "direct dev" + description: + name: test + sha256: "301b213cd241ca982e9ba50266bd3f5bd1ea33f1455554c5abb85d1be0e2d87e" + url: "https://pub.dev" + source: hosted + version: "1.25.15" + test_api: + dependency: transitive + description: + name: test_api + sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + test_core: + dependency: transitive + description: + name: test_core + sha256: "84d17c3486c8dfdbe5e12a50c8ae176d15e2a771b96909a9442b40173649ccaa" + url: "https://pub.dev" + source: hosted + version: "0.6.8" + timing: + dependency: transitive + description: + name: timing + sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + tuple: + dependency: transitive + description: + name: tuple + sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151 + url: "https://pub.dev" + source: hosted + version: "2.0.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: f6a7e5c4835bb4e3026a04793a4199ca2d14c739ec378fdfe23fc8075d0439f8 + url: "https://pub.dev" + source: hosted + version: "6.3.2" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "0aedad096a85b49df2e4725fa32118f9fa580f3b14af7a2d2221896a02cd5656" + url: "https://pub.dev" + source: hosted + version: "6.3.17" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "7f2022359d4c099eea7df3fdf739f7d3d3b9faf3166fb1dd390775176e0b76cb" + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "4e9ba368772369e3e08f231d2301b4ef72b9ff87c31192ef471b380ef29a4935" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "17ba2000b847f334f16626a574c702b196723af2a289e7a93ffcb79acff855c2" + url: "https://pub.dev" + source: hosted + version: "3.2.2" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "4bd2b7b4dc4d4d0b94e5babfffbca8eac1a126c7f3d6ecbc1a11013faa3abba2" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "3284b6d2ac454cf34f114e1d3319866fdd1e19cdc329999057e44ffe936cfa77" + url: "https://pub.dev" + source: hosted + version: "3.1.4" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff + url: "https://pub.dev" + source: hosted + version: "4.5.1" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6 + url: "https://pub.dev" + source: hosted + version: "1.1.19" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "557a315b7d2a6dbb0aaaff84d857967ce6bdc96a63dc6ee2a57ce5a6ee5d3331" + url: "https://pub.dev" + source: hosted + version: "1.1.17" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + visibility_detector: + dependency: transitive + description: + name: visibility_detector + sha256: dd5cc11e13494f432d15939c3aa8ae76844c42b723398643ce9addb88a5ed420 + url: "https://pub.dev" + source: hosted + version: "0.4.0+2" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 + url: "https://pub.dev" + source: hosted + version: "15.0.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "0b7fd4a0bbc4b92641dbf20adfd7e3fd1398fe17102d94b674234563e110088a" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: "66814138c3562338d05613a6e368ed8cfb237ad6d64a9e9334be3f309acfca03" + url: "https://pub.dev" + source: hosted + version: "5.14.0" + window_manager: + dependency: "direct main" + description: + name: window_manager + sha256: "7eb6d6c4164ec08e1bf978d6e733f3cebe792e2a23fb07cbca25c2872bfdbdcd" + url: "https://pub.dev" + source: hosted + version: "0.5.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 + url: "https://pub.dev" + source: hosted + version: "6.5.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.8.1 <4.0.0" + flutter: ">=3.32.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..c45b16b --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,139 @@ +name: chatmcp +description: "AI Chat with Mcp" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: "none" # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 0.0.76 + +environment: + sdk: ^3.8.1 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + intl: ^0.20.2 + shared_preferences: ^2.2.2 + http: ^1.2.0 + eventflux: ^2.2.1 + crypto: ^3.0.3 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + synchronized: ^3.3.0+3 + provider: ^6.1.2 + logging: ^1.2.0 + path_provider: ^2.1.5 + path: ^1.9.0 + sqflite: ^2.3.0 + sqflite_common_ffi: ^2.3.2 + markdown: ^7.3.0 + url_launcher: ^6.3.1 + window_manager: ^0.5.0 + flutter_keyboard_visibility: ^6.0.0 + file_picker: ^10.1.9 + mime: ^2.0.0 + uuid: ^4.5.1 + keyboard_dismisser: ^3.0.0 + markdown_widget: ^2.3.2+6 + flutter_math_fork: ^0.7.3 + flutter_highlight: ^0.7.0 + share_plus: ^11.0.0 + screenshot: ^3.0.0 + flutter_inappwebview: ^6.1.5 + cached_network_image: ^3.4.1 + html2md: ^1.3.2 + event_bus: ^2.0.1 + flutter_cache_manager: ^3.3.1 + flutter_svg: ^2.0.17 + json_serializable: ^6.9.5 + flutter_switch: ^0.3.2 + flutter_popup: ^3.3.4 + flutter_form_builder: ^10.0.1 + flutter_client_sse: ^2.0.3 + package_info_plus: ^8.3.0 + bot_toast: ^4.1.3 + sqflite_common_ffi_web: ^1.0.0 + # 网络服务相关 + shelf: ^1.4.1 # HTTP服务器 + shelf_router: ^1.1.4 # 路由 + shelf_cors_headers: ^0.1.5 # CORS支持 + network_info_plus: ^5.0.0 # 获取网络信息 + qr_flutter: ^4.1.0 # 二维码生成 + # qr_code_scanner: ^1.0.1 # 二维码扫描 - 已弃用,有namespace问题 + mobile_scanner: ^7.0.1 # 替代qr_code_scanner的现代二维码扫描器 + dio: ^5.4.0 # HTTP客户端 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + + test: ^1.24.0 + mockito: ^5.4.0 + build_runner: ^2.4.0 + flutter_launcher_icons: ^0.14.3 + + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + generate: true + uses-material-design: true + assets: + - assets/mcp_server.json + - assets/logo.png + - assets/sandbox/ + - assets/logo/ + - assets/logo_256.png + +flutter_launcher_icons: + remove_alpha_ios: true + android: "launcher_icon" + ios: true + image_path: "assets/logo.png" + min_sdk_android: 21 # Android最低SDK版本 + web: + generate: true + image_path: "assets/logo.png" + background_color: "#hexcode" + theme_color: "#hexcode" + windows: + generate: true + image_path: "assets/logo.png" + icon_size: 48 # 可选,默认为48 + macos: + generate: true + image_path: "assets/logo.png" + linux: + generate: true + image_path: "assets/logo_256.png" diff --git a/scripts/build_summary.sh b/scripts/build_summary.sh new file mode 100644 index 0000000..bf8f524 --- /dev/null +++ b/scripts/build_summary.sh @@ -0,0 +1,100 @@ +#!/bin/bash + +# 脚本用于显示Android构建结果摘要 +# 使用方法: ./scripts/build_summary.sh + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo -e "${BLUE}ChatMcp Android 构建结果摘要${NC}" +echo "==============================================" + +# 检查APK文件 +APK_PATH="build/app/outputs/flutter-apk/app-release.apk" +if [ -f "$APK_PATH" ]; then + echo -e "${GREEN}✅ Release APK 已生成${NC}" + echo " 文件路径: $APK_PATH" + echo " 文件大小: $(ls -lh "$APK_PATH" | awk '{print $5}')" + echo " 修改时间: $(ls -l "$APK_PATH" | awk '{print $6, $7, $8}')" + + # 检查签名 + if jarsigner -verify "$APK_PATH" &>/dev/null; then + echo -e "${GREEN} ✅ APK 签名验证成功${NC}" + else + echo -e "${YELLOW} ⚠️ APK 使用现代签名方案(v2/v3)${NC}" + fi +else + echo -e "${RED}❌ Release APK 未找到${NC}" +fi + +echo + +# 检查AAB文件 +AAB_PATH="build/app/outputs/bundle/release/app-release.aab" +if [ -f "$AAB_PATH" ]; then + echo -e "${GREEN}✅ Release AAB 已生成${NC}" + echo " 文件路径: $AAB_PATH" + echo " 文件大小: $(ls -lh "$AAB_PATH" | awk '{print $5}')" + echo " 修改时间: $(ls -l "$AAB_PATH" | awk '{print $6, $7, $8}')" +else + echo -e "${RED}❌ Release AAB 未找到${NC}" +fi + +echo + +# 检查分架构APK +echo -e "${YELLOW}分架构 APK 文件:${NC}" +SPLIT_APK_DIR="build/app/outputs/flutter-apk" +if [ -d "$SPLIT_APK_DIR" ]; then + for arch in arm64-v8a armeabi-v7a x86_64; do + SPLIT_APK="$SPLIT_APK_DIR/app-$arch-release.apk" + if [ -f "$SPLIT_APK" ]; then + echo -e "${GREEN} ✅ $arch: $(ls -lh "$SPLIT_APK" | awk '{print $5}')${NC}" + else + echo -e "${YELLOW} ⚠️ $arch: 未生成${NC}" + fi + done +else + echo -e "${YELLOW} ⚠️ 分架构APK目录不存在${NC}" +fi + +echo + +# 显示签名信息 +if [ -f "android/signing.env" ]; then + echo -e "${BLUE}签名配置信息:${NC}" + source android/signing.env + echo " 密钥库: $SIGNING_STORE_PATH" + echo " 别名: $SIGNING_KEY_ALIAS" + + KEYSTORE_FULL_PATH="android/app/$SIGNING_STORE_PATH" + if [ -f "$KEYSTORE_FULL_PATH" ] && [ -n "$SIGNING_STORE_PASSWORD" ]; then + echo -e "${GREEN} ✅ 密钥库验证成功${NC}" + + # 显示证书有效期 + VALIDITY=$(keytool -list -v -keystore "$KEYSTORE_FULL_PATH" -storepass "$SIGNING_STORE_PASSWORD" -alias "$SIGNING_KEY_ALIAS" 2>/dev/null | grep "有效期从\|Valid from" | head -1) + if [ -n "$VALIDITY" ]; then + echo " 证书有效期: $VALIDITY" + fi + fi +else + echo -e "${YELLOW}⚠️ 未找到签名配置${NC}" +fi + +echo + +# 构建建议 +echo -e "${BLUE}发布建议:${NC}" +echo "1. APK 文件适用于直接安装和第三方应用商店" +echo "2. AAB 文件适用于 Google Play Store(推荐)" +echo "3. 分架构 APK 可以减少下载大小" +echo "4. 请妥善保管签名密钥,用于后续版本更新" + +echo +echo -e "${GREEN}构建完成!${NC}" \ No newline at end of file diff --git a/scripts/create_keystore.sh b/scripts/create_keystore.sh new file mode 100644 index 0000000..3d3b64a --- /dev/null +++ b/scripts/create_keystore.sh @@ -0,0 +1,145 @@ +#!/bin/bash + +# 脚本用于创建Android应用签名密钥 +# 使用方法: ./scripts/create_keystore.sh + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +echo -e "${GREEN}ChatMcp Android 签名密钥生成工具${NC}" +echo "==============================================" + +# 检查是否安装了keytool +if ! command -v keytool &> /dev/null; then + echo -e "${RED}错误: keytool 未找到。请确保已安装 Java JDK。${NC}" + exit 1 +fi + +# 默认值 +DEFAULT_KEYSTORE_NAME="chatmcp-release-key.jks" +DEFAULT_KEY_ALIAS="chatmcp" +DEFAULT_VALIDITY="10000" + +# 获取用户输入 +echo -e "${YELLOW}请输入以下信息(直接回车使用默认值):${NC}" +echo + +read -p "密钥库文件名 [${DEFAULT_KEYSTORE_NAME}]: " KEYSTORE_NAME +KEYSTORE_NAME=${KEYSTORE_NAME:-$DEFAULT_KEYSTORE_NAME} + +read -p "密钥别名 [${DEFAULT_KEY_ALIAS}]: " KEY_ALIAS +KEY_ALIAS=${KEY_ALIAS:-$DEFAULT_KEY_ALIAS} + +read -p "有效期(天数)[${DEFAULT_VALIDITY}]: " VALIDITY +VALIDITY=${VALIDITY:-$DEFAULT_VALIDITY} + +read -s -p "密钥库密码: " STORE_PASSWORD +echo +read -s -p "确认密钥库密码: " STORE_PASSWORD_CONFIRM +echo + +if [ "$STORE_PASSWORD" != "$STORE_PASSWORD_CONFIRM" ]; then + echo -e "${RED}错误: 密码不匹配!${NC}" + exit 1 +fi + +read -s -p "密钥密码 [与密钥库密码相同]: " KEY_PASSWORD +echo +if [ -z "$KEY_PASSWORD" ]; then + KEY_PASSWORD=$STORE_PASSWORD +fi + +echo +echo -e "${YELLOW}请输入证书信息:${NC}" +read -p "您的姓名 [ChatMcp]: " CN +CN=${CN:-"ChatMcp"} + +read -p "组织单位 [IT Department]: " OU +OU=${OU:-"IT Department"} + +read -p "组织名称 [ChatMcp Team]: " O +O=${O:-"ChatMcp Team"} + +read -p "城市或地区 [Beijing]: " L +L=${L:-"Beijing"} + +read -p "省份 [Beijing]: " ST +ST=${ST:-"Beijing"} + +read -p "国家代码 [CN]: " C +C=${C:-"CN"} + +# 创建密钥库目录 +KEYSTORE_DIR="android/app/keystore" +mkdir -p $KEYSTORE_DIR + +KEYSTORE_PATH="$KEYSTORE_DIR/$KEYSTORE_NAME" + +echo +echo -e "${GREEN}正在生成密钥库...${NC}" + +# 生成密钥库 +keytool -genkey \ + -v \ + -keystore "$KEYSTORE_PATH" \ + -alias "$KEY_ALIAS" \ + -keyalg RSA \ + -keysize 2048 \ + -validity "$VALIDITY" \ + -storepass "$STORE_PASSWORD" \ + -keypass "$KEY_PASSWORD" \ + -dname "CN=$CN, OU=$OU, O=$O, L=$L, ST=$ST, C=$C" + +echo +echo -e "${GREEN}密钥库创建成功!${NC}" +echo "文件位置: $KEYSTORE_PATH" +echo + +# 创建环境变量配置文件 +ENV_FILE="android/signing.env" +echo -e "${YELLOW}创建环境变量配置文件: $ENV_FILE${NC}" + +cat > "$ENV_FILE" << EOF +# Android 应用签名配置 +# 注意:这个文件包含敏感信息,不应该提交到版本控制系统 + +SIGNING_STORE_PATH=keystore/$KEYSTORE_NAME +SIGNING_KEY_ALIAS=$KEY_ALIAS +SIGNING_STORE_PASSWORD=$STORE_PASSWORD +SIGNING_KEY_PASSWORD=$KEY_PASSWORD +EOF + +echo +echo -e "${GREEN}配置完成!${NC}" +echo -e "${YELLOW}重要提示:${NC}" +echo "1. 请将 android/signing.env 添加到 .gitignore 文件中" +echo "2. 请安全保存密钥库文件和密码" +echo "3. 在 GitHub Secrets 中添加以下变量:" +echo " - SIGNING_KEY_ALIAS: $KEY_ALIAS" +echo " - SIGNING_STORE_PASSWORD: [您的密钥库密码]" +echo " - SIGNING_KEY_PASSWORD: [您的密钥密码]" +echo " - SIGNING_KEYSTORE: [密钥库文件的 base64 编码]" +echo +echo -e "${YELLOW}生成密钥库的 base64 编码:${NC}" +echo "base64 -i $KEYSTORE_PATH | pbcopy # macOS" +echo "base64 -w 0 $KEYSTORE_PATH | xclip -selection clipboard # Linux" +echo "certutil -encode $KEYSTORE_PATH temp.base64 && type temp.base64 | clip && del temp.base64 # Windows" +echo + +# 添加到gitignore +if ! grep -q "android/signing.env" .gitignore 2>/dev/null; then + echo "android/signing.env" >> .gitignore + echo -e "${GREEN}已添加 android/signing.env 到 .gitignore${NC}" +fi + +if ! grep -q "android/app/keystore/" .gitignore 2>/dev/null; then + echo "android/app/keystore/" >> .gitignore + echo -e "${GREEN}已添加 android/app/keystore/ 到 .gitignore${NC}" +fi + +echo -e "${GREEN}安装完成!${NC}" \ No newline at end of file diff --git a/scripts/diagnose_build_issues.sh b/scripts/diagnose_build_issues.sh new file mode 100644 index 0000000..b18181b --- /dev/null +++ b/scripts/diagnose_build_issues.sh @@ -0,0 +1,143 @@ +#!/bin/bash + +# 脚本用于诊断构建问题 +# 使用方法: ./scripts/diagnose_build_issues.sh + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo -e "${BLUE}ChatMcp 构建问题诊断工具${NC}" +echo "==============================================" + +# 1. 检查Flutter环境 +echo -e "\n${YELLOW}1. 检查Flutter环境...${NC}" +flutter --version +echo + +# 2. 检查Android配置对其他平台的影响 +echo -e "${YELLOW}2. 检查Android配置...${NC}" + +if [ -f "android/app/build.gradle.kts" ]; then + echo "✅ 找到Android构建配置" + + # 检查是否有可能影响其他平台的配置 + if grep -q "flutter.compileSdkVersion" android/app/build.gradle.kts; then + echo "✅ 使用Flutter标准配置" + else + echo "⚠️ 可能使用了自定义配置" + fi +else + echo "❌ 未找到Android构建配置" +fi + +# 3. 检查pubspec.yaml +echo -e "\n${YELLOW}3. 检查依赖配置...${NC}" +if grep -q "platform" pubspec.yaml; then + echo "ℹ️ 发现平台特定配置:" + grep -A 5 -B 5 "platform" pubspec.yaml || true +fi + +# 4. 模拟GitHub Actions环境 +echo -e "\n${YELLOW}4. 模拟GitHub Actions环境测试...${NC}" + +# 4.1 测试无Android环境的构建 +echo -e "\n${BLUE}4.1 测试无Android环境时的行为...${NC}" +unset ANDROID_HOME +unset ANDROID_SDK_ROOT +unset JAVA_HOME + +# 清理并重新获取依赖 +echo "清理项目..." +flutter clean > /dev/null 2>&1 +echo "获取依赖..." +flutter pub get > /dev/null 2>&1 + +# 检查可用的构建目标 +echo -e "\n可用的构建目标:" +flutter build --help | grep -A 10 "Available subcommands:" | grep "^ " || true + +# 4.2 测试Web构建(所有平台都支持) +echo -e "\n${BLUE}4.2 测试Web构建...${NC}" +if flutter build web --release > /tmp/web_build.log 2>&1; then + echo "✅ Web构建成功" +else + echo "❌ Web构建失败" + echo "错误信息:" + tail -10 /tmp/web_build.log +fi + +# 5. 检查GitHub Actions配置 +echo -e "\n${YELLOW}5. 检查GitHub Actions配置...${NC}" +if [ -f ".github/workflows/build.yml" ]; then + echo "✅ 找到GitHub Actions配置" + + # 检查Linux构建配置 + if grep -q "ubuntu-latest" .github/workflows/build.yml; then + echo "✅ 包含Linux构建配置" + + # 检查Android签名步骤是否正确隔离 + if grep -A 5 -B 5 "Setup Android Signing" .github/workflows/build.yml | grep -q "matrix.apk_build"; then + echo "✅ Android签名配置已正确隔离到Android构建" + else + echo "⚠️ Android签名配置可能影响其他平台" + fi + else + echo "❌ 未找到Linux构建配置" + fi +else + echo "❌ 未找到GitHub Actions配置" +fi + +# 6. 检查潜在的配置冲突 +echo -e "\n${YELLOW}6. 检查潜在的配置冲突...${NC}" + +# 检查是否有全局的Android配置影响 +if [ -f "android/gradle.properties" ]; then + echo "ℹ️ Android gradle.properties内容:" + grep -v "^#" android/gradle.properties | grep -v "^$" || true + + # 检查是否有可能影响其他平台的配置 + if grep -q "systemProp" android/gradle.properties; then + echo "⚠️ 发现系统属性配置,可能影响其他构建" + fi +fi + +# 7. 生成诊断报告 +echo -e "\n${BLUE}7. 诊断总结${NC}" +echo "==============================================" + +# 检查可能的问题 +ISSUES_FOUND=0 + +if ! command -v flutter &> /dev/null; then + echo "❌ Flutter未正确安装" + ISSUES_FOUND=$((ISSUES_FOUND + 1)) +fi + +if [ ! -f ".github/workflows/build.yml" ]; then + echo "❌ 缺少GitHub Actions配置" + ISSUES_FOUND=$((ISSUES_FOUND + 1)) +fi + +if [ $ISSUES_FOUND -eq 0 ]; then + echo -e "${GREEN}✅ 未发现明显的配置问题${NC}" + echo + echo "如果Linux构建在GitHub Actions中失败,请:" + echo "1. 检查GitHub Actions的构建日志" + echo "2. 确认所有GitHub Secrets已正确配置" + echo "3. 验证依赖版本兼容性" +else + echo -e "${RED}❌ 发现 $ISSUES_FOUND 个问题需要解决${NC}" +fi + +echo +echo -e "${YELLOW}如需进一步诊断,请提供以下信息:${NC}" +echo "- GitHub Actions构建失败的具体错误日志" +echo "- 失败发生在哪个构建步骤" +echo "- 是否只有Linux构建失败,还是所有平台都失败" \ No newline at end of file diff --git a/scripts/test_build_platforms.sh b/scripts/test_build_platforms.sh new file mode 100644 index 0000000..3dd7317 --- /dev/null +++ b/scripts/test_build_platforms.sh @@ -0,0 +1,118 @@ +#!/bin/bash + +# 脚本用于测试不同平台的构建 +# 使用方法: ./scripts/test_build_platforms.sh + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo -e "${BLUE}ChatMcp 多平台构建测试${NC}" +echo "==============================================" + +# 获取当前平台 +PLATFORM=$(uname -s) +echo "当前平台: $PLATFORM" + +# 清理构建缓存 +echo -e "\n${YELLOW}清理构建缓存...${NC}" +flutter clean +flutter pub get + +# 测试可用的构建目标 +echo -e "\n${YELLOW}检查可用的构建目标...${NC}" +flutter build --help | grep "Available subcommands:" -A 20 + +echo -e "\n${BLUE}开始平台构建测试...${NC}" + +# 根据平台测试不同的构建目标 +case $PLATFORM in + "Darwin") + echo -e "\n${YELLOW}测试 macOS 构建...${NC}" + if flutter build macos --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ macOS 构建成功${NC}" + else + echo -e "${RED}❌ macOS 构建失败${NC}" + fi + + echo -e "\n${YELLOW}测试 iOS 构建...${NC}" + if flutter build ios --release --no-tree-shake-icons --no-codesign; then + echo -e "${GREEN}✅ iOS 构建成功${NC}" + else + echo -e "${RED}❌ iOS 构建失败${NC}" + fi + ;; + + "Linux") + echo -e "\n${YELLOW}测试 Linux 构建...${NC}" + if flutter build linux --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ Linux 构建成功${NC}" + else + echo -e "${RED}❌ Linux 构建失败${NC}" + fi + ;; + + "MINGW"* | "CYGWIN"* | "MSYS"*) + echo -e "\n${YELLOW}测试 Windows 构建...${NC}" + if flutter build windows --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ Windows 构建成功${NC}" + else + echo -e "${RED}❌ Windows 构建失败${NC}" + fi + ;; +esac + +# 测试 Web 构建(所有平台都支持) +echo -e "\n${YELLOW}测试 Web 构建...${NC}" +if flutter build web --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ Web 构建成功${NC}" +else + echo -e "${RED}❌ Web 构建失败${NC}" +fi + +# 测试 Android 构建(如果环境支持) +if command -v java &> /dev/null && [ -n "$ANDROID_SDK_ROOT" ] || [ -n "$ANDROID_HOME" ]; then + echo -e "\n${YELLOW}测试 Android 构建...${NC}" + + # 检查是否有签名配置 + if [ -f "android/signing.env" ]; then + echo -e "${GREEN}发现签名配置,设置环境变量...${NC}" + export $(cat android/signing.env | grep -v '^#' | xargs) + else + echo -e "${YELLOW}未发现签名配置,使用 debug 签名...${NC}" + fi + + if flutter build apk --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ Android APK 构建成功${NC}" + else + echo -e "${RED}❌ Android APK 构建失败${NC}" + fi + + if flutter build appbundle --release --no-tree-shake-icons; then + echo -e "${GREEN}✅ Android AAB 构建成功${NC}" + else + echo -e "${RED}❌ Android AAB 构建失败${NC}" + fi +else + echo -e "\n${YELLOW}跳过 Android 构建(Java 或 Android SDK 未配置)${NC}" +fi + +echo -e "\n${BLUE}构建测试完成!${NC}" + +# 显示构建产物大小 +echo -e "\n${YELLOW}构建产物信息:${NC}" +if [ -d "build" ]; then + find build -name "*.apk" -o -name "*.aab" -o -name "*.app" -o -name "*.exe" -o -name "*.dmg" -o -name "*.tar.gz" -o -name "*.zip" 2>/dev/null | while read file; do + if [ -f "$file" ]; then + size=$(du -h "$file" | cut -f1) + echo " $file: $size" + fi + done +else + echo " 无构建产物" +fi \ No newline at end of file diff --git a/scripts/verify_signing.sh b/scripts/verify_signing.sh new file mode 100644 index 0000000..9592aa4 --- /dev/null +++ b/scripts/verify_signing.sh @@ -0,0 +1,145 @@ +#!/bin/bash + +# 脚本用于验证Android签名配置 +# 使用方法: ./scripts/verify_signing.sh + +set -e + +# 颜色定义 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo -e "${BLUE}ChatMcp Android 签名配置验证工具${NC}" +echo "==============================================" + +# 检查必要工具 +echo -e "${YELLOW}检查必要工具...${NC}" + +if ! command -v keytool &> /dev/null; then + echo -e "${RED}❌ keytool 未找到。请确保已安装 Java JDK。${NC}" + exit 1 +else + echo -e "${GREEN}✅ keytool 已安装${NC}" +fi + +if ! command -v flutter &> /dev/null; then + echo -e "${RED}❌ Flutter 未找到。请确保已安装 Flutter SDK。${NC}" + exit 1 +else + echo -e "${GREEN}✅ Flutter 已安装${NC}" + flutter --version | head -1 +fi + +# 检查签名配置文件 +echo -e "\n${YELLOW}检查签名配置...${NC}" + +if [ -f "android/signing.env" ]; then + echo -e "${GREEN}✅ 找到签名配置文件: android/signing.env${NC}" + + # 读取配置 + source android/signing.env + + if [ -n "$SIGNING_STORE_PATH" ] && [ -n "$SIGNING_KEY_ALIAS" ]; then + echo -e "${GREEN}✅ 签名配置变量已设置${NC}" + echo " - 密钥库路径: $SIGNING_STORE_PATH" + echo " - 密钥别名: $SIGNING_KEY_ALIAS" + + # 检查密钥库文件 + KEYSTORE_FULL_PATH="android/app/$SIGNING_STORE_PATH" + if [ -f "$KEYSTORE_FULL_PATH" ]; then + echo -e "${GREEN}✅ 密钥库文件存在: $KEYSTORE_FULL_PATH${NC}" + + # 验证密钥库 + if [ -n "$SIGNING_STORE_PASSWORD" ]; then + echo -e "${YELLOW}验证密钥库...${NC}" + if keytool -list -keystore "$KEYSTORE_FULL_PATH" -storepass "$SIGNING_STORE_PASSWORD" -alias "$SIGNING_KEY_ALIAS" &>/dev/null; then + echo -e "${GREEN}✅ 密钥库验证成功${NC}" + + # 显示证书信息 + echo -e "\n${BLUE}证书信息:${NC}" + keytool -list -v -keystore "$KEYSTORE_FULL_PATH" -storepass "$SIGNING_STORE_PASSWORD" -alias "$SIGNING_KEY_ALIAS" | grep -E "(别名|Owner|有效期|证书指纹|Alias|Owner|Valid|Certificate fingerprints)" + else + echo -e "${RED}❌ 密钥库验证失败,请检查密码或别名${NC}" + fi + else + echo -e "${YELLOW}⚠️ 未设置密钥库密码,跳过验证${NC}" + fi + else + echo -e "${RED}❌ 密钥库文件不存在: $KEYSTORE_FULL_PATH${NC}" + fi + else + echo -e "${RED}❌ 签名配置变量未完整设置${NC}" + fi +else + echo -e "${YELLOW}⚠️ 未找到签名配置文件,将使用 debug 签名${NC}" + echo " 运行 ./scripts/create_keystore.sh 来创建签名配置" +fi + +# 检查 gradle 配置 +echo -e "\n${YELLOW}检查 Gradle 配置...${NC}" + +if grep -q "signingConfigs" android/app/build.gradle.kts; then + echo -e "${GREEN}✅ Gradle 签名配置已添加${NC}" +else + echo -e "${RED}❌ Gradle 签名配置未找到${NC}" +fi + +# 检查 .gitignore +echo -e "\n${YELLOW}检查 .gitignore 配置...${NC}" + +if grep -q "android/app/keystore/" .gitignore; then + echo -e "${GREEN}✅ 密钥库目录已添加到 .gitignore${NC}" +else + echo -e "${YELLOW}⚠️ 建议将 android/app/keystore/ 添加到 .gitignore${NC}" +fi + +if grep -q "android/signing.env" .gitignore; then + echo -e "${GREEN}✅ 签名配置文件已添加到 .gitignore${NC}" +else + echo -e "${YELLOW}⚠️ 建议将 android/signing.env 添加到 .gitignore${NC}" +fi + +# 测试构建(可选) +echo -e "\n${YELLOW}是否要测试构建 APK?(y/N): ${NC}" +read -r response +if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then + echo -e "${BLUE}开始测试构建...${NC}" + + # 设置环境变量 + if [ -f "android/signing.env" ]; then + export $(cat android/signing.env | grep -v '^#' | xargs) + fi + + # 构建 APK + if flutter build apk --release; then + echo -e "${GREEN}✅ APK 构建成功${NC}" + + # 检查输出文件 + APK_PATH="build/app/outputs/flutter-apk/app-release.apk" + if [ -f "$APK_PATH" ]; then + echo -e "${GREEN}✅ APK 文件已生成: $APK_PATH${NC}" + + # 显示 APK 信息 + echo -e "\n${BLUE}APK 信息:${NC}" + ls -lh "$APK_PATH" + + # 验证签名 + echo -e "\n${BLUE}验证 APK 签名:${NC}" + if jarsigner -verify "$APK_PATH" &>/dev/null; then + echo -e "${GREEN}✅ APK 签名验证成功${NC}" + else + echo -e "${RED}❌ APK 签名验证失败${NC}" + fi + else + echo -e "${RED}❌ APK 文件未找到${NC}" + fi + else + echo -e "${RED}❌ APK 构建失败${NC}" + fi +fi + +echo -e "\n${BLUE}验证完成!${NC}" +echo -e "${YELLOW}如需帮助,请查看文档: docs/android-signing.md${NC}" \ No newline at end of file diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..7b5b2be Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..775e969 Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..ee8ffdd Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..775e969 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..ee8ffdd Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..c8cfc05 --- /dev/null +++ b/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + chatmcp + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..4d9340b --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "chatmcp", + "short_name": "chatmcp", + "start_url": ".", + "display": "standalone", + "background_color": "#hexcode", + "theme_color": "#hexcode", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} \ No newline at end of file diff --git a/web/oauth_callback.html b/web/oauth_callback.html new file mode 100644 index 0000000..f860f4c --- /dev/null +++ b/web/oauth_callback.html @@ -0,0 +1,97 @@ + + + + OAuth Callback + + + + +
+

Processing OAuth Callback

+
+

Please wait while we complete the authentication...

+
+ + + + diff --git a/web/sqflite_sw.js b/web/sqflite_sw.js new file mode 100644 index 0000000..41accde --- /dev/null +++ b/web/sqflite_sw.js @@ -0,0 +1,9506 @@ +(function dartProgram(){function copyProperties(a,b){var s=Object.keys(a) +for(var r=0;r=0)return true +if(typeof version=="function"&&version.length==0){var q=version() +if(/^\d+\.\d+\.\d+\.\d+$/.test(q))return true}}catch(p){}return false}() +function inherit(a,b){a.prototype.constructor=a +a.prototype["$i"+a.name]=a +if(b!=null){if(z){Object.setPrototypeOf(a.prototype,b.prototype) +return}var s=Object.create(b.prototype) +copyProperties(a.prototype,s) +a.prototype=s}}function inheritMany(a,b){for(var s=0;s4294967295)throw A.c(A.T(a,0,4294967295,"length",null)) +return J.ol(new Array(a),b)}, +ok(a,b){if(a<0)throw A.c(A.a2("Length must be a non-negative integer: "+a,null)) +return A.x(new Array(a),b.h("E<0>"))}, +lN(a,b){if(a<0)throw A.c(A.a2("Length must be a non-negative integer: "+a,null)) +return A.x(new Array(a),b.h("E<0>"))}, +ol(a,b){var s=A.x(a,b.h("E<0>")) +s.$flags=1 +return s}, +om(a,b){var s=t.e8 +return J.nR(s.a(a),s.a(b))}, +lP(a){if(a<256)switch(a){case 9:case 10:case 11:case 12:case 13:case 32:case 133:case 160:return!0 +default:return!1}switch(a){case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8232:case 8233:case 8239:case 8287:case 12288:case 65279:return!0 +default:return!1}}, +oo(a,b){var s,r +for(s=a.length;b0;b=r){r=b-1 +if(!(r>>0===b&&b").t(c).h("de<1,2>")) +return new A.bj(a,b.h("@<0>").t(c).h("bj<1,2>"))}, +oq(a){return new A.cL("Field '"+a+"' has been assigned during initialization.")}, +lR(a){return new A.cL("Field '"+a+"' has not been initialized.")}, +k8(a){var s,r=a^48 +if(r<=9)return r +s=a|32 +if(97<=s&&s<=102)return s-87 +return-1}, +bb(a,b){a=a+b&536870911 +a=a+((a&524287)<<10)&536870911 +return a^a>>>6}, +kT(a){a=a+((a&67108863)<<3)&536870911 +a^=a>>>11 +return a+((a&16383)<<15)&536870911}, +k3(a,b,c){return a}, +lk(a){var s,r +for(s=$.ar.length,r=0;rc)A.H(A.T(b,0,c,"start",null))}return new A.bA(a,b,c,d.h("bA<0>"))}, +ow(a,b,c,d){if(t.O.b(a))return new A.bl(a,b,c.h("@<0>").t(d).h("bl<1,2>")) +return new A.aQ(a,b,c.h("@<0>").t(d).h("aQ<1,2>"))}, +m4(a,b,c){var s="count" +if(t.O.b(a)){A.cw(b,s,t.S) +A.aa(b,s) +return new A.c1(a,b,c.h("c1<0>"))}A.cw(b,s,t.S) +A.aa(b,s) +return new A.aT(a,b,c.h("aT<0>"))}, +of(a,b,c){return new A.c0(a,b,c.h("c0<0>"))}, +aE(){return new A.bz("No element")}, +lM(){return new A.bz("Too few elements")}, +ot(a,b){return new A.cR(a,b.h("cR<0>"))}, +bd:function bd(){}, +cy:function cy(a,b){this.a=a +this.$ti=b}, +bj:function bj(a,b){this.a=a +this.$ti=b}, +de:function de(a,b){this.a=a +this.$ti=b}, +dd:function dd(){}, +ae:function ae(a,b){this.a=a +this.$ti=b}, +cz:function cz(a,b){this.a=a +this.$ti=b}, +fL:function fL(a,b){this.a=a +this.b=b}, +fK:function fK(a){this.a=a}, +cL:function cL(a){this.a=a}, +cA:function cA(a){this.a=a}, +hh:function hh(){}, +n:function n(){}, +Y:function Y(){}, +bA:function bA(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.$ti=d}, +bs:function bs(a,b,c){var _=this +_.a=a +_.b=b +_.c=0 +_.d=null +_.$ti=c}, +aQ:function aQ(a,b,c){this.a=a +this.b=b +this.$ti=c}, +bl:function bl(a,b,c){this.a=a +this.b=b +this.$ti=c}, +cT:function cT(a,b,c){var _=this +_.a=null +_.b=a +_.c=b +_.$ti=c}, +a5:function a5(a,b,c){this.a=a +this.b=b +this.$ti=c}, +io:function io(a,b,c){this.a=a +this.b=b +this.$ti=c}, +bF:function bF(a,b,c){this.a=a +this.b=b +this.$ti=c}, +aT:function aT(a,b,c){this.a=a +this.b=b +this.$ti=c}, +c1:function c1(a,b,c){this.a=a +this.b=b +this.$ti=c}, +d1:function d1(a,b,c){this.a=a +this.b=b +this.$ti=c}, +bm:function bm(a){this.$ti=a}, +cD:function cD(a){this.$ti=a}, +d9:function d9(a,b){this.a=a +this.$ti=b}, +da:function da(a,b){this.a=a +this.$ti=b}, +bo:function bo(a,b,c){this.a=a +this.b=b +this.$ti=c}, +c0:function c0(a,b,c){this.a=a +this.b=b +this.$ti=c}, +bp:function bp(a,b,c){var _=this +_.a=a +_.b=b +_.c=-1 +_.$ti=c}, +af:function af(){}, +bc:function bc(){}, +cf:function cf(){}, +f9:function f9(a){this.a=a}, +cR:function cR(a,b){this.a=a +this.$ti=b}, +d0:function d0(a,b){this.a=a +this.$ti=b}, +dE:function dE(){}, +nq(a){var s=v.mangledGlobalNames[a] +if(s!=null)return s +return"minified:"+a}, +re(a,b){var s +if(b!=null){s=b.x +if(s!=null)return s}return t.aU.b(a)}, +o(a){var s +if(typeof a=="string")return a +if(typeof a=="number"){if(a!==0)return""+a}else if(!0===a)return"true" +else if(!1===a)return"false" +else if(a==null)return"null" +s=J.aC(a) +return s}, +et(a){var s,r=$.lV +if(r==null)r=$.lV=Symbol("identityHashCode") +s=a[r] +if(s==null){s=Math.random()*0x3fffffff|0 +a[r]=s}return s}, +kE(a,b){var s,r,q,p,o,n=null,m=/^\s*[+-]?((0x[a-f0-9]+)|(\d+)|([a-z0-9]+))\s*$/i.exec(a) +if(m==null)return n +if(3>=m.length)return A.b(m,3) +s=m[3] +if(b==null){if(s!=null)return parseInt(a,10) +if(m[2]!=null)return parseInt(a,16) +return n}if(b<2||b>36)throw A.c(A.T(b,2,36,"radix",n)) +if(b===10&&s!=null)return parseInt(a,10) +if(b<10||s==null){r=b<=10?47+b:86+b +q=m[1] +for(p=q.length,o=0;or)return n}return parseInt(a,b)}, +hc(a){var s,r,q,p +if(a instanceof A.q)return A.ao(A.aq(a),null) +s=J.bT(a) +if(s===B.E||s===B.H||t.ak.b(a)){r=B.m(a) +if(r!=="Object"&&r!=="")return r +q=a.constructor +if(typeof q=="function"){p=q.name +if(typeof p=="string"&&p!=="Object"&&p!=="")return p}}return A.ao(A.aq(a),null)}, +m1(a){if(a==null||typeof a=="number"||A.dG(a))return J.aC(a) +if(typeof a=="string")return JSON.stringify(a) +if(a instanceof A.b5)return a.j(0) +if(a instanceof A.be)return a.cF(!0) +return"Instance of '"+A.hc(a)+"'"}, +oA(){if(!!self.location)return self.location.href +return null}, +oE(a,b,c){var s,r,q,p +if(c<=500&&b===0&&c===a.length)return String.fromCharCode.apply(null,a) +for(s=b,r="";s>>0,s&1023|56320)}}throw A.c(A.T(a,0,1114111,null,null))}, +bv(a){if(a.date===void 0)a.date=new Date(a.a) +return a.date}, +m0(a){var s=A.bv(a).getFullYear()+0 +return s}, +lZ(a){var s=A.bv(a).getMonth()+1 +return s}, +lW(a){var s=A.bv(a).getDate()+0 +return s}, +lX(a){var s=A.bv(a).getHours()+0 +return s}, +lY(a){var s=A.bv(a).getMinutes()+0 +return s}, +m_(a){var s=A.bv(a).getSeconds()+0 +return s}, +oC(a){var s=A.bv(a).getMilliseconds()+0 +return s}, +oD(a){var s=A.bv(a).getDay()+0 +return B.c.Y(s+6,7)+1}, +oB(a){var s=a.$thrownJsError +if(s==null)return null +return A.aj(s)}, +kF(a,b){var s +if(a.$thrownJsError==null){s=new Error() +A.a1(a,s) +a.$thrownJsError=s +s.stack=b.j(0)}}, +r9(a){throw A.c(A.k1(a))}, +b(a,b){if(a==null)J.P(a) +throw A.c(A.k4(a,b))}, +k4(a,b){var s,r="index" +if(!A.ft(b))return new A.aw(!0,b,r,null) +s=A.d(J.P(a)) +if(b<0||b>=s)return A.ea(b,s,a,null,r) +return A.m2(b,r)}, +r0(a,b,c){if(a>c)return A.T(a,0,c,"start",null) +if(b!=null)if(bc)return A.T(b,a,c,"end",null) +return new A.aw(!0,b,"end",null)}, +k1(a){return new A.aw(!0,a,null,null)}, +c(a){return A.a1(a,new Error())}, +a1(a,b){var s +if(a==null)a=new A.aV() +b.dartException=a +s=A.rp +if("defineProperty" in Object){Object.defineProperty(b,"message",{get:s}) +b.name=""}else b.toString=s +return b}, +rp(){return J.aC(this.dartException)}, +H(a,b){throw A.a1(a,b==null?new Error():b)}, +y(a,b,c){var s +if(b==null)b=0 +if(c==null)c=0 +s=Error() +A.H(A.qk(a,b,c),s)}, +qk(a,b,c){var s,r,q,p,o,n,m,l,k +if(typeof b=="string")s=b +else{r="[]=;add;removeWhere;retainWhere;removeRange;setRange;setInt8;setInt16;setInt32;setUint8;setUint16;setUint32;setFloat32;setFloat64".split(";") +q=r.length +p=b +if(p>q){c=p/q|0 +p%=q}s=r[p]}o=typeof c=="string"?c:"modify;remove from;add to".split(";")[c] +n=t.j.b(a)?"list":"ByteData" +m=a.$flags|0 +l="a " +if((m&4)!==0)k="constant " +else if((m&2)!==0){k="unmodifiable " +l="an "}else k=(m&1)!==0?"fixed-length ":"" +return new A.d7("'"+s+"': Cannot "+o+" "+l+k+n)}, +aJ(a){throw A.c(A.a9(a))}, +aW(a){var s,r,q,p,o,n +a=A.no(a.replace(String({}),"$receiver$")) +s=a.match(/\\\$[a-zA-Z]+\\\$/g) +if(s==null)s=A.x([],t.s) +r=s.indexOf("\\$arguments\\$") +q=s.indexOf("\\$argumentsExpr\\$") +p=s.indexOf("\\$expr\\$") +o=s.indexOf("\\$method\\$") +n=s.indexOf("\\$receiver\\$") +return new A.i8(a.replace(new RegExp("\\\\\\$arguments\\\\\\$","g"),"((?:x|[^x])*)").replace(new RegExp("\\\\\\$argumentsExpr\\\\\\$","g"),"((?:x|[^x])*)").replace(new RegExp("\\\\\\$expr\\\\\\$","g"),"((?:x|[^x])*)").replace(new RegExp("\\\\\\$method\\\\\\$","g"),"((?:x|[^x])*)").replace(new RegExp("\\\\\\$receiver\\\\\\$","g"),"((?:x|[^x])*)"),r,q,p,o,n)}, +i9(a){return function($expr$){var $argumentsExpr$="$arguments$" +try{$expr$.$method$($argumentsExpr$)}catch(s){return s.message}}(a)}, +ma(a){return function($expr$){try{$expr$.$method$}catch(s){return s.message}}(a)}, +kz(a,b){var s=b==null,r=s?null:b.method +return new A.eg(a,r,s?null:b.receiver)}, +N(a){var s +if(a==null)return new A.h9(a) +if(a instanceof A.cE){s=a.a +return A.bi(a,s==null?t.K.a(s):s)}if(typeof a!=="object")return a +if("dartException" in a)return A.bi(a,a.dartException) +return A.qQ(a)}, +bi(a,b){if(t.Q.b(b))if(b.$thrownJsError==null)b.$thrownJsError=a +return b}, +qQ(a){var s,r,q,p,o,n,m,l,k,j,i,h,g +if(!("message" in a))return a +s=a.message +if("number" in a&&typeof a.number=="number"){r=a.number +q=r&65535 +if((B.c.F(r,16)&8191)===10)switch(q){case 438:return A.bi(a,A.kz(A.o(s)+" (Error "+q+")",null)) +case 445:case 5007:A.o(s) +return A.bi(a,new A.cX())}}if(a instanceof TypeError){p=$.nv() +o=$.nw() +n=$.nx() +m=$.ny() +l=$.nB() +k=$.nC() +j=$.nA() +$.nz() +i=$.nE() +h=$.nD() +g=p.a_(s) +if(g!=null)return A.bi(a,A.kz(A.L(s),g)) +else{g=o.a_(s) +if(g!=null){g.method="call" +return A.bi(a,A.kz(A.L(s),g))}else if(n.a_(s)!=null||m.a_(s)!=null||l.a_(s)!=null||k.a_(s)!=null||j.a_(s)!=null||m.a_(s)!=null||i.a_(s)!=null||h.a_(s)!=null){A.L(s) +return A.bi(a,new A.cX())}}return A.bi(a,new A.eI(typeof s=="string"?s:""))}if(a instanceof RangeError){if(typeof s=="string"&&s.indexOf("call stack")!==-1)return new A.d5() +s=function(b){try{return String(b)}catch(f){}return null}(a) +return A.bi(a,new A.aw(!1,null,null,typeof s=="string"?s.replace(/^RangeError:\s*/,""):s))}if(typeof InternalError=="function"&&a instanceof InternalError)if(typeof s=="string"&&s==="too much recursion")return new A.d5() +return a}, +aj(a){var s +if(a instanceof A.cE)return a.b +if(a==null)return new A.ds(a) +s=a.$cachedTrace +if(s!=null)return s +s=new A.ds(a) +if(typeof a==="object")a.$cachedTrace=s +return s}, +lm(a){if(a==null)return J.aL(a) +if(typeof a=="object")return A.et(a) +return J.aL(a)}, +r4(a,b){var s,r,q,p=a.length +for(s=0;s=0 +else if(b instanceof A.cJ){s=B.a.Z(a,c) +return b.b.test(s)}else return!J.nQ(b,B.a.Z(a,c)).gW(0)}, +r2(a){if(a.indexOf("$",0)>=0)return a.replace(/\$/g,"$$$$") +return a}, +no(a){if(/[[\]{}()*+?.\\^$|]/.test(a))return a.replace(/[[\]{}()*+?.\\^$|]/g,"\\$&") +return a}, +rn(a,b,c){var s=A.ro(a,b,c) +return s}, +ro(a,b,c){var s,r,q +if(b===""){if(a==="")return c +s=a.length +r=""+c +for(q=0;q=0)return a.split(b).join(c) +return a.replace(new RegExp(A.no(b),"g"),A.r2(c))}, +bf:function bf(a,b){this.a=a +this.b=b}, +cl:function cl(a,b){this.a=a +this.b=b}, +cB:function cB(){}, +cC:function cC(a,b,c){this.a=a +this.b=b +this.$ti=c}, +bM:function bM(a,b){this.a=a +this.$ti=b}, +dg:function dg(a,b,c){var _=this +_.a=a +_.b=b +_.c=0 +_.d=null +_.$ti=c}, +i8:function i8(a,b,c,d,e,f){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f}, +cX:function cX(){}, +eg:function eg(a,b,c){this.a=a +this.b=b +this.c=c}, +eI:function eI(a){this.a=a}, +h9:function h9(a){this.a=a}, +cE:function cE(a,b){this.a=a +this.b=b}, +ds:function ds(a){this.a=a +this.b=null}, +b5:function b5(){}, +dW:function dW(){}, +dX:function dX(){}, +eG:function eG(){}, +eD:function eD(){}, +bY:function bY(a,b){this.a=a +this.b=b}, +ex:function ex(a){this.a=a}, +aP:function aP(a){var _=this +_.a=0 +_.f=_.e=_.d=_.c=_.b=null +_.r=0 +_.$ti=a}, +h2:function h2(a){this.a=a}, +h3:function h3(a,b){var _=this +_.a=a +_.b=b +_.d=_.c=null}, +br:function br(a,b){this.a=a +this.$ti=b}, +cO:function cO(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=null +_.$ti=d}, +cQ:function cQ(a,b){this.a=a +this.$ti=b}, +cP:function cP(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=null +_.$ti=d}, +cM:function cM(a,b){this.a=a +this.$ti=b}, +cN:function cN(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=null +_.$ti=d}, +k9:function k9(a){this.a=a}, +ka:function ka(a){this.a=a}, +kb:function kb(a){this.a=a}, +be:function be(){}, +bP:function bP(){}, +cJ:function cJ(a,b){var _=this +_.a=a +_.b=b +_.e=_.d=_.c=null}, +dl:function dl(a){this.b=a}, +eX:function eX(a,b,c){this.a=a +this.b=b +this.c=c}, +eY:function eY(a,b,c){var _=this +_.a=a +_.b=b +_.c=c +_.d=null}, +d6:function d6(a,b){this.a=a +this.c=b}, +fm:function fm(a,b,c){this.a=a +this.b=b +this.c=c}, +fn:function fn(a,b,c){var _=this +_.a=a +_.b=b +_.c=c +_.d=null}, +aK(a){throw A.a1(A.lR(a),new Error())}, +fx(a){throw A.a1(A.oq(a),new Error())}, +iz(a){var s=new A.iy(a) +return s.b=s}, +iy:function iy(a){this.a=a +this.b=null}, +qi(a){return a}, +fr(a,b,c){}, +ql(a){return a}, +ox(a,b,c){var s +A.fr(a,b,c) +s=new DataView(a,b) +return s}, +bt(a,b,c){A.fr(a,b,c) +c=B.c.E(a.byteLength-b,4) +return new Int32Array(a,b,c)}, +oy(a,b,c){A.fr(a,b,c) +return new Uint32Array(a,b,c)}, +oz(a){return new Uint8Array(a)}, +aR(a,b,c){A.fr(a,b,c) +return c==null?new Uint8Array(a,b):new Uint8Array(a,b,c)}, +aZ(a,b,c){if(a>>>0!==a||a>=c)throw A.c(A.k4(b,a))}, +qj(a,b,c){var s +if(!(a>>>0!==a))s=b>>>0!==b||a>b||b>c +else s=!0 +if(s)throw A.c(A.r0(a,b,c)) +return b}, +ca:function ca(){}, +cV:function cV(){}, +fp:function fp(a){this.a=a}, +cU:function cU(){}, +a6:function a6(){}, +b9:function b9(){}, +am:function am(){}, +ei:function ei(){}, +ej:function ej(){}, +ek:function ek(){}, +el:function el(){}, +em:function em(){}, +en:function en(){}, +eo:function eo(){}, +cW:function cW(){}, +bu:function bu(){}, +dm:function dm(){}, +dn:function dn(){}, +dp:function dp(){}, +dq:function dq(){}, +kG(a,b){var s=b.c +return s==null?b.c=A.dw(a,"z",[b.x]):s}, +m3(a){var s=a.w +if(s===6||s===7)return A.m3(a.x) +return s===11||s===12}, +oJ(a){return a.as}, +b0(a){return A.jK(v.typeUniverse,a,!1)}, +bR(a1,a2,a3,a4){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0=a2.w +switch(a0){case 5:case 1:case 2:case 3:case 4:return a2 +case 6:s=a2.x +r=A.bR(a1,s,a3,a4) +if(r===s)return a2 +return A.mz(a1,r,!0) +case 7:s=a2.x +r=A.bR(a1,s,a3,a4) +if(r===s)return a2 +return A.my(a1,r,!0) +case 8:q=a2.y +p=A.cr(a1,q,a3,a4) +if(p===q)return a2 +return A.dw(a1,a2.x,p) +case 9:o=a2.x +n=A.bR(a1,o,a3,a4) +m=a2.y +l=A.cr(a1,m,a3,a4) +if(n===o&&l===m)return a2 +return A.l4(a1,n,l) +case 10:k=a2.x +j=a2.y +i=A.cr(a1,j,a3,a4) +if(i===j)return a2 +return A.mA(a1,k,i) +case 11:h=a2.x +g=A.bR(a1,h,a3,a4) +f=a2.y +e=A.qN(a1,f,a3,a4) +if(g===h&&e===f)return a2 +return A.mx(a1,g,e) +case 12:d=a2.y +a4+=d.length +c=A.cr(a1,d,a3,a4) +o=a2.x +n=A.bR(a1,o,a3,a4) +if(c===d&&n===o)return a2 +return A.l5(a1,n,c,!0) +case 13:b=a2.x +if(b=p)return A.b(q,0) +s=A.dy(v.typeUniverse,A.le(q[0]),"@<0>") +for(r=1;r=0)p+=" "+r[q];++q}return p+"})"}, +mZ(a3,a4,a5){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1=", ",a2=null +if(a5!=null){s=a5.length +if(a4==null)a4=A.x([],t.s) +else a2=a4.length +r=a4.length +for(q=s;q>0;--q)B.b.n(a4,"T"+(r+q)) +for(p=t.X,o="<",n="",q=0;q=0))return A.b(a4,l) +o=o+n+a4[l] +k=a5[q] +j=k.w +if(!(j===2||j===3||j===4||j===5||k===p))o+=" extends "+A.ao(k,a4)}o+=">"}else o="" +p=a3.x +i=a3.y +h=i.a +g=h.length +f=i.b +e=f.length +d=i.c +c=d.length +b=A.ao(p,a4) +for(a="",a0="",q=0;q0){a+=a0+"[" +for(a0="",q=0;q0){a+=a0+"{" +for(a0="",q=0;q "+b}, +ao(a,b){var s,r,q,p,o,n,m,l=a.w +if(l===5)return"erased" +if(l===2)return"dynamic" +if(l===3)return"void" +if(l===1)return"Never" +if(l===4)return"any" +if(l===6){s=a.x +r=A.ao(s,b) +q=s.w +return(q===11||q===12?"("+r+")":r)+"?"}if(l===7)return"FutureOr<"+A.ao(a.x,b)+">" +if(l===8){p=A.qP(a.x) +o=a.y +return o.length>0?p+("<"+A.n8(o,b)+">"):p}if(l===10)return A.qH(a,b) +if(l===11)return A.mZ(a,b,null) +if(l===12)return A.mZ(a.x,b,a.y) +if(l===13){n=a.x +m=b.length +n=m-1-n +if(!(n>=0&&n0)p+="<"+A.dv(c)+">" +s=a.eC.get(p) +if(s!=null)return s +r=new A.ay(null,null) +r.w=8 +r.x=b +r.y=c +if(c.length>0)r.c=c[0] +r.as=p +q=A.bg(a,r) +a.eC.set(p,q) +return q}, +l4(a,b,c){var s,r,q,p,o,n +if(b.w===9){s=b.x +r=b.y.concat(c)}else{r=c +s=b}q=s.as+(";<"+A.dv(r)+">") +p=a.eC.get(q) +if(p!=null)return p +o=new A.ay(null,null) +o.w=9 +o.x=s +o.y=r +o.as=q +n=A.bg(a,o) +a.eC.set(q,n) +return n}, +mA(a,b,c){var s,r,q="+"+(b+"("+A.dv(c)+")"),p=a.eC.get(q) +if(p!=null)return p +s=new A.ay(null,null) +s.w=10 +s.x=b +s.y=c +s.as=q +r=A.bg(a,s) +a.eC.set(q,r) +return r}, +mx(a,b,c){var s,r,q,p,o,n=b.as,m=c.a,l=m.length,k=c.b,j=k.length,i=c.c,h=i.length,g="("+A.dv(m) +if(j>0){s=l>0?",":"" +g+=s+"["+A.dv(k)+"]"}if(h>0){s=l>0?",":"" +g+=s+"{"+A.pP(i)+"}"}r=n+(g+")") +q=a.eC.get(r) +if(q!=null)return q +p=new A.ay(null,null) +p.w=11 +p.x=b +p.y=c +p.as=r +o=A.bg(a,p) +a.eC.set(r,o) +return o}, +l5(a,b,c,d){var s,r=b.as+("<"+A.dv(c)+">"),q=a.eC.get(r) +if(q!=null)return q +s=A.pR(a,b,c,r,d) +a.eC.set(r,s) +return s}, +pR(a,b,c,d,e){var s,r,q,p,o,n,m,l +if(e){s=c.length +r=A.jO(s) +for(q=0,p=0;p0){n=A.bR(a,b,r,0) +m=A.cr(a,c,r,0) +return A.l5(a,n,m,c!==m)}}l=new A.ay(null,null) +l.w=12 +l.x=b +l.y=c +l.as=d +return A.bg(a,l)}, +ms(a,b,c,d){return{u:a,e:b,r:c,s:[],p:0,n:d}}, +mu(a){var s,r,q,p,o,n,m,l=a.r,k=a.s +for(s=l.length,r=0;r=48&&q<=57)r=A.pJ(r+1,q,l,k) +else if((((q|32)>>>0)-97&65535)<26||q===95||q===36||q===124)r=A.mt(a,r,l,k,!1) +else if(q===46)r=A.mt(a,r,l,k,!0) +else{++r +switch(q){case 44:break +case 58:k.push(!1) +break +case 33:k.push(!0) +break +case 59:k.push(A.bO(a.u,a.e,k.pop())) +break +case 94:k.push(A.pT(a.u,k.pop())) +break +case 35:k.push(A.dx(a.u,5,"#")) +break +case 64:k.push(A.dx(a.u,2,"@")) +break +case 126:k.push(A.dx(a.u,3,"~")) +break +case 60:k.push(a.p) +a.p=k.length +break +case 62:A.pL(a,k) +break +case 38:A.pK(a,k) +break +case 63:p=a.u +k.push(A.mz(p,A.bO(p,a.e,k.pop()),a.n)) +break +case 47:p=a.u +k.push(A.my(p,A.bO(p,a.e,k.pop()),a.n)) +break +case 40:k.push(-3) +k.push(a.p) +a.p=k.length +break +case 41:A.pI(a,k) +break +case 91:k.push(a.p) +a.p=k.length +break +case 93:o=k.splice(a.p) +A.mv(a.u,a.e,o) +a.p=k.pop() +k.push(o) +k.push(-1) +break +case 123:k.push(a.p) +a.p=k.length +break +case 125:o=k.splice(a.p) +A.pN(a.u,a.e,o) +a.p=k.pop() +k.push(o) +k.push(-2) +break +case 43:n=l.indexOf("(",r) +k.push(l.substring(r,n)) +k.push(-4) +k.push(a.p) +a.p=k.length +r=n+1 +break +default:throw"Bad character "+q}}}m=k.pop() +return A.bO(a.u,a.e,m)}, +pJ(a,b,c,d){var s,r,q=b-48 +for(s=c.length;a=48&&r<=57))break +q=q*10+(r-48)}d.push(q) +return a}, +mt(a,b,c,d,e){var s,r,q,p,o,n,m=b+1 +for(s=c.length;m>>0)-97&65535)<26||r===95||r===36||r===124))q=r>=48&&r<=57 +else q=!0 +if(!q)break}}p=c.substring(b,m) +if(e){s=a.u +o=a.e +if(o.w===9)o=o.x +n=A.pX(s,o.x)[p] +if(n==null)A.H('No "'+p+'" in "'+A.oJ(o)+'"') +d.push(A.dy(s,o,n))}else d.push(p) +return m}, +pL(a,b){var s,r=a.u,q=A.mr(a,b),p=b.pop() +if(typeof p=="string")b.push(A.dw(r,p,q)) +else{s=A.bO(r,a.e,p) +switch(s.w){case 11:b.push(A.l5(r,s,q,a.n)) +break +default:b.push(A.l4(r,s,q)) +break}}}, +pI(a,b){var s,r,q,p=a.u,o=b.pop(),n=null,m=null +if(typeof o=="number")switch(o){case-1:n=b.pop() +break +case-2:m=b.pop() +break +default:b.push(o) +break}else b.push(o) +s=A.mr(a,b) +o=b.pop() +switch(o){case-3:o=b.pop() +if(n==null)n=p.sEA +if(m==null)m=p.sEA +r=A.bO(p,a.e,o) +q=new A.f3() +q.a=s +q.b=n +q.c=m +b.push(A.mx(p,r,q)) +return +case-4:b.push(A.mA(p,b.pop(),s)) +return +default:throw A.c(A.dO("Unexpected state under `()`: "+A.o(o)))}}, +pK(a,b){var s=b.pop() +if(0===s){b.push(A.dx(a.u,1,"0&")) +return}if(1===s){b.push(A.dx(a.u,4,"1&")) +return}throw A.c(A.dO("Unexpected extended operation "+A.o(s)))}, +mr(a,b){var s=b.splice(a.p) +A.mv(a.u,a.e,s) +a.p=b.pop() +return s}, +bO(a,b,c){if(typeof c=="string")return A.dw(a,c,a.sEA) +else if(typeof c=="number"){b.toString +return A.pM(a,b,c)}else return c}, +mv(a,b,c){var s,r=c.length +for(s=0;sn)return!1 +m=n-o +l=s.b +k=r.b +j=l.length +i=k.length +if(o+j=d)return!1 +a1=f[b] +b+=3 +if(a00?new Array(q):v.typeUniverse.sEA +for(o=0;o0?new Array(a):v.typeUniverse.sEA}, +ay:function ay(a,b){var _=this +_.a=a +_.b=b +_.r=_.f=_.d=_.c=null +_.w=0 +_.as=_.Q=_.z=_.y=_.x=null}, +f3:function f3(){this.c=this.b=this.a=null}, +jJ:function jJ(a){this.a=a}, +f1:function f1(){}, +du:function du(a){this.a=a}, +pw(){var s,r,q +if(self.scheduleImmediate!=null)return A.qU() +if(self.MutationObserver!=null&&self.document!=null){s={} +r=self.document.createElement("div") +q=self.document.createElement("span") +s.a=null +new self.MutationObserver(A.bS(new A.ir(s),1)).observe(r,{childList:true}) +return new A.iq(s,r,q)}else if(self.setImmediate!=null)return A.qV() +return A.qW()}, +px(a){self.scheduleImmediate(A.bS(new A.is(t.M.a(a)),0))}, +py(a){self.setImmediate(A.bS(new A.it(t.M.a(a)),0))}, +pz(a){A.m9(B.n,t.M.a(a))}, +m9(a,b){var s=B.c.E(a.a,1000) +return A.pO(s<0?0:s,b)}, +pO(a,b){var s=new A.jH(!0) +s.dz(a,b) +return s}, +l(a){return new A.db(new A.v($.w,a.h("v<0>")),a.h("db<0>"))}, +k(a,b){a.$2(0,null) +b.b=!0 +return b.a}, +f(a,b){b.toString +A.qc(a,b)}, +j(a,b){b.U(a)}, +i(a,b){b.bW(A.N(a),A.aj(a))}, +qc(a,b){var s,r,q=new A.jR(b),p=new A.jS(b) +if(a instanceof A.v)a.cE(q,p,t.z) +else{s=t.z +if(a instanceof A.v)a.bm(q,p,s) +else{r=new A.v($.w,t._) +r.a=8 +r.c=a +r.cE(q,p,s)}}}, +m(a){var s=function(b,c){return function(d,e){while(true){try{b(d,e) +break}catch(r){e=r +d=c}}}}(a,1) +return $.w.d1(new A.k0(s),t.H,t.S,t.z)}, +mw(a,b,c){return 0}, +dP(a){var s +if(t.Q.b(a)){s=a.gaj() +if(s!=null)return s}return B.j}, +oa(a,b){var s=new A.v($.w,b.h("v<0>")) +A.pn(B.n,new A.fX(a,s)) +return s}, +ob(a,b){var s,r,q,p,o,n,m,l=null +try{l=a.$0()}catch(q){s=A.N(q) +r=A.aj(q) +p=new A.v($.w,b.h("v<0>")) +o=s +n=r +m=A.jY(o,n) +if(m==null)o=new A.X(o,n==null?A.dP(o):n) +else o=m +p.aE(o) +return p}return b.h("z<0>").b(l)?l:A.mp(l,b)}, +lJ(a){var s +a.a(null) +s=new A.v($.w,a.h("v<0>")) +s.bx(null) +return s}, +kv(a,b){var s,r,q,p,o,n,m,l,k,j,i={},h=null,g=!1,f=new A.v($.w,b.h("v>")) +i.a=null +i.b=0 +i.c=i.d=null +s=new A.fZ(i,h,g,f) +try{for(n=J.W(a),m=t.P;n.m();){r=n.gp() +q=i.b +r.bm(new A.fY(i,q,f,b,h,g),s,m);++i.b}n=i.b +if(n===0){n=f +n.aY(A.x([],b.h("E<0>"))) +return n}i.a=A.cS(n,null,!1,b.h("0?"))}catch(l){p=A.N(l) +o=A.aj(l) +if(i.b===0||g){n=f +m=p +k=o +j=A.jY(m,k) +if(j==null)m=new A.X(m,k==null?A.dP(m):k) +else m=j +n.aE(m) +return n}else{i.d=p +i.c=o}}return f}, +jY(a,b){var s,r,q,p=$.w +if(p===B.e)return null +s=p.ex(a,b) +if(s==null)return null +r=s.a +q=s.b +if(t.Q.b(r))A.kF(r,q) +return s}, +n_(a,b){var s +if($.w!==B.e){s=A.jY(a,b) +if(s!=null)return s}if(b==null)if(t.Q.b(a)){b=a.gaj() +if(b==null){A.kF(a,B.j) +b=B.j}}else b=B.j +else if(t.Q.b(a))A.kF(a,b) +return new A.X(a,b)}, +mp(a,b){var s=new A.v($.w,b.h("v<0>")) +b.a(a) +s.a=8 +s.c=a +return s}, +iL(a,b,c){var s,r,q,p,o={},n=o.a=a +for(s=t._;r=n.a,(r&4)!==0;n=a){a=s.a(n.c) +o.a=a}if(n===b){s=A.ph() +b.aE(new A.X(new A.aw(!0,n,null,"Cannot complete a future with itself"),s)) +return}q=b.a&1 +s=n.a=r|q +if((s&24)===0){p=t.d.a(b.c) +b.a=b.a&1|4 +b.c=n +n.ct(p) +return}if(!c)if(b.c==null)n=(s&16)===0||q!==0 +else n=!1 +else n=!0 +if(n){p=b.aI() +b.aX(o.a) +A.bL(b,p) +return}b.a^=2 +b.b.az(new A.iM(o,b))}, +bL(a,b){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d={},c=d.a=a +for(s=t.n,r=t.d;!0;){q={} +p=c.a +o=(p&16)===0 +n=!o +if(b==null){if(n&&(p&1)===0){m=s.a(c.c) +c.b.cT(m.a,m.b)}return}q.a=b +l=b.a +for(c=b;l!=null;c=l,l=k){c.a=null +A.bL(d.a,c) +q.a=l +k=l.a}p=d.a +j=p.c +q.b=n +q.c=j +if(o){i=c.c +i=(i&1)!==0||(i&15)===8}else i=!0 +if(i){h=c.b.b +if(n){c=p.b +c=!(c===h||c.gap()===h.gap())}else c=!1 +if(c){c=d.a +m=s.a(c.c) +c.b.cT(m.a,m.b) +return}g=$.w +if(g!==h)$.w=h +else g=null +c=q.a.c +if((c&15)===8)new A.iQ(q,d,n).$0() +else if(o){if((c&1)!==0)new A.iP(q,j).$0()}else if((c&2)!==0)new A.iO(d,q).$0() +if(g!=null)$.w=g +c=q.c +if(c instanceof A.v){p=q.a.$ti +p=p.h("z<2>").b(c)||!p.y[1].b(c)}else p=!1 +if(p){f=q.a.b +if((c.a&24)!==0){e=r.a(f.c) +f.c=null +b=f.b2(e) +f.a=c.a&30|f.a&1 +f.c=c.c +d.a=c +continue}else A.iL(c,f,!0) +return}}f=q.a.b +e=r.a(f.c) +f.c=null +b=f.b2(e) +c=q.b +p=q.c +if(!c){f.$ti.c.a(p) +f.a=8 +f.c=p}else{s.a(p) +f.a=f.a&1|16 +f.c=p}d.a=f +c=f}}, +qI(a,b){if(t.U.b(a))return b.d1(a,t.z,t.K,t.l) +if(t.v.b(a))return b.d2(a,t.z,t.K) +throw A.c(A.aM(a,"onError",u.c))}, +qG(){var s,r +for(s=$.cq;s!=null;s=$.cq){$.dI=null +r=s.b +$.cq=r +if(r==null)$.dH=null +s.a.$0()}}, +qM(){$.lc=!0 +try{A.qG()}finally{$.dI=null +$.lc=!1 +if($.cq!=null)$.lo().$1(A.nf())}}, +na(a){var s=new A.eZ(a),r=$.dH +if(r==null){$.cq=$.dH=s +if(!$.lc)$.lo().$1(A.nf())}else $.dH=r.b=s}, +qL(a){var s,r,q,p=$.cq +if(p==null){A.na(a) +$.dI=$.dH +return}s=new A.eZ(a) +r=$.dI +if(r==null){s.b=p +$.cq=$.dI=s}else{q=r.b +s.b=q +$.dI=r.b=s +if(q==null)$.dH=s}}, +ry(a,b){return new A.fl(A.k3(a,"stream",t.K),b.h("fl<0>"))}, +pn(a,b){var s=$.w +if(s===B.e)return s.cM(a,b) +return s.cM(a,s.cJ(b))}, +ld(a,b){A.qL(new A.jZ(a,b))}, +n6(a,b,c,d,e){var s,r +t.E.a(a) +t.q.a(b) +t.x.a(c) +e.h("0()").a(d) +r=$.w +if(r===c)return d.$0() +$.w=c +s=r +try{r=d.$0() +return r}finally{$.w=s}}, +n7(a,b,c,d,e,f,g){var s,r +t.E.a(a) +t.q.a(b) +t.x.a(c) +f.h("@<0>").t(g).h("1(2)").a(d) +g.a(e) +r=$.w +if(r===c)return d.$1(e) +$.w=c +s=r +try{r=d.$1(e) +return r}finally{$.w=s}}, +qJ(a,b,c,d,e,f,g,h,i){var s,r +t.E.a(a) +t.q.a(b) +t.x.a(c) +g.h("@<0>").t(h).t(i).h("1(2,3)").a(d) +h.a(e) +i.a(f) +r=$.w +if(r===c)return d.$2(e,f) +$.w=c +s=r +try{r=d.$2(e,f) +return r}finally{$.w=s}}, +qK(a,b,c,d){var s,r +t.M.a(d) +if(B.e!==c){s=B.e.gap() +r=c.gap() +d=s!==r?c.cJ(d):c.ek(d,t.H)}A.na(d)}, +ir:function ir(a){this.a=a}, +iq:function iq(a,b,c){this.a=a +this.b=b +this.c=c}, +is:function is(a){this.a=a}, +it:function it(a){this.a=a}, +jH:function jH(a){this.a=a +this.b=null +this.c=0}, +jI:function jI(a,b){this.a=a +this.b=b}, +db:function db(a,b){this.a=a +this.b=!1 +this.$ti=b}, +jR:function jR(a){this.a=a}, +jS:function jS(a){this.a=a}, +k0:function k0(a){this.a=a}, +dt:function dt(a,b){var _=this +_.a=a +_.e=_.d=_.c=_.b=null +_.$ti=b}, +cm:function cm(a,b){this.a=a +this.$ti=b}, +X:function X(a,b){this.a=a +this.b=b}, +fX:function fX(a,b){this.a=a +this.b=b}, +fZ:function fZ(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d}, +fY:function fY(a,b,c,d,e,f){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f}, +ci:function ci(){}, +bH:function bH(a,b){this.a=a +this.$ti=b}, +a_:function a_(a,b){this.a=a +this.$ti=b}, +aY:function aY(a,b,c,d,e){var _=this +_.a=null +_.b=a +_.c=b +_.d=c +_.e=d +_.$ti=e}, +v:function v(a,b){var _=this +_.a=0 +_.b=a +_.c=null +_.$ti=b}, +iI:function iI(a,b){this.a=a +this.b=b}, +iN:function iN(a,b){this.a=a +this.b=b}, +iM:function iM(a,b){this.a=a +this.b=b}, +iK:function iK(a,b){this.a=a +this.b=b}, +iJ:function iJ(a,b){this.a=a +this.b=b}, +iQ:function iQ(a,b,c){this.a=a +this.b=b +this.c=c}, +iR:function iR(a,b){this.a=a +this.b=b}, +iS:function iS(a){this.a=a}, +iP:function iP(a,b){this.a=a +this.b=b}, +iO:function iO(a,b){this.a=a +this.b=b}, +eZ:function eZ(a){this.a=a +this.b=null}, +eE:function eE(){}, +i5:function i5(a,b){this.a=a +this.b=b}, +i6:function i6(a,b){this.a=a +this.b=b}, +fl:function fl(a,b){var _=this +_.a=null +_.b=a +_.c=!1 +_.$ti=b}, +dD:function dD(){}, +jZ:function jZ(a,b){this.a=a +this.b=b}, +ff:function ff(){}, +jF:function jF(a,b,c){this.a=a +this.b=b +this.c=c}, +jE:function jE(a,b){this.a=a +this.b=b}, +jG:function jG(a,b,c){this.a=a +this.b=b +this.c=c}, +or(a,b){return new A.aP(a.h("@<0>").t(b).h("aP<1,2>"))}, +ah(a,b,c){return b.h("@<0>").t(c).h("lS<1,2>").a(A.r4(a,new A.aP(b.h("@<0>").t(c).h("aP<1,2>"))))}, +O(a,b){return new A.aP(a.h("@<0>").t(b).h("aP<1,2>"))}, +os(a){return new A.dh(a.h("dh<0>"))}, +l3(){var s=Object.create(null) +s[""]=s +delete s[""] +return s}, +mq(a,b,c){var s=new A.bN(a,b,c.h("bN<0>")) +s.c=a.e +return s}, +kA(a,b,c){var s=A.or(b,c) +a.M(0,new A.h4(s,b,c)) +return s}, +h6(a){var s,r +if(A.lk(a))return"{...}" +s=new A.ac("") +try{r={} +B.b.n($.ar,a) +s.a+="{" +r.a=!0 +a.M(0,new A.h7(r,s)) +s.a+="}"}finally{if(0>=$.ar.length)return A.b($.ar,-1) +$.ar.pop()}r=s.a +return r.charCodeAt(0)==0?r:r}, +dh:function dh(a){var _=this +_.a=0 +_.f=_.e=_.d=_.c=_.b=null +_.r=0 +_.$ti=a}, +f8:function f8(a){this.a=a +this.c=this.b=null}, +bN:function bN(a,b,c){var _=this +_.a=a +_.b=b +_.d=_.c=null +_.$ti=c}, +h4:function h4(a,b,c){this.a=a +this.b=b +this.c=c}, +c8:function c8(a){var _=this +_.b=_.a=0 +_.c=null +_.$ti=a}, +di:function di(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=null +_.d=c +_.e=!1 +_.$ti=d}, +a4:function a4(){}, +r:function r(){}, +D:function D(){}, +h5:function h5(a){this.a=a}, +h7:function h7(a,b){this.a=a +this.b=b}, +cg:function cg(){}, +dj:function dj(a,b){this.a=a +this.$ti=b}, +dk:function dk(a,b,c){var _=this +_.a=a +_.b=b +_.c=null +_.$ti=c}, +dz:function dz(){}, +cc:function cc(){}, +dr:function dr(){}, +q6(a,b,c){var s,r,q,p,o=c-b +if(o<=4096)s=$.nK() +else s=new Uint8Array(o) +for(r=J.ap(a),q=0;q=16)return null +r=r*16+o}n=h-1 +if(!(h>=0&&h=0&&s=16)return null +r=r*16+o}m=n-1 +if(!(n>=0&&n=j)return A.b(i,0) +l=i[0]===0}else l=!1 +if(l)return $.b2() +l=A.as(j,i) +return new A.R(l===0?!1:c,i,l)}, +l2(a,b){var s,r,q,p,o,n +if(a==="")return null +s=$.nG().eF(a) +if(s==null)return null +r=s.b +q=r.length +if(1>=q)return A.b(r,1) +p=r[1]==="-" +if(4>=q)return A.b(r,4) +o=r[4] +n=r[3] +if(5>=q)return A.b(r,5) +if(o!=null)return A.pD(o,p) +if(n!=null)return A.pE(n,2,p) +return null}, +as(a,b){var s,r=b.length +while(!0){if(a>0){s=a-1 +if(!(s=0&&q=0;--s){p=s+c +if(!(s=0&&p=0;--s){q&2&&A.y(d) +if(!(s=0;--s){if(!(s=0&&n>>0 +p=B.c.aB((o&i)>>>0,k)}q&2&&A.y(d) +if(!(l>=0&&l=0;){r&2&&A.y(d) +if(!(q=0&&r=0&&m>>0,k) +q&2&&A.y(d) +if(!(p>>0 +s=B.c.aC(n,l)}q&2&&A.y(d) +if(!(r>=0&&r=0;--s){if(!(s=0&&o=0&&b=0&&o=0;e=l,c=o){o=c+1 +if(!(c=0&&e=0&&e=0&&c=0&&r>>0,a) +if(q>65535)return 65535 +return q}, +kc(a,b){var s=A.kE(a,b) +if(s!=null)return s +throw A.c(A.a3(a,null,null))}, +o5(a,b){a=A.a1(a,new Error()) +if(a==null)a=t.K.a(a) +a.stack=b.j(0) +throw a}, +cS(a,b,c,d){var s,r=c?J.ok(a,d):J.lO(a,d) +if(a!==0&&b!=null)for(s=0;s")) +for(s=J.W(a);s.m();)B.b.n(r,c.a(s.gp())) +if(b)return r +r.$flags=1 +return r}, +kB(a,b){var s,r +if(Array.isArray(a))return A.x(a.slice(0),b.h("E<0>")) +s=A.x([],b.h("E<0>")) +for(r=J.W(a);r.m();)B.b.n(s,r.gp()) +return s}, +eh(a,b){var s=A.kC(a,!1,b) +s.$flags=3 +return s}, +m8(a,b,c){var s,r +A.aa(b,"start") +if(c!=null){s=c-b +if(s<0)throw A.c(A.T(c,b,null,"end",null)) +if(s===0)return""}r=A.pl(a,b,c) +return r}, +pl(a,b,c){var s=a.length +if(b>=s)return"" +return A.oE(a,b,c==null||c>s?s:c)}, +ax(a,b){return new A.cJ(a,A.lQ(a,!1,b,!1,!1,""))}, +kS(a,b,c){var s=J.W(b) +if(!s.m())return a +if(c.length===0){do a+=A.o(s.gp()) +while(s.m())}else{a+=A.o(s.gp()) +for(;s.m();)a=a+c+A.o(s.gp())}return a}, +kV(){var s,r,q=A.oA() +if(q==null)throw A.c(A.U("'Uri.base' is not supported")) +s=$.me +if(s!=null&&q===$.md)return s +r=A.mf(q) +$.me=r +$.md=q +return r}, +ph(){return A.aj(new Error())}, +o4(a){var s=Math.abs(a),r=a<0?"-":"" +if(s>=1000)return""+a +if(s>=100)return r+"0"+s +if(s>=10)return r+"00"+s +return r+"000"+s}, +lH(a){if(a>=100)return""+a +if(a>=10)return"0"+a +return"00"+a}, +e4(a){if(a>=10)return""+a +return"0"+a}, +fV(a){if(typeof a=="number"||A.dG(a)||a==null)return J.aC(a) +if(typeof a=="string")return JSON.stringify(a) +return A.m1(a)}, +o6(a,b){A.k3(a,"error",t.K) +A.k3(b,"stackTrace",t.l) +A.o5(a,b)}, +dO(a){return new A.dN(a)}, +a2(a,b){return new A.aw(!1,null,b,a)}, +aM(a,b,c){return new A.aw(!0,a,b,c)}, +cw(a,b,c){return a}, +m2(a,b){return new A.cb(null,null,!0,a,b,"Value not in range")}, +T(a,b,c,d,e){return new A.cb(b,c,!0,a,d,"Invalid value")}, +oG(a,b,c,d){if(ac)throw A.c(A.T(a,b,c,d,null)) +return a}, +bw(a,b,c){if(0>a||a>c)throw A.c(A.T(a,0,c,"start",null)) +if(b!=null){if(a>b||b>c)throw A.c(A.T(b,a,c,"end",null)) +return b}return c}, +aa(a,b){if(a<0)throw A.c(A.T(a,0,null,b,null)) +return a}, +lL(a,b){var s=b.b +return new A.cF(s,!0,a,null,"Index out of range")}, +ea(a,b,c,d,e){return new A.cF(b,!0,a,e,"Index out of range")}, +od(a,b,c,d,e){if(0>a||a>=b)throw A.c(A.ea(a,b,c,d,e==null?"index":e)) +return a}, +U(a){return new A.d7(a)}, +mb(a){return new A.eH(a)}, +Q(a){return new A.bz(a)}, +a9(a){return new A.e_(a)}, +lI(a){return new A.iF(a)}, +a3(a,b,c){return new A.fW(a,b,c)}, +oj(a,b,c){var s,r +if(A.lk(a)){if(b==="("&&c===")")return"(...)" +return b+"..."+c}s=A.x([],t.s) +B.b.n($.ar,a) +try{A.qF(a,s)}finally{if(0>=$.ar.length)return A.b($.ar,-1) +$.ar.pop()}r=A.kS(b,t.hf.a(s),", ")+c +return r.charCodeAt(0)==0?r:r}, +kw(a,b,c){var s,r +if(A.lk(a))return b+"..."+c +s=new A.ac(b) +B.b.n($.ar,a) +try{r=s +r.a=A.kS(r.a,a,", ")}finally{if(0>=$.ar.length)return A.b($.ar,-1) +$.ar.pop()}s.a+=c +r=s.a +return r.charCodeAt(0)==0?r:r}, +qF(a,b){var s,r,q,p,o,n,m,l=a.gu(a),k=0,j=0 +while(!0){if(!(k<80||j<3))break +if(!l.m())return +s=A.o(l.gp()) +B.b.n(b,s) +k+=s.length+2;++j}if(!l.m()){if(j<=5)return +if(0>=b.length)return A.b(b,-1) +r=b.pop() +if(0>=b.length)return A.b(b,-1) +q=b.pop()}else{p=l.gp();++j +if(!l.m()){if(j<=4){B.b.n(b,A.o(p)) +return}r=A.o(p) +if(0>=b.length)return A.b(b,-1) +q=b.pop() +k+=r.length+2}else{o=l.gp();++j +for(;l.m();p=o,o=n){n=l.gp();++j +if(j>100){while(!0){if(!(k>75&&j>3))break +if(0>=b.length)return A.b(b,-1) +k-=b.pop().length+2;--j}B.b.n(b,"...") +return}}q=A.o(p) +r=A.o(o) +k+=r.length+q.length+4}}if(j>b.length+2){k+=5 +m="..."}else m=null +while(!0){if(!(k>80&&b.length>3))break +if(0>=b.length)return A.b(b,-1) +k-=b.pop().length+2 +if(m==null){k+=5 +m="..."}}if(m!=null)B.b.n(b,m) +B.b.n(b,q) +B.b.n(b,r)}, +lT(a,b,c,d){var s +if(B.h===c){s=B.c.gv(a) +b=J.aL(b) +return A.kT(A.bb(A.bb($.ks(),s),b))}if(B.h===d){s=B.c.gv(a) +b=J.aL(b) +c=J.aL(c) +return A.kT(A.bb(A.bb(A.bb($.ks(),s),b),c))}s=B.c.gv(a) +b=J.aL(b) +c=J.aL(c) +d=J.aL(d) +d=A.kT(A.bb(A.bb(A.bb(A.bb($.ks(),s),b),c),d)) +return d}, +au(a){var s=$.nm +if(s==null)A.nl(a) +else s.$1(a)}, +mf(a5){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1,a2,a3=null,a4=a5.length +if(a4>=5){if(4>=a4)return A.b(a5,4) +s=((a5.charCodeAt(4)^58)*3|a5.charCodeAt(0)^100|a5.charCodeAt(1)^97|a5.charCodeAt(2)^116|a5.charCodeAt(3)^97)>>>0 +if(s===0)return A.mc(a4=14)B.b.l(r,7,a4) +q=r[1] +if(q>=0)if(A.n9(a5,0,q,20,r)===20)r[7]=q +p=r[2]+1 +o=r[3] +n=r[4] +m=r[5] +l=r[6] +if(lq+3)){i=o>0 +if(!(i&&o+1===n)){if(!B.a.K(a5,"\\",n))if(p>0)h=B.a.K(a5,"\\",p-1)||B.a.K(a5,"\\",p-2) +else h=!1 +else h=!0 +if(!h){if(!(mn+2&&B.a.K(a5,"/..",m-3) +else h=!0 +if(!h)if(q===4){if(B.a.K(a5,"file",0)){if(p<=0){if(!B.a.K(a5,"/",n)){g="file:///" +s=3}else{g="file://" +s=2}a5=g+B.a.q(a5,n,a4) +m+=s +l+=s +a4=a5.length +p=7 +o=7 +n=7}else if(n===m){++l +f=m+1 +a5=B.a.au(a5,n,m,"/");++a4 +m=f}j="file"}else if(B.a.K(a5,"http",0)){if(i&&o+3===n&&B.a.K(a5,"80",o+1)){l-=3 +e=n-3 +m-=3 +a5=B.a.au(a5,o,n,"") +a4-=3 +n=e}j="http"}}else if(q===5&&B.a.K(a5,"https",0)){if(i&&o+4===n&&B.a.K(a5,"443",o+1)){l-=4 +e=n-4 +m-=4 +a5=B.a.au(a5,o,n,"") +a4-=3 +n=e}j="https"}k=!h}}}}if(k)return new A.fi(a40)j=A.q1(a5,0,q) +else{if(q===0)A.co(a5,0,"Invalid empty scheme") +j=""}d=a3 +if(p>0){c=q+3 +b=c=0&&r9)j.$2("invalid character",r)}else{if(p===3)j.$2(l,r) +n=A.kc(B.a.q(a,q,r),null) +if(n>255)j.$2(k,q) +m=p+1 +if(!(p<4))return A.b(i,p) +i[p]=n +q=r+1 +p=m}}if(p!==3)j.$2(l,c) +n=A.kc(B.a.q(a,q,c),null) +if(n>255)j.$2(k,q) +if(!(p<4))return A.b(i,p) +i[p]=n +return i}, +mg(a,a0,a1){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e=null,d=new A.ic(a),c=new A.id(d,a),b=a.length +if(b<2)d.$2("address is too short",e) +s=A.x([],t.t) +for(r=a0,q=r,p=!1,o=!1;r=0&&r>>0) +B.b.n(s,(l[2]<<8|l[3])>>>0)}if(p){if(s.length>7)d.$2("an address with a wildcard must have less than 7 parts",e)}else if(s.length!==8)d.$2("an address without a wildcard must contain exactly 8 parts",e) +k=new Uint8Array(16) +for(b=s.length,j=9-b,r=0,i=0;r=0&&i<16))return A.b(k,i) +k[i]=0 +f=i+1 +if(!(f<16))return A.b(k,f) +k[f]=0 +i+=2}else{f=B.c.F(h,8) +if(!(i>=0&&i<16))return A.b(k,i) +k[i]=f +f=i+1 +if(!(f<16))return A.b(k,f) +k[f]=h&255 +i+=2}}return k}, +mC(a,b,c,d,e,f,g){return new A.dA(a,b,c,d,e,f,g)}, +mD(a){if(a==="http")return 80 +if(a==="https")return 443 +return 0}, +co(a,b,c){throw A.c(A.a3(c,a,b))}, +pZ(a,b){var s,r,q +for(s=a.length,r=0;r=0&&b=0&&r=b&&q=b&&s=0&&r=o){if(h==null)h=new A.ac("") +if(q=0&&r=n){if(p==null)p=new A.ac("") +if(q=k)return"%" +s=b+1 +if(!(s>=0&&s=0))return A.b(a,l) +q=a.charCodeAt(l) +p=A.k8(r) +o=A.k8(q) +if(p<0||o<0)return"%" +n=p*16+o +if(n<127){if(!(n>=0))return A.b(m,n) +l=(m.charCodeAt(n)&1)!==0}else l=!1 +if(l)return A.aS(c&&65<=n&&90>=n?(n|32)>>>0:n) +if(r>=97||q>=97)return B.a.q(a,b,b+3).toUpperCase() +return null}, +l6(a){var s,r,q,p,o,n,m,l,k="0123456789ABCDEF" +if(a<=127){s=new Uint8Array(3) +s[0]=37 +r=a>>>4 +if(!(r<16))return A.b(k,r) +s[1]=k.charCodeAt(r) +s[2]=k.charCodeAt(a&15)}else{if(a>2047)if(a>65535){q=240 +p=4}else{q=224 +p=3}else{q=192 +p=2}r=3*p +s=new Uint8Array(r) +for(o=0;--p,p>=0;q=128){n=B.c.ec(a,6*p)&63|q +if(!(o>>4 +if(!(l<16))return A.b(k,l) +if(!(m=0&&q=m)return A.b(s,-1) +s.pop() +if(s.length===0)B.b.n(s,"")}p=!0}else{p="."===n +if(!p)B.b.n(s,n)}}if(p)B.b.n(s,"") +return B.b.af(s,"/")}, +mO(a,b){var s,r,q,p,o,n +if(!A.mM(a))return!b?A.mE(a):a +s=A.x([],t.s) +for(r=a.split("/"),q=r.length,p=!1,o=0;o=s.length)return A.b(s,-1) +s.pop()}else B.b.n(s,"..")}else{p="."===n +if(!p)B.b.n(s,n)}}r=s.length +if(r!==0)if(r===1){if(0>=r)return A.b(s,0) +r=s[0].length===0}else r=!1 +else r=!0 +if(r)return"./" +if(p||B.b.ga2(s)==="..")B.b.n(s,"") +if(!b){if(0>=s.length)return A.b(s,0) +B.b.l(s,0,A.mE(s[0]))}return B.b.af(s,"/")}, +mE(a){var s,r,q,p=u.f,o=a.length +if(o>=2&&A.mF(a.charCodeAt(0)))for(s=1;s127)throw A.c(A.a2("Illegal percent encoding in URI",null)) +if(r===37){if(n+3>o)throw A.c(A.a2("Truncated URI",null)) +B.b.n(p,A.q0(a,n+1)) +n+=2}else B.b.n(p,r)}}return d.aL(p)}, +mF(a){var s=a|32 +return 97<=s&&s<=122}, +mc(a,b,c){var s,r,q,p,o,n,m,l,k="Invalid MIME type",j=A.x([b-1],t.t) +for(s=a.length,r=b,q=-1,p=null;rb)throw A.c(A.a3(k,a,r)) +for(;p!==44;){B.b.n(j,r);++r +for(o=-1;r=0))return A.b(a,r) +p=a.charCodeAt(r) +if(p===61){if(o<0)o=r}else if(p===59||p===44)break}if(o>=0)B.b.n(j,o) +else{n=B.b.ga2(j) +if(p!==44||r!==n+7||!B.a.K(a,"base64",n+1))throw A.c(A.a3("Expecting '='",a,r)) +break}}B.b.n(j,r) +m=r+1 +if((j.length&1)===1)a=B.u.f6(a,m,s) +else{l=A.mN(a,m,s,256,!0,!1) +if(l!=null)a=B.a.au(a,m,s,l)}return new A.ia(a,j,c)}, +n9(a,b,c,d,e){var s,r,q,p,o,n='\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe1\xe1\x01\xe1\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe3\xe1\xe1\x01\xe1\x01\xe1\xcd\x01\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x0e\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01"\x01\xe1\x01\xe1\xac\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe1\xe1\x01\xe1\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xea\xe1\xe1\x01\xe1\x01\xe1\xcd\x01\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\n\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01"\x01\xe1\x01\xe1\xac\xeb\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\xeb\xeb\xeb\x8b\xeb\xeb\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\xeb\x83\xeb\xeb\x8b\xeb\x8b\xeb\xcd\x8b\xeb\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x92\x83\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\x8b\xeb\x8b\xeb\x8b\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xebD\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\x12D\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xe5\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\xe5\xe5\xe5\x05\xe5D\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe8\x8a\xe5\xe5\x05\xe5\x05\xe5\xcd\x05\xe5\x05\x05\x05\x05\x05\x05\x05\x05\x05\x8a\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05f\x05\xe5\x05\xe5\xac\xe5\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\xe5\xe5\xe5\x05\xe5D\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\xe5\x8a\xe5\xe5\x05\xe5\x05\xe5\xcd\x05\xe5\x05\x05\x05\x05\x05\x05\x05\x05\x05\x8a\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05f\x05\xe5\x05\xe5\xac\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7D\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\x8a\xe7\xe7\xe7\xe7\xe7\xe7\xcd\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\x8a\xe7\x07\x07\x07\x07\x07\x07\x07\x07\x07\xe7\xe7\xe7\xe7\xe7\xac\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7D\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\x8a\xe7\xe7\xe7\xe7\xe7\xe7\xcd\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\xe7\x8a\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\xe7\xe7\xe7\xe7\xe7\xac\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\x05\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\x10\xea\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\x12\n\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\v\n\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xec\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\xec\xec\xec\f\xec\xec\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\xec\xec\xec\xec\f\xec\f\xec\xcd\f\xec\f\f\f\f\f\f\f\f\f\xec\f\f\f\f\f\f\f\f\f\f\xec\f\xec\f\xec\f\xed\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\xed\xed\xed\r\xed\xed\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\xed\xed\xed\xed\r\xed\r\xed\xed\r\xed\r\r\r\r\r\r\r\r\r\xed\r\r\r\r\r\r\r\r\r\r\xed\r\xed\r\xed\r\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe1\xe1\x01\xe1\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xea\xe1\xe1\x01\xe1\x01\xe1\xcd\x01\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x0f\xea\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01"\x01\xe1\x01\xe1\xac\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe1\xe1\x01\xe1\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xe1\xe9\xe1\xe1\x01\xe1\x01\xe1\xcd\x01\xe1\x01\x01\x01\x01\x01\x01\x01\x01\x01\t\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01"\x01\xe1\x01\xe1\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\x11\xea\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xe9\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\v\t\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\x13\xea\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xeb\xeb\v\xeb\xeb\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\v\xeb\xea\xeb\xeb\v\xeb\v\xeb\xcd\v\xeb\v\v\v\v\v\v\v\v\v\xea\v\v\v\v\v\v\v\v\v\v\xeb\v\xeb\v\xeb\xac\xf5\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\xf5\x15\xf5\x15\x15\xf5\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\xf5\xf5\xf5\xf5\xf5\xf5' +for(s=a.length,r=b;r95)q=31 +p=d*96+q +if(!(p<2112))return A.b(n,p) +o=n.charCodeAt(p) +d=o&31 +B.b.l(e,o>>>5,r)}return d}, +R:function R(a,b,c){this.a=a +this.b=b +this.c=c}, +iw:function iw(){}, +ix:function ix(){}, +f2:function f2(a,b){this.a=a +this.$ti=b}, +bk:function bk(a,b,c){this.a=a +this.b=b +this.c=c}, +b6:function b6(a){this.a=a}, +iC:function iC(){}, +J:function J(){}, +dN:function dN(a){this.a=a}, +aV:function aV(){}, +aw:function aw(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d}, +cb:function cb(a,b,c,d,e,f){var _=this +_.e=a +_.f=b +_.a=c +_.b=d +_.c=e +_.d=f}, +cF:function cF(a,b,c,d,e){var _=this +_.f=a +_.a=b +_.b=c +_.c=d +_.d=e}, +d7:function d7(a){this.a=a}, +eH:function eH(a){this.a=a}, +bz:function bz(a){this.a=a}, +e_:function e_(a){this.a=a}, +eq:function eq(){}, +d5:function d5(){}, +iF:function iF(a){this.a=a}, +fW:function fW(a,b,c){this.a=a +this.b=b +this.c=c}, +ec:function ec(){}, +e:function e(){}, +K:function K(a,b,c){this.a=a +this.b=b +this.$ti=c}, +F:function F(){}, +q:function q(){}, +fo:function fo(){}, +ac:function ac(a){this.a=a}, +ib:function ib(a){this.a=a}, +ic:function ic(a){this.a=a}, +id:function id(a,b){this.a=a +this.b=b}, +dA:function dA(a,b,c,d,e,f,g){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f +_.r=g +_.y=_.x=_.w=$}, +ia:function ia(a,b,c){this.a=a +this.b=b +this.c=c}, +fi:function fi(a,b,c,d,e,f,g,h){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f +_.r=g +_.w=h +_.x=null}, +f0:function f0(a,b,c,d,e,f,g){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f +_.r=g +_.y=_.x=_.w=$}, +e6:function e6(a,b){this.a=a +this.$ti=b}, +at(a){var s +if(typeof a=="function")throw A.c(A.a2("Attempting to rewrap a JS function.",null)) +s=function(b,c){return function(d){return b(c,d,arguments.length)}}(A.qd,a) +s[$.cu()]=a +return s}, +bh(a){var s +if(typeof a=="function")throw A.c(A.a2("Attempting to rewrap a JS function.",null)) +s=function(b,c){return function(d,e){return b(c,d,e,arguments.length)}}(A.qe,a) +s[$.cu()]=a +return s}, +fs(a){var s +if(typeof a=="function")throw A.c(A.a2("Attempting to rewrap a JS function.",null)) +s=function(b,c){return function(d,e,f){return b(c,d,e,f,arguments.length)}}(A.qf,a) +s[$.cu()]=a +return s}, +jW(a){var s +if(typeof a=="function")throw A.c(A.a2("Attempting to rewrap a JS function.",null)) +s=function(b,c){return function(d,e,f,g){return b(c,d,e,f,g,arguments.length)}}(A.qg,a) +s[$.cu()]=a +return s}, +la(a){var s +if(typeof a=="function")throw A.c(A.a2("Attempting to rewrap a JS function.",null)) +s=function(b,c){return function(d,e,f,g,h){return b(c,d,e,f,g,h,arguments.length)}}(A.qh,a) +s[$.cu()]=a +return s}, +qd(a,b,c){t.Z.a(a) +if(A.d(c)>=1)return a.$1(b) +return a.$0()}, +qe(a,b,c,d){t.Z.a(a) +A.d(d) +if(d>=2)return a.$2(b,c) +if(d===1)return a.$1(b) +return a.$0()}, +qf(a,b,c,d,e){t.Z.a(a) +A.d(e) +if(e>=3)return a.$3(b,c,d) +if(e===2)return a.$2(b,c) +if(e===1)return a.$1(b) +return a.$0()}, +qg(a,b,c,d,e,f){t.Z.a(a) +A.d(f) +if(f>=4)return a.$4(b,c,d,e) +if(f===3)return a.$3(b,c,d) +if(f===2)return a.$2(b,c) +if(f===1)return a.$1(b) +return a.$0()}, +qh(a,b,c,d,e,f,g){t.Z.a(a) +A.d(g) +if(g>=5)return a.$5(b,c,d,e,f) +if(g===4)return a.$4(b,c,d,e) +if(g===3)return a.$3(b,c,d) +if(g===2)return a.$2(b,c) +if(g===1)return a.$1(b) +return a.$0()}, +fu(a,b,c,d){return d.a(a[b].apply(a,c))}, +ln(a,b){var s=new A.v($.w,b.h("v<0>")),r=new A.bH(s,b.h("bH<0>")) +a.then(A.bS(new A.km(r,b),1),A.bS(new A.kn(r),1)) +return s}, +km:function km(a,b){this.a=a +this.b=b}, +kn:function kn(a){this.a=a}, +h8:function h8(a){this.a=a}, +f7:function f7(a){this.a=a}, +ep:function ep(){}, +eJ:function eJ(){}, +qR(a,b){var s,r,q,p,o,n,m,l +for(s=b.length,r=1;r=1;s=q){q=s-1 +if(b[q]!=null)break}p=new A.ac("") +o=""+(a+"(") +p.a=o +n=A.a0(b) +m=n.h("bA<1>") +l=new A.bA(b,0,s,m) +l.dt(b,0,s,n.c) +m=o+new A.a5(l,m.h("h(Y.E)").a(new A.k_()),m.h("a5")).af(0,", ") +p.a=m +p.a=m+("): part "+(r-1)+" was null, but part "+r+" was not.") +throw A.c(A.a2(p.j(0),null))}}, +e0:function e0(a){this.a=a}, +fR:function fR(){}, +k_:function k_(){}, +c5:function c5(){}, +lU(a,b){var s,r,q,p,o,n,m=b.dg(a) +b.aq(a) +if(m!=null)a=B.a.Z(a,m.length) +s=t.s +r=A.x([],s) +q=A.x([],s) +s=a.length +if(s!==0){if(0>=s)return A.b(a,0) +p=b.a1(a.charCodeAt(0))}else p=!1 +if(p){if(0>=s)return A.b(a,0) +B.b.n(q,a[0]) +o=1}else{B.b.n(q,"") +o=0}for(n=o;n50)return B.a.q(s,0,50)+"..." +return s}, +qT(a){if(t.p.b(a))return"Blob("+a.length+")" +return A.q8(a)}, +ne(a){var s=a.$ti +return"["+new A.a5(a,s.h("h?(r.E)").a(new A.k2()),s.h("a5")).af(0,", ")+"]"}, +k2:function k2(){}, +e2:function e2(){}, +ey:function ey(){}, +hi:function hi(a){this.a=a}, +hj:function hj(a){this.a=a}, +fU:function fU(){}, +o7(a){var s=a.i(0,"method"),r=a.i(0,"arguments") +if(s!=null)return new A.e7(A.L(s),r) +return null}, +e7:function e7(a,b){this.a=a +this.b=b}, +c2:function c2(a,b){this.a=a +this.b=b}, +ez(a,b,c,d){var s=new A.aU(a,b,b,c) +s.b=d +return s}, +aU:function aU(a,b,c,d){var _=this +_.w=_.r=_.f=null +_.x=a +_.y=b +_.b=null +_.c=c +_.d=null +_.a=d}, +hx:function hx(){}, +hy:function hy(){}, +mY(a){var s=a.j(0) +return A.ez("sqlite_error",null,s,a.c)}, +jV(a,b,c,d){var s,r,q,p +if(a instanceof A.aU){s=a.f +if(s==null)s=a.f=b +r=a.r +if(r==null)r=a.r=c +q=a.w +if(q==null)q=a.w=d +p=s==null +if(!p||r!=null||q!=null)if(a.y==null){r=A.O(t.N,t.X) +if(!p)r.l(0,"database",s.d3()) +s=a.r +if(s!=null)r.l(0,"sql",s) +s=a.w +if(s!=null)r.l(0,"arguments",s) +a.sev(r)}return a}else if(a instanceof A.by)return A.jV(A.mY(a),b,c,d) +else return A.jV(A.ez("error",null,J.aC(a),null),b,c,d)}, +hW(a){return A.p5(a)}, +p5(a){var s=0,r=A.l(t.z),q,p=2,o=[],n,m,l,k,j,i,h +var $async$hW=A.m(function(b,c){if(b===1){o.push(c) +s=p}while(true)switch(s){case 0:p=4 +s=7 +return A.f(A.a7(a),$async$hW) +case 7:n=c +q=n +s=1 +break +p=2 +s=6 +break +case 4:p=3 +h=o.pop() +m=A.N(h) +A.aj(h) +j=A.m5(a) +i=A.ba(a,"sql",t.N) +l=A.jV(m,j,i,A.eA(a)) +throw A.c(l) +s=6 +break +case 3:s=2 +break +case 6:case 1:return A.j(q,r) +case 2:return A.i(o.at(-1),r)}}) +return A.k($async$hW,r)}, +d2(a,b){var s=A.hD(a) +return s.aM(A.fq(t.f.a(a.b).i(0,"transactionId")),new A.hC(b,s))}, +bx(a,b){return $.nN().a0(new A.hB(b),t.z)}, +a7(a){return A.pf(a)}, +pf(a){var s=0,r=A.l(t.z),q,p +var $async$a7=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=a.a +case 3:switch(p){case"openDatabase":s=5 +break +case"closeDatabase":s=6 +break +case"query":s=7 +break +case"queryCursorNext":s=8 +break +case"execute":s=9 +break +case"insert":s=10 +break +case"update":s=11 +break +case"batch":s=12 +break +case"getDatabasesPath":s=13 +break +case"deleteDatabase":s=14 +break +case"databaseExists":s=15 +break +case"options":s=16 +break +case"writeDatabaseBytes":s=17 +break +case"readDatabaseBytes":s=18 +break +case"debugMode":s=19 +break +default:s=20 +break}break +case 5:s=21 +return A.f(A.bx(a,A.oT(a)),$async$a7) +case 21:q=c +s=1 +break +case 6:s=22 +return A.f(A.bx(a,A.oN(a)),$async$a7) +case 22:q=c +s=1 +break +case 7:s=23 +return A.f(A.d2(a,A.oV(a)),$async$a7) +case 23:q=c +s=1 +break +case 8:s=24 +return A.f(A.d2(a,A.oW(a)),$async$a7) +case 24:q=c +s=1 +break +case 9:s=25 +return A.f(A.d2(a,A.oQ(a)),$async$a7) +case 25:q=c +s=1 +break +case 10:s=26 +return A.f(A.d2(a,A.oS(a)),$async$a7) +case 26:q=c +s=1 +break +case 11:s=27 +return A.f(A.d2(a,A.oY(a)),$async$a7) +case 27:q=c +s=1 +break +case 12:s=28 +return A.f(A.d2(a,A.oM(a)),$async$a7) +case 28:q=c +s=1 +break +case 13:s=29 +return A.f(A.bx(a,A.oR(a)),$async$a7) +case 29:q=c +s=1 +break +case 14:s=30 +return A.f(A.bx(a,A.oP(a)),$async$a7) +case 30:q=c +s=1 +break +case 15:s=31 +return A.f(A.bx(a,A.oO(a)),$async$a7) +case 31:q=c +s=1 +break +case 16:s=32 +return A.f(A.bx(a,A.oU(a)),$async$a7) +case 32:q=c +s=1 +break +case 17:s=33 +return A.f(A.bx(a,A.oZ(a)),$async$a7) +case 33:q=c +s=1 +break +case 18:s=34 +return A.f(A.bx(a,A.oX(a)),$async$a7) +case 34:q=c +s=1 +break +case 19:s=35 +return A.f(A.kK(a),$async$a7) +case 35:q=c +s=1 +break +case 20:throw A.c(A.a2("Invalid method "+p+" "+a.j(0),null)) +case 4:case 1:return A.j(q,r)}}) +return A.k($async$a7,r)}, +oT(a){return new A.hN(a)}, +hX(a){return A.p7(a)}, +p7(a){var s=0,r=A.l(t.f),q,p=2,o=[],n,m,l,k,j,i,h,g,f,e,d,c +var $async$hX=A.m(function(b,a0){if(b===1){o.push(a0) +s=p}while(true)switch(s){case 0:h=t.f.a(a.b) +g=A.L(h.i(0,"path")) +f=new A.hY() +e=A.cp(h.i(0,"singleInstance")) +d=e===!0 +e=A.cp(h.i(0,"readOnly")) +if(d){l=$.fv.i(0,g) +if(l!=null){if($.ke>=2)l.ag("Reopening existing single database "+l.j(0)) +q=f.$1(l.e) +s=1 +break}}n=null +p=4 +k=$.ad +s=7 +return A.f((k==null?$.ad=A.bV():k).bi(h),$async$hX) +case 7:n=a0 +p=2 +s=6 +break +case 4:p=3 +c=o.pop() +h=A.N(c) +if(h instanceof A.by){m=h +h=m +f=h.j(0) +throw A.c(A.ez("sqlite_error",null,"open_failed: "+f,h.c))}else throw c +s=6 +break +case 3:s=2 +break +case 6:i=$.n4=$.n4+1 +h=n +k=$.ke +l=new A.an(A.x([],t.bi),A.kD(),i,d,g,e===!0,h,k,A.O(t.S,t.aT),A.kD()) +$.ng.l(0,i,l) +l.ag("Opening database "+l.j(0)) +if(d)$.fv.l(0,g,l) +q=f.$1(i) +s=1 +break +case 1:return A.j(q,r) +case 2:return A.i(o.at(-1),r)}}) +return A.k($async$hX,r)}, +oN(a){return new A.hH(a)}, +kI(a){return A.p_(a)}, +p_(a){var s=0,r=A.l(t.z),q +var $async$kI=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:q=A.hD(a) +if(q.f){$.fv.I(0,q.r) +if($.nc==null)$.nc=new A.fU()}q.aK() +return A.j(null,r)}}) +return A.k($async$kI,r)}, +hD(a){var s=A.m5(a) +if(s==null)throw A.c(A.Q("Database "+A.o(A.m6(a))+" not found")) +return s}, +m5(a){var s=A.m6(a) +if(s!=null)return $.ng.i(0,s) +return null}, +m6(a){var s=a.b +if(t.f.b(s))return A.fq(s.i(0,"id")) +return null}, +ba(a,b,c){var s=a.b +if(t.f.b(s))return c.h("0?").a(s.i(0,b)) +return null}, +pe(a){var s="transactionId",r=a.b +if(t.f.b(r))return r.L(s)&&r.i(0,s)==null +return!1}, +hF(a){var s,r,q=A.ba(a,"path",t.N) +if(q!=null&&q!==":memory:"&&$.ls().a.a7(q)<=0){if($.ad==null)$.ad=A.bV() +s=$.ls() +r=A.x(["/",q,null,null,null,null,null,null,null,null,null,null,null,null,null,null],t.d4) +A.qR("join",r) +q=s.f1(new A.d9(r,t.eJ))}return q}, +eA(a){var s,r,q,p=A.ba(a,"arguments",t.j),o=p==null +if(!o)for(s=J.W(p),r=t.p;s.m();){q=s.gp() +if(q!=null)if(typeof q!="number")if(typeof q!="string")if(!r.b(q))if(!(q instanceof A.R))throw A.c(A.a2("Invalid sql argument type '"+J.bW(q).j(0)+"': "+A.o(q),null))}return o?null:J.kt(p,t.X)}, +oL(a){var s=A.x([],t.eK),r=t.f +r=J.kt(t.j.a(r.a(a.b).i(0,"operations")),r) +r.M(r,new A.hE(s)) +return s}, +oV(a){return new A.hQ(a)}, +kN(a,b){return A.p9(a,b)}, +p9(a,b){var s=0,r=A.l(t.z),q,p,o +var $async$kN=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:o=A.ba(a,"sql",t.N) +o.toString +p=A.eA(a) +q=b.eN(A.fq(t.f.a(a.b).i(0,"cursorPageSize")),o,p) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kN,r)}, +oW(a){return new A.hP(a)}, +kO(a,b){return A.pa(a,b)}, +pa(a,b){var s=0,r=A.l(t.z),q,p,o +var $async$kO=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:b=A.hD(a) +p=t.f.a(a.b) +o=A.d(p.i(0,"cursorId")) +q=b.eO(A.cp(p.i(0,"cancel")),o) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kO,r)}, +hA(a,b){return A.oK(a,b)}, +oK(a,b){var s=0,r=A.l(t.X),q,p +var $async$hA=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:b=A.hD(a) +p=A.ba(a,"sql",t.N) +p.toString +s=3 +return A.f(b.eK(p,A.eA(a)),$async$hA) +case 3:q=null +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$hA,r)}, +oQ(a){return new A.hK(a)}, +hV(a,b){return A.p3(a,b)}, +p3(a,b){var s=0,r=A.l(t.X),q,p=2,o=[],n,m,l,k +var $async$hV=A.m(function(c,d){if(c===1){o.push(d) +s=p}while(true)switch(s){case 0:m=A.ba(a,"inTransaction",t.y) +l=m===!0&&A.pe(a) +if(l)b.b=++b.a +p=4 +s=7 +return A.f(A.hA(a,b),$async$hV) +case 7:p=2 +s=6 +break +case 4:p=3 +k=o.pop() +if(l)b.b=null +throw k +s=6 +break +case 3:s=2 +break +case 6:if(l){q=A.ah(["transactionId",b.b],t.N,t.X) +s=1 +break}else if(m===!1)b.b=null +q=null +s=1 +break +case 1:return A.j(q,r) +case 2:return A.i(o.at(-1),r)}}) +return A.k($async$hV,r)}, +oU(a){return new A.hO(a)}, +hZ(a){return A.p8(a)}, +p8(a){var s=0,r=A.l(t.z),q,p,o +var $async$hZ=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:o=a.b +s=t.f.b(o)?3:4 +break +case 3:if(o.L("logLevel")){p=A.fq(o.i(0,"logLevel")) +$.ke=p==null?0:p}p=$.ad +s=5 +return A.f((p==null?$.ad=A.bV():p).bZ(o),$async$hZ) +case 5:case 4:q=null +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$hZ,r)}, +kK(a){return A.p1(a)}, +p1(a){var s=0,r=A.l(t.z),q +var $async$kK=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:if(J.V(a.b,!0))$.ke=2 +q=null +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kK,r)}, +oS(a){return new A.hM(a)}, +kM(a,b){return A.p6(a,b)}, +p6(a,b){var s=0,r=A.l(t.I),q,p +var $async$kM=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:p=A.ba(a,"sql",t.N) +p.toString +q=b.eL(p,A.eA(a)) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kM,r)}, +oY(a){return new A.hS(a)}, +kP(a,b){return A.pc(a,b)}, +pc(a,b){var s=0,r=A.l(t.S),q,p +var $async$kP=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:p=A.ba(a,"sql",t.N) +p.toString +q=b.eQ(p,A.eA(a)) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kP,r)}, +oM(a){return new A.hG(a)}, +oR(a){return new A.hL(a)}, +kL(a){return A.p4(a)}, +p4(a){var s=0,r=A.l(t.z),q +var $async$kL=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:if($.ad==null)$.ad=A.bV() +q="/" +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kL,r)}, +oP(a){return new A.hJ(a)}, +hU(a){return A.p2(a)}, +p2(a){var s=0,r=A.l(t.H),q=1,p=[],o,n,m,l,k,j +var $async$hU=A.m(function(b,c){if(b===1){p.push(c) +s=q}while(true)switch(s){case 0:l=A.hF(a) +k=$.fv.i(0,l) +if(k!=null){k.aK() +$.fv.I(0,l)}q=3 +o=$.ad +if(o==null)o=$.ad=A.bV() +n=l +n.toString +s=6 +return A.f(o.b9(n),$async$hU) +case 6:q=1 +s=5 +break +case 3:q=2 +j=p.pop() +s=5 +break +case 2:s=1 +break +case 5:return A.j(null,r) +case 1:return A.i(p.at(-1),r)}}) +return A.k($async$hU,r)}, +oO(a){return new A.hI(a)}, +kJ(a){return A.p0(a)}, +p0(a){var s=0,r=A.l(t.y),q,p,o +var $async$kJ=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=A.hF(a) +o=$.ad +if(o==null)o=$.ad=A.bV() +p.toString +q=o.bc(p) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kJ,r)}, +oX(a){return new A.hR(a)}, +i_(a){return A.pb(a)}, +pb(a){var s=0,r=A.l(t.f),q,p,o,n +var $async$i_=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=A.hF(a) +o=$.ad +if(o==null)o=$.ad=A.bV() +p.toString +n=A +s=3 +return A.f(o.bk(p),$async$i_) +case 3:q=n.ah(["bytes",c],t.N,t.X) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$i_,r)}, +oZ(a){return new A.hT(a)}, +kQ(a){return A.pd(a)}, +pd(a){var s=0,r=A.l(t.H),q,p,o,n +var $async$kQ=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=A.hF(a) +o=A.ba(a,"bytes",t.p) +n=$.ad +if(n==null)n=$.ad=A.bV() +p.toString +o.toString +q=n.bn(p,o) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$kQ,r)}, +d3:function d3(){this.c=this.b=this.a=null}, +fj:function fj(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=!1}, +fb:function fb(a,b){this.a=a +this.b=b}, +an:function an(a,b,c,d,e,f,g,h,i,j){var _=this +_.a=0 +_.b=null +_.c=a +_.d=b +_.e=c +_.f=d +_.r=e +_.w=f +_.x=g +_.y=h +_.z=i +_.Q=0 +_.as=j}, +hs:function hs(a,b,c){this.a=a +this.b=b +this.c=c}, +hq:function hq(a){this.a=a}, +hl:function hl(a){this.a=a}, +ht:function ht(a,b,c){this.a=a +this.b=b +this.c=c}, +hw:function hw(a,b,c){this.a=a +this.b=b +this.c=c}, +hv:function hv(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d}, +hu:function hu(a,b,c){this.a=a +this.b=b +this.c=c}, +hr:function hr(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d}, +hp:function hp(){}, +ho:function ho(a,b){this.a=a +this.b=b}, +hm:function hm(a,b,c,d,e,f){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f}, +hn:function hn(a,b){this.a=a +this.b=b}, +hC:function hC(a,b){this.a=a +this.b=b}, +hB:function hB(a){this.a=a}, +hN:function hN(a){this.a=a}, +hY:function hY(){}, +hH:function hH(a){this.a=a}, +hE:function hE(a){this.a=a}, +hQ:function hQ(a){this.a=a}, +hP:function hP(a){this.a=a}, +hK:function hK(a){this.a=a}, +hO:function hO(a){this.a=a}, +hM:function hM(a){this.a=a}, +hS:function hS(a){this.a=a}, +hG:function hG(a){this.a=a}, +hL:function hL(a){this.a=a}, +hJ:function hJ(a){this.a=a}, +hI:function hI(a){this.a=a}, +hR:function hR(a){this.a=a}, +hT:function hT(a){this.a=a}, +hk:function hk(a){this.a=a}, +hz:function hz(a){var _=this +_.a=a +_.b=$ +_.d=_.c=null}, +fk:function fk(){}, +dF(a){return A.qq(a)}, +qq(a8){var s=0,r=A.l(t.H),q=1,p=[],o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1,a2,a3,a4,a5,a6,a7 +var $async$dF=A.m(function(a9,b0){if(a9===1){p.push(b0) +s=q}while(true)switch(s){case 0:a4=a8.data +a5=a4==null?null:A.kR(a4) +a4=t.c.a(a8.ports) +o=J.b4(t.k.b(a4)?a4:new A.ae(a4,A.a0(a4).h("ae<1,C>"))) +q=3 +s=typeof a5=="string"?6:8 +break +case 6:o.postMessage(a5) +s=7 +break +case 8:s=t.j.b(a5)?9:11 +break +case 9:n=J.b3(a5,0) +if(J.V(n,"varSet")){m=t.f.a(J.b3(a5,1)) +l=A.L(J.b3(m,"key")) +k=J.b3(m,"value") +A.au($.dJ+" "+A.o(n)+" "+A.o(l)+": "+A.o(k)) +$.np.l(0,l,k) +o.postMessage(null)}else if(J.V(n,"varGet")){j=t.f.a(J.b3(a5,1)) +i=A.L(J.b3(j,"key")) +h=$.np.i(0,i) +A.au($.dJ+" "+A.o(n)+" "+A.o(i)+": "+A.o(h)) +a4=t.N +o.postMessage(A.i1(A.ah(["result",A.ah(["key",i,"value",h],a4,t.X)],a4,t.a)))}else{A.au($.dJ+" "+A.o(n)+" unknown") +o.postMessage(null)}s=10 +break +case 11:s=t.f.b(a5)?12:14 +break +case 12:g=A.o7(a5) +s=g!=null?15:17 +break +case 15:g=new A.e7(g.a,A.l8(g.b)) +s=$.nb==null?18:19 +break +case 18:s=20 +return A.f(A.fw(new A.i0(),!0),$async$dF) +case 20:a4=b0 +$.nb=a4 +a4.toString +$.ad=new A.hz(a4) +case 19:f=new A.jX(o) +q=22 +s=25 +return A.f(A.hW(g),$async$dF) +case 25:e=b0 +e=A.l9(e) +f.$1(new A.c2(e,null)) +q=3 +s=24 +break +case 22:q=21 +a6=p.pop() +d=A.N(a6) +c=A.aj(a6) +a4=d +a1=c +a2=new A.c2($,$) +a3=A.O(t.N,t.X) +if(a4 instanceof A.aU){a3.l(0,"code",a4.x) +a3.l(0,"details",a4.y) +a3.l(0,"message",a4.a) +a3.l(0,"resultCode",a4.bt()) +a4=a4.d +a3.l(0,"transactionClosed",a4===!0)}else a3.l(0,"message",J.aC(a4)) +a4=$.n3 +if(!(a4==null?$.n3=!0:a4)&&a1!=null)a3.l(0,"stackTrace",a1.j(0)) +a2.b=a3 +a2.a=null +f.$1(a2) +s=24 +break +case 21:s=3 +break +case 24:s=16 +break +case 17:A.au($.dJ+" "+a5.j(0)+" unknown") +o.postMessage(null) +case 16:s=13 +break +case 14:A.au($.dJ+" "+A.o(a5)+" map unknown") +o.postMessage(null) +case 13:case 10:case 7:q=1 +s=5 +break +case 3:q=2 +a7=p.pop() +b=A.N(a7) +a=A.aj(a7) +A.au($.dJ+" error caught "+A.o(b)+" "+A.o(a)) +o.postMessage(null) +s=5 +break +case 2:s=1 +break +case 5:return A.j(null,r) +case 1:return A.i(p.at(-1),r)}}) +return A.k($async$dF,r)}, +ri(a){var s,r,q,p,o,n,m=$.w +try{s=v.G +try{r=A.L(s.name)}catch(n){q=A.N(n)}s.onconnect=A.at(new A.kj(m))}catch(n){}p=v.G +try{p.onmessage=A.at(new A.kk(m))}catch(n){o=A.N(n)}}, +jX:function jX(a){this.a=a}, +kj:function kj(a){this.a=a}, +ki:function ki(a,b){this.a=a +this.b=b}, +kg:function kg(a){this.a=a}, +kf:function kf(a){this.a=a}, +kk:function kk(a){this.a=a}, +kh:function kh(a){this.a=a}, +n0(a){if(a==null)return!0 +else if(typeof a=="number"||typeof a=="string"||A.dG(a))return!0 +return!1}, +n5(a){var s +if(a.gk(a)===1){s=J.b4(a.gN()) +if(typeof s=="string")return B.a.J(s,"@") +throw A.c(A.aM(s,null,null))}return!1}, +l9(a){var s,r,q,p,o,n,m,l +if(A.n0(a))return a +a.toString +for(s=$.lr(),r=0;r<1;++r){q=s[r] +p=A.u(q).h("cn.T") +if(p.b(a))return A.ah(["@"+q.a,t.dG.a(p.a(a)).j(0)],t.N,t.X)}if(t.f.b(a)){s={} +if(A.n5(a))return A.ah(["@",a],t.N,t.X) +s.a=null +a.M(0,new A.jU(s,a)) +s=s.a +if(s==null)s=a +return s}else if(t.j.b(a)){for(s=J.ap(a),p=t.z,o=null,n=0;n"));q.m();){n=q.c +n=n>=0?new A.bf(o+n,p.gp()):A.H(A.aE()) +m=n.b +l=m==null?null:A.i1(m) +r[n.a]=l}return r}else if(A.dG(a))return a +throw A.c(A.U("Unsupported value: "+A.o(a)+" (type: "+J.bW(a).j(0)+")"))}, +i2:function i2(a){this.a=a}, +i0:function i0(){}, +d4:function d4(){}, +ko(a){return A.rk(a)}, +rk(a){var s=0,r=A.l(t.e),q,p +var $async$ko=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=A +s=3 +return A.f(A.eb("sqflite_databases"),$async$ko) +case 3:q=p.m7(c,a,null) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$ko,r)}, +fw(a,b){return A.rl(a,!0)}, +rl(a,b){var s=0,r=A.l(t.e),q,p,o,n,m,l,k,j,i,h +var $async$fw=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:s=3 +return A.f(A.ko(a),$async$fw) +case 3:h=d +h=h +p=$.nM() +o=h.b +s=4 +return A.f(A.il(p),$async$fw) +case 4:n=d +m=n.a +m=m.b +l=m.b4(B.f.an(o.a),1) +k=m.c.e +j=k.a +k.l(0,j,o) +i=A.d(A.p(m.y.call(null,l,j,1))) +if(i===0)A.H(A.Q("could not register vfs")) +m=$.nr() +m.$ti.h("1?").a(i) +m.a.set(o,i) +q=A.m7(o,a,n) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$fw,r)}, +m7(a,b,c){return new A.eB(a,c)}, +eB:function eB(a,b){this.b=a +this.c=b +this.f=$}, +pg(a,b,c,d,e,f,g){return new A.by(b,c,a,g,f,d,e)}, +by:function by(a,b,c,d,e,f,g){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.e=e +_.f=f +_.r=g}, +i4:function i4(){}, +eu:function eu(){}, +eC:function eC(a,b,c){this.a=a +this.b=b +this.$ti=c}, +ev:function ev(){}, +hf:function hf(){}, +cZ:function cZ(){}, +hd:function hd(){}, +he:function he(){}, +e8:function e8(a,b,c){this.b=a +this.c=b +this.d=c}, +e3:function e3(a,b,c){var _=this +_.a=a +_.b=b +_.c=c +_.r=!1}, +fT:function fT(a,b){this.a=a +this.b=b}, +aN:function aN(){}, +k6:function k6(){}, +i3:function i3(){}, +c3:function c3(a){this.b=a +this.c=!0 +this.d=!1}, +ce:function ce(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d +_.f=_.e=null}, +eW:function eW(a,b,c){var _=this +_.r=a +_.w=-1 +_.x=$ +_.y=!1 +_.a=b +_.c=c}, +oc(a){var s=$.kq() +return new A.e9(A.O(t.N,t.fN),s,"dart-memory")}, +e9:function e9(a,b,c){this.d=a +this.b=b +this.a=c}, +f4:function f4(a,b,c){var _=this +_.a=a +_.b=b +_.c=c +_.d=0}, +c_:function c_(){}, +cG:function cG(){}, +ew:function ew(a,b,c){this.d=a +this.a=b +this.c=c}, +ab:function ab(a,b){this.a=a +this.b=b}, +fc:function fc(a){this.a=a +this.b=-1}, +fd:function fd(){}, +fe:function fe(){}, +fg:function fg(){}, +fh:function fh(){}, +cY:function cY(a){this.b=a}, +dY:function dY(){}, +bq:function bq(a){this.a=a}, +eN(a){return new A.d8(a)}, +ly(a,b){var s,r,q +if(b==null)b=$.kq() +for(s=a.length,r=0;r")),r=new A.a_(s,b.h("a_<0>")),q=t.w,p=t.m +A.bK(a,"success",q.a(new A.fM(r,a,b)),!1,p) +A.bK(a,"error",q.a(new A.fN(r,a)),!1,p) +return s}, +o3(a,b){var s=new A.v($.w,b.h("v<0>")),r=new A.a_(s,b.h("a_<0>")),q=t.w,p=t.m +A.bK(a,"success",q.a(new A.fO(r,a,b)),!1,p) +A.bK(a,"error",q.a(new A.fP(r,a)),!1,p) +A.bK(a,"blocked",q.a(new A.fQ(r,a)),!1,p) +return s}, +bJ:function bJ(a,b){var _=this +_.c=_.b=_.a=null +_.d=a +_.$ti=b}, +iA:function iA(a,b){this.a=a +this.b=b}, +iB:function iB(a,b){this.a=a +this.b=b}, +fM:function fM(a,b,c){this.a=a +this.b=b +this.c=c}, +fN:function fN(a,b){this.a=a +this.b=b}, +fO:function fO(a,b,c){this.a=a +this.b=b +this.c=c}, +fP:function fP(a,b){this.a=a +this.b=b}, +fQ:function fQ(a,b){this.a=a +this.b=b}, +ih(a,b){return A.pt(a,b)}, +pt(a,b){var s=0,r=A.l(t.g9),q,p,o,n,m,l +var $async$ih=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:l={} +b.M(0,new A.ij(l)) +p=t.m +s=3 +return A.f(A.ln(p.a(v.G.WebAssembly.instantiateStreaming(a,l)),p),$async$ih) +case 3:o=d +n=p.a(p.a(o.instance).exports) +if("_initialize" in n)t.g.a(n._initialize).call() +m=t.N +m=new A.eR(A.O(m,t.g),A.O(m,p)) +m.du(p.a(o.instance)) +q=m +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$ih,r)}, +eR:function eR(a,b){this.a=a +this.b=b}, +ij:function ij(a){this.a=a}, +ii:function ii(a){this.a=a}, +il(a){return A.pv(a)}, +pv(a){var s=0,r=A.l(t.ab),q,p,o,n,m +var $async$il=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=v.G +o=t.m +n=a.gcX()?o.a(new p.URL(a.j(0))):o.a(new p.URL(a.j(0),A.kV().j(0))) +m=A +s=3 +return A.f(A.ln(o.a(p.fetch(n,null)),o),$async$il) +case 3:q=m.ik(c) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$il,r)}, +ik(a){return A.pu(a)}, +pu(a){var s=0,r=A.l(t.ab),q,p,o +var $async$ik=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=A +o=A +s=3 +return A.f(A.ig(a),$async$ik) +case 3:q=new p.eS(new o.eT(c)) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$ik,r)}, +eS:function eS(a){this.a=a}, +eb(a){return A.oe(a)}, +oe(a){var s=0,r=A.l(t.bd),q,p,o,n,m,l +var $async$eb=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:p=t.N +o=new A.fC(a) +n=A.oc(null) +m=$.kq() +l=new A.c4(o,n,new A.c8(t.h),A.os(p),A.O(p,t.S),m,"indexeddb") +s=3 +return A.f(o.bh(),$async$eb) +case 3:s=4 +return A.f(l.aH(),$async$eb) +case 4:q=l +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$eb,r)}, +fC:function fC(a){this.a=null +this.b=a}, +fG:function fG(a){this.a=a}, +fD:function fD(a){this.a=a}, +fH:function fH(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.d=d}, +fF:function fF(a,b){this.a=a +this.b=b}, +fE:function fE(a,b){this.a=a +this.b=b}, +iG:function iG(a,b,c){this.a=a +this.b=b +this.c=c}, +iH:function iH(a,b){this.a=a +this.b=b}, +fa:function fa(a,b){this.a=a +this.b=b}, +c4:function c4(a,b,c,d,e,f,g){var _=this +_.d=a +_.f=null +_.r=b +_.w=c +_.x=d +_.y=e +_.b=f +_.a=g}, +h_:function h_(a){this.a=a}, +h0:function h0(){}, +f5:function f5(a,b,c){this.a=a +this.b=b +this.c=c}, +iT:function iT(a,b){this.a=a +this.b=b}, +Z:function Z(){}, +ck:function ck(a,b){var _=this +_.w=a +_.d=b +_.c=_.b=_.a=null}, +cj:function cj(a,b,c){var _=this +_.w=a +_.x=b +_.d=c +_.c=_.b=_.a=null}, +bI:function bI(a,b,c){var _=this +_.w=a +_.x=b +_.d=c +_.c=_.b=_.a=null}, +bQ:function bQ(a,b,c,d,e){var _=this +_.w=a +_.x=b +_.y=c +_.z=d +_.d=e +_.c=_.b=_.a=null}, +ig(a){return A.ps(a)}, +ps(c6){var s=0,r=A.l(t.h2),q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,c0,c1,c2,c3,c4,c5 +var $async$ig=A.m(function(c7,c8){if(c7===1)return A.i(c8,r) +while(true)switch(s){case 0:c4=A.pH() +c5=c4.b +c5===$&&A.aK("injectedValues") +s=3 +return A.f(A.ih(c6,c5),$async$ig) +case 3:p=c8 +c5=c4.c +c5===$&&A.aK("memory") +o=p.a +n=o.i(0,"dart_sqlite3_malloc") +n.toString +m=o.i(0,"dart_sqlite3_free") +m.toString +o.i(0,"dart_sqlite3_create_scalar_function").toString +o.i(0,"dart_sqlite3_create_aggregate_function").toString +o.i(0,"dart_sqlite3_create_window_function").toString +o.i(0,"dart_sqlite3_create_collation").toString +l=o.i(0,"dart_sqlite3_register_vfs") +l.toString +o.i(0,"sqlite3_vfs_unregister").toString +k=o.i(0,"dart_sqlite3_updates") +k.toString +o.i(0,"sqlite3_libversion").toString +o.i(0,"sqlite3_sourceid").toString +o.i(0,"sqlite3_libversion_number").toString +j=o.i(0,"sqlite3_open_v2") +j.toString +i=o.i(0,"sqlite3_close_v2") +i.toString +h=o.i(0,"sqlite3_extended_errcode") +h.toString +g=o.i(0,"sqlite3_errmsg") +g.toString +f=o.i(0,"sqlite3_errstr") +f.toString +e=o.i(0,"sqlite3_extended_result_codes") +e.toString +d=o.i(0,"sqlite3_exec") +d.toString +o.i(0,"sqlite3_free").toString +c=o.i(0,"sqlite3_prepare_v3") +c.toString +b=o.i(0,"sqlite3_bind_parameter_count") +b.toString +a=o.i(0,"sqlite3_column_count") +a.toString +a0=o.i(0,"sqlite3_column_name") +a0.toString +a1=o.i(0,"sqlite3_reset") +a1.toString +a2=o.i(0,"sqlite3_step") +a2.toString +a3=o.i(0,"sqlite3_finalize") +a3.toString +a4=o.i(0,"sqlite3_column_type") +a4.toString +a5=o.i(0,"sqlite3_column_int64") +a5.toString +a6=o.i(0,"sqlite3_column_double") +a6.toString +a7=o.i(0,"sqlite3_column_bytes") +a7.toString +a8=o.i(0,"sqlite3_column_blob") +a8.toString +a9=o.i(0,"sqlite3_column_text") +a9.toString +b0=o.i(0,"sqlite3_bind_null") +b0.toString +b1=o.i(0,"sqlite3_bind_int64") +b1.toString +b2=o.i(0,"sqlite3_bind_double") +b2.toString +b3=o.i(0,"sqlite3_bind_text") +b3.toString +b4=o.i(0,"sqlite3_bind_blob64") +b4.toString +b5=o.i(0,"sqlite3_bind_parameter_index") +b5.toString +b6=o.i(0,"sqlite3_changes") +b6.toString +b7=o.i(0,"sqlite3_last_insert_rowid") +b7.toString +b8=o.i(0,"sqlite3_user_data") +b8.toString +o.i(0,"sqlite3_result_null").toString +o.i(0,"sqlite3_result_int64").toString +o.i(0,"sqlite3_result_double").toString +o.i(0,"sqlite3_result_text").toString +o.i(0,"sqlite3_result_blob64").toString +o.i(0,"sqlite3_result_error").toString +o.i(0,"sqlite3_value_type").toString +o.i(0,"sqlite3_value_int64").toString +o.i(0,"sqlite3_value_double").toString +o.i(0,"sqlite3_value_bytes").toString +o.i(0,"sqlite3_value_text").toString +o.i(0,"sqlite3_value_blob").toString +o.i(0,"sqlite3_aggregate_context").toString +b9=o.i(0,"sqlite3_get_autocommit") +b9.toString +o.i(0,"sqlite3_stmt_isexplain").toString +o.i(0,"sqlite3_stmt_readonly").toString +c0=o.i(0,"dart_sqlite3_db_config_int") +c1=o.i(0,"sqlite3_initialize") +c2=o.i(0,"sqlite3_error_offset") +c3=o.i(0,"dart_sqlite3_commits") +o=o.i(0,"dart_sqlite3_rollbacks") +p.b.i(0,"sqlite3_temp_directory").toString +q=c4.a=new A.eP(c5,c4.d,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1,a2,a4,a5,a6,a7,a9,a8,b0,b1,b2,b3,b4,b5,a3,b6,b7,b8,b9,c0,c1,c3,o,c2) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$ig,r)}, +ai(a){var s,r,q +try{a.$0() +return 0}catch(r){q=A.N(r) +if(q instanceof A.d8){s=q +return s.a}else return 1}}, +kX(a,b){var s=A.aR(t.o.a(a.buffer),b,null),r=s.length,q=0 +while(!0){if(!(q")) +s.ee() +return s}, +qS(a,b){var s=$.w +if(s===B.e)return a +return s.cK(a,b)}, +ku:function ku(a,b){this.a=a +this.$ti=b}, +iD:function iD(a,b,c,d){var _=this +_.a=a +_.b=b +_.c=c +_.$ti=d}, +df:function df(a,b,c,d,e){var _=this +_.a=0 +_.b=a +_.c=b +_.d=c +_.e=d +_.$ti=e}, +iE:function iE(a){this.a=a}, +nl(a){if(typeof dartPrint=="function"){dartPrint(a) +return}if(typeof console=="object"&&typeof console.log!="undefined"){console.log(a) +return}if(typeof print=="function"){print(a) +return}throw"Unable to print message: "+String(a)}, +ou(a,b){return a}, +kx(a,b){var s,r,q,p,o,n +if(b.length===0)return!1 +s=b.split(".") +r=v.G +for(q=s.length,p=t.A,o=0;o=65&&a<=90))s=a>=97&&a<=122 +else s=!0 +return s}, +r1(a,b){var s,r,q=null,p=a.length,o=b+2 +if(p=0&&b=0&&s").t(b).h("ae<1,2>"))}, +n(a,b){A.a0(a).c.a(b) +a.$flags&1&&A.y(a,29) +a.push(b)}, +fh(a,b){var s +a.$flags&1&&A.y(a,"removeAt",1) +s=a.length +if(b>=s)throw A.c(A.m2(b,null)) +return a.splice(b,1)[0]}, +eS(a,b,c){var s,r +A.a0(a).h("e<1>").a(c) +a.$flags&1&&A.y(a,"insertAll",2) +A.oG(b,0,a.length,"index") +if(!t.O.b(c))c=J.nV(c) +s=J.P(c) +a.length=a.length+s +r=b+s +this.D(a,r,a.length,a,b) +this.R(a,b,r,c)}, +I(a,b){var s +a.$flags&1&&A.y(a,"remove",1) +for(s=0;s").a(b) +a.$flags&1&&A.y(a,"addAll",2) +if(Array.isArray(b)){this.dB(a,b) +return}for(s=J.W(b);s.m();)a.push(s.gp())}, +dB(a,b){var s,r +t.b.a(b) +s=b.length +if(s===0)return +if(a===b)throw A.c(A.a9(a)) +for(r=0;r").t(c).h("a5<1,2>"))}, +af(a,b){var s,r=A.cS(a.length,"",!1,t.N) +for(s=0;s=0&&b0)return a[0] +throw A.c(A.aE())}, +ga2(a){var s=a.length +if(s>0)return a[s-1] +throw A.c(A.aE())}, +D(a,b,c,d,e){var s,r,q,p,o +A.a0(a).h("e<1>").a(d) +a.$flags&2&&A.y(a,5) +A.bw(b,c,a.length) +s=c-b +if(s===0)return +A.aa(e,"skipCount") +if(t.j.b(d)){r=d +q=e}else{r=J.dM(d,e).aw(0,!1) +q=0}p=J.ap(r) +if(q+s>p.gk(r))throw A.c(A.lM()) +if(q=0;--o)a[b+o]=p.i(r,q+o) +else for(o=0;o0){a[0]=q +a[1]=r}return}p=0 +if(n.c.b(null))for(o=0;o0)this.e8(a,p)}, +dh(a){return this.di(a,null)}, +e8(a,b){var s,r=a.length +for(;s=r-1,r>0;r=s)if(a[s]===null){a[s]=void 0;--b +if(b===0)break}}, +f2(a,b){var s,r=a.length,q=r-1 +if(q<0)return-1 +q=0;--s){if(!(s"))}, +gv(a){return A.et(a)}, +gk(a){return a.length}, +i(a,b){if(!(b>=0&&b=0&&b=p){r.d=null +return!1}r.d=q[s] +r.c=s+1 +return!0}, +$iA:1} +J.c6.prototype={ +T(a,b){var s +A.mV(b) +if(ab)return 1 +else if(a===b){if(a===0){s=this.gc3(b) +if(this.gc3(a)===s)return 0 +if(this.gc3(a))return-1 +return 1}return 0}else if(isNaN(a)){if(isNaN(b))return 0 +return 1}else return-1}, +gc3(a){return a===0?1/a<0:a<0}, +el(a){var s,r +if(a>=0){if(a<=2147483647){s=a|0 +return a===s?s:s+1}}else if(a>=-2147483648)return a|0 +r=Math.ceil(a) +if(isFinite(r))return r +throw A.c(A.U(""+a+".ceil()"))}, +j(a){if(a===0&&1/a<0)return"-0.0" +else return""+a}, +gv(a){var s,r,q,p,o=a|0 +if(a===o)return o&536870911 +s=Math.abs(a) +r=Math.log(s)/0.6931471805599453|0 +q=Math.pow(2,r) +p=s<1?s/q:q/s +return((p*9007199254740992|0)+(p*3542243181176521|0))*599197+r*1259&536870911}, +Y(a,b){var s=a%b +if(s===0)return 0 +if(s>0)return s +return s+b}, +ds(a,b){if((a|0)===a)if(b>=1||b<-1)return a/b|0 +return this.cC(a,b)}, +E(a,b){return(a|0)===a?a/b|0:this.cC(a,b)}, +cC(a,b){var s=a/b +if(s>=-2147483648&&s<=2147483647)return s|0 +if(s>0){if(s!==1/0)return Math.floor(s)}else if(s>-1/0)return Math.ceil(s) +throw A.c(A.U("Result of truncating division is "+A.o(s)+": "+A.o(a)+" ~/ "+b))}, +aB(a,b){if(b<0)throw A.c(A.k1(b)) +return b>31?0:a<>>0}, +aC(a,b){var s +if(b<0)throw A.c(A.k1(b)) +if(a>0)s=this.bR(a,b) +else{s=b>31?31:b +s=a>>s>>>0}return s}, +F(a,b){var s +if(a>0)s=this.bR(a,b) +else{s=b>31?31:b +s=a>>s>>>0}return s}, +ec(a,b){if(0>b)throw A.c(A.k1(b)) +return this.bR(a,b)}, +bR(a,b){return b>31?0:a>>>b}, +gB(a){return A.aI(t.r)}, +$ia8:1, +$iB:1, +$iak:1} +J.cH.prototype={ +gcL(a){var s,r=a<0?-a-1:a,q=r +for(s=32;q>=4294967296;){q=this.E(q,4294967296) +s+=32}return s-Math.clz32(q)}, +gB(a){return A.aI(t.S)}, +$iG:1, +$ia:1} +J.ef.prototype={ +gB(a){return A.aI(t.i)}, +$iG:1} +J.b7.prototype={ +cH(a,b){return new A.fm(b,a,0)}, +cO(a,b){var s=b.length,r=a.length +if(s>r)return!1 +return b===this.Z(a,r-s)}, +au(a,b,c,d){var s=A.bw(b,c,a.length) +return a.substring(0,b)+d+a.substring(s)}, +K(a,b,c){var s +if(c<0||c>a.length)throw A.c(A.T(c,0,a.length,null,null)) +s=c+b.length +if(s>a.length)return!1 +return b===a.substring(c,s)}, +J(a,b){return this.K(a,b,0)}, +q(a,b,c){return a.substring(b,A.bw(b,c,a.length))}, +Z(a,b){return this.q(a,b,null)}, +fo(a){var s,r,q,p=a.trim(),o=p.length +if(o===0)return p +if(0>=o)return A.b(p,0) +if(p.charCodeAt(0)===133){s=J.oo(p,1) +if(s===o)return""}else s=0 +r=o-1 +if(!(r>=0))return A.b(p,r) +q=p.charCodeAt(r)===133?J.op(p,r):o +if(s===0&&q===o)return p +return p.substring(s,q)}, +aT(a,b){var s,r +if(0>=b)return"" +if(b===1||a.length===0)return a +if(b!==b>>>0)throw A.c(B.D) +for(s=a,r="";!0;){if((b&1)===1)r=s+r +b=b>>>1 +if(b===0)break +s+=s}return r}, +f9(a,b,c){var s=b-a.length +if(s<=0)return a +return this.aT(c,s)+a}, +ae(a,b,c){var s +if(c<0||c>a.length)throw A.c(A.T(c,0,a.length,null,null)) +s=a.indexOf(b,c) +return s}, +c_(a,b){return this.ae(a,b,0)}, +G(a,b){return A.rm(a,b,0)}, +T(a,b){var s +A.L(b) +if(a===b)s=0 +else s=a>6}r=r+((r&67108863)<<3)&536870911 +r^=r>>11 +return r+((r&16383)<<15)&536870911}, +gB(a){return A.aI(t.N)}, +gk(a){return a.length}, +$iG:1, +$ia8:1, +$ihb:1, +$ih:1} +A.bd.prototype={ +gu(a){return new A.cy(J.W(this.ga5()),A.u(this).h("cy<1,2>"))}, +gk(a){return J.P(this.ga5())}, +O(a,b){var s=A.u(this) +return A.dV(J.dM(this.ga5(),b),s.c,s.y[1])}, +C(a,b){return A.u(this).y[1].a(J.dL(this.ga5(),b))}, +gH(a){return A.u(this).y[1].a(J.b4(this.ga5()))}, +G(a,b){return J.lv(this.ga5(),b)}, +j(a){return J.aC(this.ga5())}} +A.cy.prototype={ +m(){return this.a.m()}, +gp(){return this.$ti.y[1].a(this.a.gp())}, +$iA:1} +A.bj.prototype={ +ga5(){return this.a}} +A.de.prototype={$in:1} +A.dd.prototype={ +i(a,b){return this.$ti.y[1].a(J.b3(this.a,b))}, +l(a,b,c){var s=this.$ti +J.fB(this.a,b,s.c.a(s.y[1].a(c)))}, +D(a,b,c,d,e){var s=this.$ti +J.nT(this.a,b,c,A.dV(s.h("e<2>").a(d),s.y[1],s.c),e)}, +R(a,b,c,d){return this.D(0,b,c,d,0)}, +$in:1, +$it:1} +A.ae.prototype={ +b5(a,b){return new A.ae(this.a,this.$ti.h("@<1>").t(b).h("ae<1,2>"))}, +ga5(){return this.a}} +A.cz.prototype={ +L(a){return this.a.L(a)}, +i(a,b){return this.$ti.h("4?").a(this.a.i(0,b))}, +M(a,b){this.a.M(0,new A.fL(this,this.$ti.h("~(3,4)").a(b)))}, +gN(){var s=this.$ti +return A.dV(this.a.gN(),s.c,s.y[2])}, +ga8(){var s=this.$ti +return A.dV(this.a.ga8(),s.y[1],s.y[3])}, +gk(a){var s=this.a +return s.gk(s)}, +gao(){return this.a.gao().a6(0,new A.fK(this),this.$ti.h("K<3,4>"))}} +A.fL.prototype={ +$2(a,b){var s=this.a.$ti +s.c.a(a) +s.y[1].a(b) +this.b.$2(s.y[2].a(a),s.y[3].a(b))}, +$S(){return this.a.$ti.h("~(1,2)")}} +A.fK.prototype={ +$1(a){var s=this.a.$ti +s.h("K<1,2>").a(a) +return new A.K(s.y[2].a(a.a),s.y[3].a(a.b),s.h("K<3,4>"))}, +$S(){return this.a.$ti.h("K<3,4>(K<1,2>)")}} +A.cL.prototype={ +j(a){return"LateInitializationError: "+this.a}} +A.cA.prototype={ +gk(a){return this.a.length}, +i(a,b){var s=this.a +if(!(b>=0&&b"))}, +gH(a){if(this.gk(this)===0)throw A.c(A.aE()) +return this.C(0,0)}, +G(a,b){var s,r=this,q=r.gk(r) +for(s=0;s").t(c).h("a5<1,2>"))}, +O(a,b){return A.eF(this,b,null,A.u(this).h("Y.E"))}} +A.bA.prototype={ +dt(a,b,c,d){var s,r=this.b +A.aa(r,"start") +s=this.c +if(s!=null){A.aa(s,"end") +if(r>s)throw A.c(A.T(r,0,s,"start",null))}}, +gdN(){var s=J.P(this.a),r=this.c +if(r==null||r>s)return s +return r}, +ged(){var s=J.P(this.a),r=this.b +if(r>s)return s +return r}, +gk(a){var s,r=J.P(this.a),q=this.b +if(q>=r)return 0 +s=this.c +if(s==null||s>=r)return r-q +return s-q}, +C(a,b){var s=this,r=s.ged()+b +if(b<0||r>=s.gdN())throw A.c(A.ea(b,s.gk(0),s,null,"index")) +return J.dL(s.a,r)}, +O(a,b){var s,r,q=this +A.aa(b,"count") +s=q.b+b +r=q.c +if(r!=null&&s>=r)return new A.bm(q.$ti.h("bm<1>")) +return A.eF(q.a,s,r,q.$ti.c)}, +aw(a,b){var s,r,q,p=this,o=p.b,n=p.a,m=J.ap(n),l=m.gk(n),k=p.c +if(k!=null&&k=o){r.d=null +return!1}r.d=p.C(q,s);++r.c +return!0}, +$iA:1} +A.aQ.prototype={ +gu(a){return new A.cT(J.W(this.a),this.b,A.u(this).h("cT<1,2>"))}, +gk(a){return J.P(this.a)}, +gH(a){return this.b.$1(J.b4(this.a))}, +C(a,b){return this.b.$1(J.dL(this.a,b))}} +A.bl.prototype={$in:1} +A.cT.prototype={ +m(){var s=this,r=s.b +if(r.m()){s.a=s.c.$1(r.gp()) +return!0}s.a=null +return!1}, +gp(){var s=this.a +return s==null?this.$ti.y[1].a(s):s}, +$iA:1} +A.a5.prototype={ +gk(a){return J.P(this.a)}, +C(a,b){return this.b.$1(J.dL(this.a,b))}} +A.io.prototype={ +gu(a){return new A.bF(J.W(this.a),this.b,this.$ti.h("bF<1>"))}, +a6(a,b,c){var s=this.$ti +return new A.aQ(this,s.t(c).h("1(2)").a(b),s.h("@<1>").t(c).h("aQ<1,2>"))}} +A.bF.prototype={ +m(){var s,r +for(s=this.a,r=this.b;s.m();)if(r.$1(s.gp()))return!0 +return!1}, +gp(){return this.a.gp()}, +$iA:1} +A.aT.prototype={ +O(a,b){A.cw(b,"count",t.S) +A.aa(b,"count") +return new A.aT(this.a,this.b+b,A.u(this).h("aT<1>"))}, +gu(a){return new A.d1(J.W(this.a),this.b,A.u(this).h("d1<1>"))}} +A.c1.prototype={ +gk(a){var s=J.P(this.a)-this.b +if(s>=0)return s +return 0}, +O(a,b){A.cw(b,"count",t.S) +A.aa(b,"count") +return new A.c1(this.a,this.b+b,this.$ti)}, +$in:1} +A.d1.prototype={ +m(){var s,r +for(s=this.a,r=0;r"))}, +O(a,b){A.aa(b,"count") +return this}} +A.cD.prototype={ +m(){return!1}, +gp(){throw A.c(A.aE())}, +$iA:1} +A.d9.prototype={ +gu(a){return new A.da(J.W(this.a),this.$ti.h("da<1>"))}} +A.da.prototype={ +m(){var s,r +for(s=this.a,r=this.$ti.c;s.m();)if(r.b(s.gp()))return!0 +return!1}, +gp(){return this.$ti.c.a(this.a.gp())}, +$iA:1} +A.bo.prototype={ +gk(a){return J.P(this.a)}, +gH(a){return new A.bf(this.b,J.b4(this.a))}, +C(a,b){return new A.bf(b+this.b,J.dL(this.a,b))}, +G(a,b){return!1}, +O(a,b){A.cw(b,"count",t.S) +A.aa(b,"count") +return new A.bo(J.dM(this.a,b),b+this.b,A.u(this).h("bo<1>"))}, +gu(a){return new A.bp(J.W(this.a),this.b,A.u(this).h("bp<1>"))}} +A.c0.prototype={ +G(a,b){return!1}, +O(a,b){A.cw(b,"count",t.S) +A.aa(b,"count") +return new A.c0(J.dM(this.a,b),this.b+b,this.$ti)}, +$in:1} +A.bp.prototype={ +m(){if(++this.c>=0&&this.a.m())return!0 +this.c=-2 +return!1}, +gp(){var s=this.c +return s>=0?new A.bf(this.b+s,this.a.gp()):A.H(A.aE())}, +$iA:1} +A.af.prototype={} +A.bc.prototype={ +l(a,b,c){A.u(this).h("bc.E").a(c) +throw A.c(A.U("Cannot modify an unmodifiable list"))}, +D(a,b,c,d,e){A.u(this).h("e").a(d) +throw A.c(A.U("Cannot modify an unmodifiable list"))}, +R(a,b,c,d){return this.D(0,b,c,d,0)}} +A.cf.prototype={} +A.f9.prototype={ +gk(a){return J.P(this.a)}, +C(a,b){A.od(b,J.P(this.a),this,null,null) +return b}} +A.cR.prototype={ +i(a,b){return this.L(b)?J.b3(this.a,A.d(b)):null}, +gk(a){return J.P(this.a)}, +ga8(){return A.eF(this.a,0,null,this.$ti.c)}, +gN(){return new A.f9(this.a)}, +L(a){return A.ft(a)&&a>=0&&a>"))}, +ew(){var s=this +return function(){var r=0,q=1,p=[],o,n,m,l,k +return function $async$gao(a,b,c){if(b===1){p.push(c) +r=q}while(true)switch(r){case 0:o=s.gN(),o=o.gu(o),n=A.u(s),m=n.y[1],n=n.h("K<1,2>") +case 2:if(!o.m()){r=3 +break}l=o.gp() +k=s.i(0,l) +r=4 +return a.b=new A.K(l,k==null?m.a(k):k,n),1 +case 4:r=2 +break +case 3:return 0 +case 1:return a.c=p.at(-1),3}}}}, +$iI:1} +A.cC.prototype={ +gk(a){return this.b.length}, +gcq(){var s=this.$keys +if(s==null){s=Object.keys(this.a) +this.$keys=s}return s}, +L(a){if(typeof a!="string")return!1 +if("__proto__"===a)return!1 +return this.a.hasOwnProperty(a)}, +i(a,b){if(!this.L(b))return null +return this.b[this.a[b]]}, +M(a,b){var s,r,q,p +this.$ti.h("~(1,2)").a(b) +s=this.gcq() +r=this.b +for(q=s.length,p=0;p"))}, +ga8(){return new A.bM(this.b,this.$ti.h("bM<2>"))}} +A.bM.prototype={ +gk(a){return this.a.length}, +gu(a){var s=this.a +return new A.dg(s,s.length,this.$ti.h("dg<1>"))}} +A.dg.prototype={ +gp(){var s=this.d +return s==null?this.$ti.c.a(s):s}, +m(){var s=this,r=s.c +if(r>=s.b){s.d=null +return!1}s.d=s.a[r] +s.c=r+1 +return!0}, +$iA:1} +A.i8.prototype={ +a_(a){var s,r,q=this,p=new RegExp(q.a).exec(a) +if(p==null)return null +s=Object.create(null) +r=q.b +if(r!==-1)s.arguments=p[r+1] +r=q.c +if(r!==-1)s.argumentsExpr=p[r+1] +r=q.d +if(r!==-1)s.expr=p[r+1] +r=q.e +if(r!==-1)s.method=p[r+1] +r=q.f +if(r!==-1)s.receiver=p[r+1] +return s}} +A.cX.prototype={ +j(a){return"Null check operator used on a null value"}} +A.eg.prototype={ +j(a){var s,r=this,q="NoSuchMethodError: method not found: '",p=r.b +if(p==null)return"NoSuchMethodError: "+r.a +s=r.c +if(s==null)return q+p+"' ("+r.a+")" +return q+p+"' on '"+s+"' ("+r.a+")"}} +A.eI.prototype={ +j(a){var s=this.a +return s.length===0?"Error":"Error: "+s}} +A.h9.prototype={ +j(a){return"Throw of null ('"+(this.a===null?"null":"undefined")+"' from JavaScript)"}} +A.cE.prototype={} +A.ds.prototype={ +j(a){var s,r=this.b +if(r!=null)return r +r=this.a +s=r!==null&&typeof r==="object"?r.stack:null +return this.b=s==null?"":s}, +$iaF:1} +A.b5.prototype={ +j(a){var s=this.constructor,r=s==null?null:s.name +return"Closure '"+A.nq(r==null?"unknown":r)+"'"}, +gB(a){var s=A.lg(this) +return A.aI(s==null?A.aq(this):s)}, +$ibn:1, +gft(){return this}, +$C:"$1", +$R:1, +$D:null} +A.dW.prototype={$C:"$0",$R:0} +A.dX.prototype={$C:"$2",$R:2} +A.eG.prototype={} +A.eD.prototype={ +j(a){var s=this.$static_name +if(s==null)return"Closure of unknown static method" +return"Closure '"+A.nq(s)+"'"}} +A.bY.prototype={ +X(a,b){if(b==null)return!1 +if(this===b)return!0 +if(!(b instanceof A.bY))return!1 +return this.$_target===b.$_target&&this.a===b.a}, +gv(a){return(A.lm(this.a)^A.et(this.$_target))>>>0}, +j(a){return"Closure '"+this.$_name+"' of "+("Instance of '"+A.hc(this.a)+"'")}} +A.ex.prototype={ +j(a){return"RuntimeError: "+this.a}} +A.aP.prototype={ +gk(a){return this.a}, +gf_(a){return this.a!==0}, +gN(){return new A.br(this,A.u(this).h("br<1>"))}, +ga8(){return new A.cQ(this,A.u(this).h("cQ<2>"))}, +gao(){return new A.cM(this,A.u(this).h("cM<1,2>"))}, +L(a){var s,r +if(typeof a=="string"){s=this.b +if(s==null)return!1 +return s[a]!=null}else if(typeof a=="number"&&(a&0x3fffffff)===a){r=this.c +if(r==null)return!1 +return r[a]!=null}else return this.eW(a)}, +eW(a){var s=this.d +if(s==null)return!1 +return this.bf(s[this.be(a)],a)>=0}, +bU(a,b){A.u(this).h("I<1,2>").a(b).M(0,new A.h2(this))}, +i(a,b){var s,r,q,p,o=null +if(typeof b=="string"){s=this.b +if(s==null)return o +r=s[b] +q=r==null?o:r.b +return q}else if(typeof b=="number"&&(b&0x3fffffff)===b){p=this.c +if(p==null)return o +r=p[b] +q=r==null?o:r.b +return q}else return this.eX(b)}, +eX(a){var s,r,q=this.d +if(q==null)return null +s=q[this.be(a)] +r=this.bf(s,a) +if(r<0)return null +return s[r].b}, +l(a,b,c){var s,r,q=this,p=A.u(q) +p.c.a(b) +p.y[1].a(c) +if(typeof b=="string"){s=q.b +q.ce(s==null?q.b=q.bN():s,b,c)}else if(typeof b=="number"&&(b&0x3fffffff)===b){r=q.c +q.ce(r==null?q.c=q.bN():r,b,c)}else q.eZ(b,c)}, +eZ(a,b){var s,r,q,p,o=this,n=A.u(o) +n.c.a(a) +n.y[1].a(b) +s=o.d +if(s==null)s=o.d=o.bN() +r=o.be(a) +q=s[r] +if(q==null)s[r]=[o.bO(a,b)] +else{p=o.bf(q,a) +if(p>=0)q[p].b=b +else q.push(o.bO(a,b))}}, +fb(a,b){var s,r,q=this,p=A.u(q) +p.c.a(a) +p.h("2()").a(b) +if(q.L(a)){s=q.i(0,a) +return s==null?p.y[1].a(s):s}r=b.$0() +q.l(0,a,r) +return r}, +I(a,b){var s=this +if(typeof b=="string")return s.cv(s.b,b) +else if(typeof b=="number"&&(b&0x3fffffff)===b)return s.cv(s.c,b) +else return s.eY(b)}, +eY(a){var s,r,q,p,o=this,n=o.d +if(n==null)return null +s=o.be(a) +r=n[s] +q=o.bf(r,a) +if(q<0)return null +p=r.splice(q,1)[0] +o.cG(p) +if(r.length===0)delete n[s] +return p.b}, +M(a,b){var s,r,q=this +A.u(q).h("~(1,2)").a(b) +s=q.e +r=q.r +for(;s!=null;){b.$2(s.a,s.b) +if(r!==q.r)throw A.c(A.a9(q)) +s=s.c}}, +ce(a,b,c){var s,r=A.u(this) +r.c.a(b) +r.y[1].a(c) +s=a[b] +if(s==null)a[b]=this.bO(b,c) +else s.b=c}, +cv(a,b){var s +if(a==null)return null +s=a[b] +if(s==null)return null +this.cG(s) +delete a[b] +return s.b}, +cs(){this.r=this.r+1&1073741823}, +bO(a,b){var s=this,r=A.u(s),q=new A.h3(r.c.a(a),r.y[1].a(b)) +if(s.e==null)s.e=s.f=q +else{r=s.f +r.toString +q.d=r +s.f=r.c=q}++s.a +s.cs() +return q}, +cG(a){var s=this,r=a.d,q=a.c +if(r==null)s.e=q +else r.c=q +if(q==null)s.f=r +else q.d=r;--s.a +s.cs()}, +be(a){return J.aL(a)&1073741823}, +bf(a,b){var s,r +if(a==null)return-1 +s=a.length +for(r=0;r"]=s +delete s[""] +return s}, +$ilS:1} +A.h2.prototype={ +$2(a,b){var s=this.a,r=A.u(s) +s.l(0,r.c.a(a),r.y[1].a(b))}, +$S(){return A.u(this.a).h("~(1,2)")}} +A.h3.prototype={} +A.br.prototype={ +gk(a){return this.a.a}, +gu(a){var s=this.a +return new A.cO(s,s.r,s.e,this.$ti.h("cO<1>"))}, +G(a,b){return this.a.L(b)}} +A.cO.prototype={ +gp(){return this.d}, +m(){var s,r=this,q=r.a +if(r.b!==q.r)throw A.c(A.a9(q)) +s=r.c +if(s==null){r.d=null +return!1}else{r.d=s.a +r.c=s.c +return!0}}, +$iA:1} +A.cQ.prototype={ +gk(a){return this.a.a}, +gu(a){var s=this.a +return new A.cP(s,s.r,s.e,this.$ti.h("cP<1>"))}} +A.cP.prototype={ +gp(){return this.d}, +m(){var s,r=this,q=r.a +if(r.b!==q.r)throw A.c(A.a9(q)) +s=r.c +if(s==null){r.d=null +return!1}else{r.d=s.b +r.c=s.c +return!0}}, +$iA:1} +A.cM.prototype={ +gk(a){return this.a.a}, +gu(a){var s=this.a +return new A.cN(s,s.r,s.e,this.$ti.h("cN<1,2>"))}} +A.cN.prototype={ +gp(){var s=this.d +s.toString +return s}, +m(){var s,r=this,q=r.a +if(r.b!==q.r)throw A.c(A.a9(q)) +s=r.c +if(s==null){r.d=null +return!1}else{r.d=new A.K(s.a,s.b,r.$ti.h("K<1,2>")) +r.c=s.c +return!0}}, +$iA:1} +A.k9.prototype={ +$1(a){return this.a(a)}, +$S:56} +A.ka.prototype={ +$2(a,b){return this.a(a,b)}, +$S:32} +A.kb.prototype={ +$1(a){return this.a(A.L(a))}, +$S:24} +A.be.prototype={ +gB(a){return A.aI(this.co())}, +co(){return A.r3(this.$r,this.cm())}, +j(a){return this.cF(!1)}, +cF(a){var s,r,q,p,o,n=this.dR(),m=this.cm(),l=(a?""+"Record ":"")+"(" +for(s=n.length,r="",q=0;q0;){--q;--s +B.b.l(j,q,r[s])}}return A.eh(j,k)}} +A.bP.prototype={ +cm(){return[this.a,this.b]}, +X(a,b){if(b==null)return!1 +return b instanceof A.bP&&this.$s===b.$s&&J.V(this.a,b.a)&&J.V(this.b,b.b)}, +gv(a){return A.lT(this.$s,this.a,this.b,B.h)}} +A.cJ.prototype={ +j(a){return"RegExp/"+this.a+"/"+this.b.flags}, +ge1(){var s=this,r=s.c +if(r!=null)return r +r=s.b +return s.c=A.lQ(s.a,r.multiline,!r.ignoreCase,r.unicode,r.dotAll,"g")}, +eF(a){var s=this.b.exec(a) +if(s==null)return null +return new A.dl(s)}, +cH(a,b){return new A.eX(this,b,0)}, +dP(a,b){var s,r=this.ge1() +if(r==null)r=t.K.a(r) +r.lastIndex=b +s=r.exec(a) +if(s==null)return null +return new A.dl(s)}, +$ihb:1, +$ioI:1} +A.dl.prototype={$ic9:1,$id_:1} +A.eX.prototype={ +gu(a){return new A.eY(this.a,this.b,this.c)}} +A.eY.prototype={ +gp(){var s=this.d +return s==null?t.cz.a(s):s}, +m(){var s,r,q,p,o,n,m=this,l=m.b +if(l==null)return!1 +s=m.c +r=l.length +if(s<=r){q=m.a +p=q.dP(l,s) +if(p!=null){m.d=p +s=p.b +o=s.index +n=o+s[0].length +if(o===n){s=!1 +if(q.b.unicode){q=m.c +o=q+1 +if(o=0&&q=55296&&q<=56319){if(!(o>=0))return A.b(l,o) +s=l.charCodeAt(o) +s=s>=56320&&s<=57343}}}n=(s?n+1:n)+1}m.c=n +return!0}}m.b=m.d=null +return!1}, +$iA:1} +A.d6.prototype={$ic9:1} +A.fm.prototype={ +gu(a){return new A.fn(this.a,this.b,this.c)}, +gH(a){var s=this.b,r=this.a.indexOf(s,this.c) +if(r>=0)return new A.d6(r,s) +throw A.c(A.aE())}} +A.fn.prototype={ +m(){var s,r,q=this,p=q.c,o=q.b,n=o.length,m=q.a,l=m.length +if(p+n>l){q.d=null +return!1}s=m.indexOf(o,p) +if(s<0){q.c=l+1 +q.d=null +return!1}r=s+n +q.d=new A.d6(s,o) +q.c=r===q.c?r+1:r +return!0}, +gp(){var s=this.d +s.toString +return s}, +$iA:1} +A.iy.prototype={ +S(){var s=this.b +if(s===this)throw A.c(A.lR(this.a)) +return s}} +A.ca.prototype={ +gB(a){return B.M}, +cI(a,b,c){A.fr(a,b,c) +return c==null?new Uint8Array(a,b):new Uint8Array(a,b,c)}, +$iG:1, +$ica:1, +$idU:1} +A.cV.prototype={ +gam(a){if(((a.$flags|0)&2)!==0)return new A.fp(a.buffer) +else return a.buffer}, +e0(a,b,c,d){var s=A.T(b,0,c,d,null) +throw A.c(s)}, +cg(a,b,c,d){if(b>>>0!==b||b>c)this.e0(a,b,c,d)}} +A.fp.prototype={ +cI(a,b,c){var s=A.aR(this.a,b,c) +s.$flags=3 +return s}, +$idU:1} +A.cU.prototype={ +gB(a){return B.N}, +$iG:1, +$ilE:1} +A.a6.prototype={ +gk(a){return a.length}, +cz(a,b,c,d,e){var s,r,q=a.length +this.cg(a,b,q,"start") +this.cg(a,c,q,"end") +if(b>c)throw A.c(A.T(b,0,c,null,null)) +s=c-b +if(e<0)throw A.c(A.a2(e,null)) +r=d.length +if(r-e").b(a))s.cf(a) +else s.aY(a)}}, +bW(a,b){var s=this.a +if(this.b)s.P(new A.X(a,b)) +else s.aE(new A.X(a,b))}, +$idZ:1} +A.jR.prototype={ +$1(a){return this.a.$2(0,a)}, +$S:7} +A.jS.prototype={ +$2(a,b){this.a.$2(1,new A.cE(a,t.l.a(b)))}, +$S:29} +A.k0.prototype={ +$2(a,b){this.a(A.d(a),b)}, +$S:36} +A.dt.prototype={ +gp(){var s=this.b +return s==null?this.$ti.c.a(s):s}, +e9(a,b){var s,r,q +a=A.d(a) +b=b +s=this.a +for(;!0;)try{r=s(this,a,b) +return r}catch(q){b=q +a=1}}, +m(){var s,r,q,p,o=this,n=null,m=0 +for(;!0;){s=o.d +if(s!=null)try{if(s.m()){o.b=s.gp() +return!0}else o.d=null}catch(r){n=r +m=1 +o.d=null}q=o.e9(m,n) +if(1===q)return!0 +if(0===q){o.b=null +p=o.e +if(p==null||p.length===0){o.a=A.mw +return!1}if(0>=p.length)return A.b(p,-1) +o.a=p.pop() +m=0 +n=null +continue}if(2===q){m=0 +n=null +continue}if(3===q){n=o.c +o.c=null +p=o.e +if(p==null||p.length===0){o.b=null +o.a=A.mw +throw n +return!1}if(0>=p.length)return A.b(p,-1) +o.a=p.pop() +m=1 +continue}throw A.c(A.Q("sync*"))}return!1}, +fv(a){var s,r,q=this +if(a instanceof A.cm){s=a.a() +r=q.e +if(r==null)r=q.e=[] +B.b.n(r,q.a) +q.a=s +return 2}else{q.d=J.W(a) +return 2}}, +$iA:1} +A.cm.prototype={ +gu(a){return new A.dt(this.a(),this.$ti.h("dt<1>"))}} +A.X.prototype={ +j(a){return A.o(this.a)}, +$iJ:1, +gaj(){return this.b}} +A.fX.prototype={ +$0(){var s,r,q,p,o,n,m=null +try{m=this.a.$0()}catch(q){s=A.N(q) +r=A.aj(q) +p=s +o=r +n=A.jY(p,o) +if(n==null)p=new A.X(p,o) +else p=n +this.b.P(p) +return}this.b.bD(m)}, +$S:0} +A.fZ.prototype={ +$2(a,b){var s,r,q=this +t.K.a(a) +t.l.a(b) +s=q.a +r=--s.b +if(s.a!=null){s.a=null +s.d=a +s.c=b +if(r===0||q.c)q.d.P(new A.X(a,b))}else if(r===0&&!q.c){r=s.d +r.toString +s=s.c +s.toString +q.d.P(new A.X(r,s))}}, +$S:42} +A.fY.prototype={ +$1(a){var s,r,q,p,o,n,m,l,k=this,j=k.d +j.a(a) +o=k.a +s=--o.b +r=o.a +if(r!=null){J.fB(r,k.b,a) +if(J.V(s,0)){q=A.x([],j.h("E<0>")) +for(o=r,n=o.length,m=0;m")) +q=b==null?1:3 +this.aV(new A.aY(r,q,a,b,p.h("@<1>").t(c).h("aY<1,2>"))) +return r}, +fm(a,b){a.toString +return this.bm(a,null,b)}, +cE(a,b,c){var s,r=this.$ti +r.t(c).h("1/(2)").a(a) +s=new A.v($.w,c.h("v<0>")) +this.aV(new A.aY(s,19,a,b,r.h("@<1>").t(c).h("aY<1,2>"))) +return s}, +eb(a){this.a=this.a&1|16 +this.c=a}, +aX(a){this.a=a.a&30|this.a&1 +this.c=a.c}, +aV(a){var s,r=this,q=r.a +if(q<=3){a.a=t.d.a(r.c) +r.c=a}else{if((q&4)!==0){s=t._.a(r.c) +if((s.a&24)===0){s.aV(a) +return}r.aX(s)}r.b.az(new A.iI(r,a))}}, +ct(a){var s,r,q,p,o,n,m=this,l={} +l.a=a +if(a==null)return +s=m.a +if(s<=3){r=t.d.a(m.c) +m.c=a +if(r!=null){q=a.a +for(p=a;q!=null;p=q,q=o)o=q.a +p.a=r}}else{if((s&4)!==0){n=t._.a(m.c) +if((n.a&24)===0){n.ct(a) +return}m.aX(n)}l.a=m.b2(a) +m.b.az(new A.iN(l,m))}}, +aI(){var s=t.d.a(this.c) +this.c=null +return this.b2(s)}, +b2(a){var s,r,q +for(s=a,r=null;s!=null;r=s,s=q){q=s.a +s.a=r}return r}, +bD(a){var s,r=this,q=r.$ti +q.h("1/").a(a) +if(q.h("z<1>").b(a))A.iL(a,r,!0) +else{s=r.aI() +q.c.a(a) +r.a=8 +r.c=a +A.bL(r,s)}}, +aY(a){var s,r=this +r.$ti.c.a(a) +s=r.aI() +r.a=8 +r.c=a +A.bL(r,s)}, +dG(a){var s,r,q,p=this +if((a.a&16)!==0){s=p.b +r=a.b +s=!(s===r||s.gap()===r.gap())}else s=!1 +if(s)return +q=p.aI() +p.aX(a) +A.bL(p,q)}, +P(a){var s=this.aI() +this.eb(a) +A.bL(this,s)}, +bx(a){var s=this.$ti +s.h("1/").a(a) +if(s.h("z<1>").b(a)){this.cf(a) +return}this.dC(a)}, +dC(a){var s=this +s.$ti.c.a(a) +s.a^=2 +s.b.az(new A.iK(s,a))}, +cf(a){A.iL(this.$ti.h("z<1>").a(a),this,!1) +return}, +aE(a){this.a^=2 +this.b.az(new A.iJ(this,a))}, +$iz:1} +A.iI.prototype={ +$0(){A.bL(this.a,this.b)}, +$S:0} +A.iN.prototype={ +$0(){A.bL(this.b,this.a.a)}, +$S:0} +A.iM.prototype={ +$0(){A.iL(this.a.a,this.b,!0)}, +$S:0} +A.iK.prototype={ +$0(){this.a.aY(this.b)}, +$S:0} +A.iJ.prototype={ +$0(){this.a.P(this.b)}, +$S:0} +A.iQ.prototype={ +$0(){var s,r,q,p,o,n,m,l,k=this,j=null +try{q=k.a.a +j=q.b.b.aP(t.fO.a(q.d),t.z)}catch(p){s=A.N(p) +r=A.aj(p) +if(k.c&&t.n.a(k.b.a.c).a===s){q=k.a +q.c=t.n.a(k.b.a.c)}else{q=s +o=r +if(o==null)o=A.dP(q) +n=k.a +n.c=new A.X(q,o) +q=n}q.b=!0 +return}if(j instanceof A.v&&(j.a&24)!==0){if((j.a&16)!==0){q=k.a +q.c=t.n.a(j.c) +q.b=!0}return}if(j instanceof A.v){m=k.b.a +l=new A.v(m.b,m.$ti) +j.bm(new A.iR(l,m),new A.iS(l),t.H) +q=k.a +q.c=l +q.b=!1}}, +$S:0} +A.iR.prototype={ +$1(a){this.a.dG(this.b)}, +$S:16} +A.iS.prototype={ +$2(a,b){t.K.a(a) +t.l.a(b) +this.a.P(new A.X(a,b))}, +$S:66} +A.iP.prototype={ +$0(){var s,r,q,p,o,n,m,l +try{q=this.a +p=q.a +o=p.$ti +n=o.c +m=n.a(this.b) +q.c=p.b.b.c9(o.h("2/(1)").a(p.d),m,o.h("2/"),n)}catch(l){s=A.N(l) +r=A.aj(l) +q=s +p=r +if(p==null)p=A.dP(q) +o=this.a +o.c=new A.X(q,p) +o.b=!0}}, +$S:0} +A.iO.prototype={ +$0(){var s,r,q,p,o,n,m,l=this +try{s=t.n.a(l.a.a.c) +p=l.b +if(p.a.f4(s)&&p.a.e!=null){p.c=p.a.eJ(s) +p.b=!1}}catch(o){r=A.N(o) +q=A.aj(o) +p=t.n.a(l.a.a.c) +if(p.a===r){n=l.b +n.c=p +p=n}else{p=r +n=q +if(n==null)n=A.dP(p) +m=l.b +m.c=new A.X(p,n) +p=m}p.b=!0}}, +$S:0} +A.eZ.prototype={} +A.eE.prototype={ +gk(a){var s,r,q=this,p={},o=new A.v($.w,t.fJ) +p.a=0 +s=q.$ti +r=s.h("~(1)?").a(new A.i5(p,q)) +t.g5.a(new A.i6(p,o)) +A.bK(q.a,q.b,r,!1,s.c) +return o}} +A.i5.prototype={ +$1(a){this.b.$ti.c.a(a);++this.a.a}, +$S(){return this.b.$ti.h("~(1)")}} +A.i6.prototype={ +$0(){this.b.bD(this.a.a)}, +$S:0} +A.fl.prototype={} +A.dD.prototype={$iip:1} +A.jZ.prototype={ +$0(){A.o6(this.a,this.b)}, +$S:0} +A.ff.prototype={ +gap(){return this}, +fk(a){var s,r,q +t.M.a(a) +try{if(B.e===$.w){a.$0() +return}A.n6(null,null,this,a,t.H)}catch(q){s=A.N(q) +r=A.aj(q) +A.ld(t.K.a(s),t.l.a(r))}}, +fl(a,b,c){var s,r,q +c.h("~(0)").a(a) +c.a(b) +try{if(B.e===$.w){a.$1(b) +return}A.n7(null,null,this,a,b,t.H,c)}catch(q){s=A.N(q) +r=A.aj(q) +A.ld(t.K.a(s),t.l.a(r))}}, +ek(a,b){return new A.jF(this,b.h("0()").a(a),b)}, +cJ(a){return new A.jE(this,t.M.a(a))}, +cK(a,b){return new A.jG(this,b.h("~(0)").a(a),b)}, +cT(a,b){A.ld(a,t.l.a(b))}, +aP(a,b){b.h("0()").a(a) +if($.w===B.e)return a.$0() +return A.n6(null,null,this,a,b)}, +c9(a,b,c,d){c.h("@<0>").t(d).h("1(2)").a(a) +d.a(b) +if($.w===B.e)return a.$1(b) +return A.n7(null,null,this,a,b,c,d)}, +fj(a,b,c,d,e,f){d.h("@<0>").t(e).t(f).h("1(2,3)").a(a) +e.a(b) +f.a(c) +if($.w===B.e)return a.$2(b,c) +return A.qJ(null,null,this,a,b,c,d,e,f)}, +fg(a,b){return b.h("0()").a(a)}, +d2(a,b,c){return b.h("@<0>").t(c).h("1(2)").a(a)}, +d1(a,b,c,d){return b.h("@<0>").t(c).t(d).h("1(2,3)").a(a)}, +ex(a,b){return null}, +az(a){A.qK(null,null,this,t.M.a(a))}, +cM(a,b){return A.m9(a,t.M.a(b))}} +A.jF.prototype={ +$0(){return this.a.aP(this.b,this.c)}, +$S(){return this.c.h("0()")}} +A.jE.prototype={ +$0(){return this.a.fk(this.b)}, +$S:0} +A.jG.prototype={ +$1(a){var s=this.c +return this.a.fl(this.b,s.a(a),s)}, +$S(){return this.c.h("~(0)")}} +A.dh.prototype={ +gu(a){var s=this,r=new A.bN(s,s.r,s.$ti.h("bN<1>")) +r.c=s.e +return r}, +gk(a){return this.a}, +G(a,b){var s,r +if(b!=="__proto__"){s=this.b +if(s==null)return!1 +return t.V.a(s[b])!=null}else{r=this.dJ(b) +return r}}, +dJ(a){var s=this.d +if(s==null)return!1 +return this.bJ(s[B.a.gv(a)&1073741823],a)>=0}, +gH(a){var s=this.e +if(s==null)throw A.c(A.Q("No elements")) +return this.$ti.c.a(s.a)}, +n(a,b){var s,r,q=this +q.$ti.c.a(b) +if(typeof b=="string"&&b!=="__proto__"){s=q.b +return q.ci(s==null?q.b=A.l3():s,b)}else if(typeof b=="number"&&(b&1073741823)===b){r=q.c +return q.ci(r==null?q.c=A.l3():r,b)}else return q.dA(b)}, +dA(a){var s,r,q,p=this +p.$ti.c.a(a) +s=p.d +if(s==null)s=p.d=A.l3() +r=J.aL(a)&1073741823 +q=s[r] +if(q==null)s[r]=[p.bB(a)] +else{if(p.bJ(q,a)>=0)return!1 +q.push(p.bB(a))}return!0}, +I(a,b){var s +if(b!=="__proto__")return this.dF(this.b,b) +else{s=this.e7(b) +return s}}, +e7(a){var s,r,q,p,o=this.d +if(o==null)return!1 +s=B.a.gv(a)&1073741823 +r=o[s] +q=this.bJ(r,a) +if(q<0)return!1 +p=r.splice(q,1)[0] +if(0===r.length)delete o[s] +this.ck(p) +return!0}, +ci(a,b){this.$ti.c.a(b) +if(t.V.a(a[b])!=null)return!1 +a[b]=this.bB(b) +return!0}, +dF(a,b){var s +if(a==null)return!1 +s=t.V.a(a[b]) +if(s==null)return!1 +this.ck(s) +delete a[b] +return!0}, +cj(){this.r=this.r+1&1073741823}, +bB(a){var s,r=this,q=new A.f8(r.$ti.c.a(a)) +if(r.e==null)r.e=r.f=q +else{s=r.f +s.toString +q.c=s +r.f=s.b=q}++r.a +r.cj() +return q}, +ck(a){var s=this,r=a.c,q=a.b +if(r==null)s.e=q +else r.b=q +if(q==null)s.f=r +else q.c=r;--s.a +s.cj()}, +bJ(a,b){var s,r +if(a==null)return-1 +s=a.length +for(r=0;r"))}, +gk(a){return this.b}, +gH(a){var s +if(this.b===0)throw A.c(A.Q("No such element")) +s=this.c +s.toString +return s}, +ga2(a){var s +if(this.b===0)throw A.c(A.Q("No such element")) +s=this.c.c +s.toString +return s}, +gW(a){return this.b===0}, +bM(a,b,c){var s=this,r=s.$ti +r.h("1?").a(a) +r.c.a(b) +if(b.a!=null)throw A.c(A.Q("LinkedListEntry is already in a LinkedList"));++s.a +b.scr(s) +if(s.b===0){b.saF(b) +b.saG(b) +s.c=b;++s.b +return}r=a.c +r.toString +b.saG(r) +b.saF(a) +r.saF(b) +a.saG(b);++s.b}, +bS(a){var s,r,q=this +q.$ti.c.a(a);++q.a +a.b.saG(a.c) +s=a.c +r=a.b +s.saF(r);--q.b +a.saG(null) +a.saF(null) +a.scr(null) +if(q.b===0)q.c=null +else if(a===q.c)q.c=r}} +A.di.prototype={ +gp(){var s=this.c +return s==null?this.$ti.c.a(s):s}, +m(){var s=this,r=s.a +if(s.b!==r.a)throw A.c(A.a9(s)) +if(r.b!==0)r=s.e&&s.d===r.gH(0) +else r=!0 +if(r){s.c=null +return!1}s.e=!0 +r=s.d +s.c=r +s.d=r.b +return!0}, +$iA:1} +A.a4.prototype={ +gaO(){var s=this.a +if(s==null||this===s.gH(0))return null +return this.c}, +scr(a){this.a=A.u(this).h("c8?").a(a)}, +saF(a){this.b=A.u(this).h("a4.E?").a(a)}, +saG(a){this.c=A.u(this).h("a4.E?").a(a)}} +A.r.prototype={ +gu(a){return new A.bs(a,this.gk(a),A.aq(a).h("bs"))}, +C(a,b){return this.i(a,b)}, +M(a,b){var s,r +A.aq(a).h("~(r.E)").a(b) +s=this.gk(a) +for(r=0;r").t(c).h("a5<1,2>"))}, +O(a,b){return A.eF(a,b,null,A.aq(a).h("r.E"))}, +b5(a,b){return new A.ae(a,A.aq(a).h("@").t(b).h("ae<1,2>"))}, +cR(a,b,c,d){var s +A.aq(a).h("r.E?").a(d) +A.bw(b,c,this.gk(a)) +for(s=b;s").a(d) +A.bw(b,c,this.gk(a)) +s=c-b +if(s===0)return +A.aa(e,"skipCount") +if(t.j.b(d)){r=e +q=d}else{q=J.dM(d,e).aw(0,!1) +r=0}p=J.ap(q) +if(r+s>p.gk(q))throw A.c(A.lM()) +if(r=0;--o)this.l(a,b+o,p.i(q,r+o)) +else for(o=0;o").a(c) +if(t.j.b(c))this.R(a,b,b+c.length,c) +else for(s=J.W(c);s.m();b=r){r=b+1 +this.l(a,b,s.gp())}}, +j(a){return A.kw(a,"[","]")}, +$in:1, +$ie:1, +$it:1} +A.D.prototype={ +M(a,b){var s,r,q,p=A.u(this) +p.h("~(D.K,D.V)").a(b) +for(s=J.W(this.gN()),p=p.h("D.V");s.m();){r=s.gp() +q=this.i(0,r) +b.$2(r,q==null?p.a(q):q)}}, +gao(){return J.lw(this.gN(),new A.h5(this),A.u(this).h("K"))}, +f3(a,b,c,d){var s,r,q,p,o,n=A.u(this) +n.t(c).t(d).h("K<1,2>(D.K,D.V)").a(b) +s=A.O(c,d) +for(r=J.W(this.gN()),n=n.h("D.V");r.m();){q=r.gp() +p=this.i(0,q) +o=b.$2(q,p==null?n.a(p):p) +s.l(0,o.a,o.b)}return s}, +L(a){return J.lv(this.gN(),a)}, +gk(a){return J.P(this.gN())}, +ga8(){return new A.dj(this,A.u(this).h("dj"))}, +j(a){return A.h6(this)}, +$iI:1} +A.h5.prototype={ +$1(a){var s=this.a,r=A.u(s) +r.h("D.K").a(a) +s=s.i(0,a) +if(s==null)s=r.h("D.V").a(s) +return new A.K(a,s,r.h("K"))}, +$S(){return A.u(this.a).h("K(D.K)")}} +A.h7.prototype={ +$2(a,b){var s,r=this.a +if(!r.a)this.b.a+=", " +r.a=!1 +r=this.b +s=A.o(a) +r.a=(r.a+=s)+": " +s=A.o(b) +r.a+=s}, +$S:60} +A.cg.prototype={} +A.dj.prototype={ +gk(a){var s=this.a +return s.gk(s)}, +gH(a){var s=this.a +s=s.i(0,J.b4(s.gN())) +return s==null?this.$ti.y[1].a(s):s}, +gu(a){var s=this.a +return new A.dk(J.W(s.gN()),s,this.$ti.h("dk<1,2>"))}} +A.dk.prototype={ +m(){var s=this,r=s.a +if(r.m()){s.c=s.b.i(0,r.gp()) +return!0}s.c=null +return!1}, +gp(){var s=this.c +return s==null?this.$ti.y[1].a(s):s}, +$iA:1} +A.dz.prototype={} +A.cc.prototype={ +a6(a,b,c){var s=this.$ti +return new A.bl(this,s.t(c).h("1(2)").a(b),s.h("@<1>").t(c).h("bl<1,2>"))}, +j(a){return A.kw(this,"{","}")}, +O(a,b){return A.m4(this,b,this.$ti.c)}, +gH(a){var s,r=A.mq(this,this.r,this.$ti.c) +if(!r.m())throw A.c(A.aE()) +s=r.d +return s==null?r.$ti.c.a(s):s}, +C(a,b){var s,r,q,p=this +A.aa(b,"index") +s=A.mq(p,p.r,p.$ti.c) +for(r=b;s.m();){if(r===0){q=s.d +return q==null?s.$ti.c.a(q):q}--r}throw A.c(A.ea(b,b-r,p,null,"index"))}, +$in:1, +$ie:1, +$ikH:1} +A.dr.prototype={} +A.jM.prototype={ +$0(){var s,r +try{s=new TextDecoder("utf-8",{fatal:true}) +return s}catch(r){}return null}, +$S:20} +A.jL.prototype={ +$0(){var s,r +try{s=new TextDecoder("utf-8",{fatal:false}) +return s}catch(r){}return null}, +$S:20} +A.dQ.prototype={ +f6(a3,a4,a5){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,a0="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a1="Invalid base64 encoding length ",a2=a3.length +a5=A.bw(a4,a5,a2) +s=$.nF() +for(r=s.length,q=a4,p=q,o=null,n=-1,m=-1,l=0;q=0&&e=0){if(!(d<64))return A.b(a0,d) +e=a0.charCodeAt(d) +if(e===j)continue +j=e}else{if(d===-1){if(n<0){g=o==null?null:o.a.length +if(g==null)g=0 +n=g+(q-p) +m=q}++l +if(j===61)continue}j=e}if(d!==-2){if(o==null){o=new A.ac("") +g=o}else g=o +g.a+=B.a.q(a3,p,q) +c=A.aS(j) +g.a+=c +p=k +continue}}throw A.c(A.a3("Invalid base64 data",a3,q))}if(o!=null){a2=B.a.q(a3,p,a5) +a2=o.a+=a2 +r=a2.length +if(n>=0)A.lx(a3,m,a5,n,l,r) +else{b=B.c.Y(r-1,4)+1 +if(b===1)throw A.c(A.a3(a1,a3,a5)) +for(;b<4;){a2+="=" +o.a=a2;++b}}a2=o.a +return B.a.au(a3,a4,a5,a2.charCodeAt(0)==0?a2:a2)}a=a5-a4 +if(n>=0)A.lx(a3,m,a5,n,l,a) +else{b=B.c.Y(a,4) +if(b===1)throw A.c(A.a3(a1,a3,a5)) +if(b>1)a3=B.a.au(a3,a5,a5,b===2?"==":"=")}return a3}} +A.fI.prototype={} +A.bZ.prototype={} +A.e1.prototype={} +A.e5.prototype={} +A.eM.prototype={ +aL(a){t.L.a(a) +return new A.dC(!1).bE(a,0,null,!0)}} +A.ie.prototype={ +an(a){var s,r,q,p,o=a.length,n=A.bw(0,null,o) +if(n===0)return new Uint8Array(0) +s=n*3 +r=new Uint8Array(s) +q=new A.jN(r) +if(q.dT(a,0,n)!==n){p=n-1 +if(!(p>=0&&p>>18|240 +q=n.b=p+1 +if(!(p>>12&63|128 +p=n.b=q+1 +if(!(q>>6&63|128 +n.b=p+1 +if(!(p=0&&s=q)break +k.b=m+1 +r&2&&A.y(s) +s[m]=n}else{m=n&64512 +if(m===55296){if(k.b+4>q)break +m=o+1 +if(!(mq)break +k.bT()}else if(n<=2047){m=k.b +l=m+1 +if(l>=q)break +k.b=l +r&2&&A.y(s) +if(!(m>>6|192 +k.b=l+1 +s[l]=n&63|128}else{m=k.b +if(m+2>=q)break +l=k.b=m+1 +r&2&&A.y(s) +if(!(m>>12|224 +m=k.b=l+1 +if(!(l>>6&63|128 +k.b=m+1 +if(!(m=15){o=l.a +n=A.q5(o,q,b,s) +if(n!=null){if(!o)return n +if(n.indexOf("\ufffd")<0)return n}}n=l.bF(q,b,s,!0) +o=l.b +if((o&1)!==0){m=A.q7(o) +l.b=0 +throw A.c(A.a3(m,a,p+l.c))}return n}, +bF(a,b,c,d){var s,r,q=this +if(c-b>1000){s=B.c.E(b+c,2) +r=q.bF(a,b,s,!1) +if((q.b&1)!==0)return r +return r+q.bF(a,s,c,d)}return q.eq(a,b,c,d)}, +eq(a,b,a0,a1){var s,r,q,p,o,n,m,l,k=this,j="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHIHHHJEEBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBKCCCCCCCCCCCCDCLONNNMEEEEEEEEEEE",i=" \x000:XECCCCCN:lDb \x000:XECCCCCNvlDb \x000:XECCCCCN:lDb AAAAA\x00\x00\x00\x00\x00AAAAA00000AAAAA:::::AAAAAGG000AAAAA00KKKAAAAAG::::AAAAA:IIIIAAAAA000\x800AAAAA\x00\x00\x00\x00 AAAAA",h=65533,g=k.b,f=k.c,e=new A.ac(""),d=b+1,c=a.length +if(!(b>=0&&b=0&&s<256))return A.b(j,s) +q=j.charCodeAt(s)&31 +f=g<=32?s&61694>>>q:(s&63|f<<6)>>>0 +p=g+q +if(!(p>=0&&p<144))return A.b(i,p) +g=i.charCodeAt(p) +if(g===0){p=A.aS(f) +e.a+=p +if(d===a0)break $label0$0 +break}else if((g&1)!==0){if(r)switch(g){case 69:case 67:p=A.aS(h) +e.a+=p +break +case 65:p=A.aS(h) +e.a+=p;--d +break +default:p=A.aS(h) +e.a=(e.a+=p)+A.aS(h) +break}else{k.b=g +k.c=d-1 +return""}g=0}if(d===a0)break $label0$0 +o=d+1 +if(!(d>=0&&d=0&&d=0&&o=128){n=m-1 +o=m +break}o=m}if(n-d<20)for(l=d;l32)if(r){c=A.aS(h) +e.a+=c}else{k.b=77 +k.c=a0 +return""}k.b=g +k.c=f +c=e.a +return c.charCodeAt(0)==0?c:c}} +A.R.prototype={ +a3(a){var s,r,q=this,p=q.c +if(p===0)return q +s=!q.a +r=q.b +p=A.as(p,r) +return new A.R(p===0?!1:s,r,p)}, +dM(a){var s,r,q,p,o,n,m,l,k=this,j=k.c +if(j===0)return $.b2() +s=j-a +if(s<=0)return k.a?$.lq():$.b2() +r=k.b +q=new Uint16Array(s) +for(p=r.length,o=a;o=0&&o=0&&r>>0!==0)return l.bv(0,$.fz()) +for(k=0;k=0)return q.aU(b,r) +return b.aU(q,!r)}, +bv(a,b){var s,r,q=this,p=q.c +if(p===0)return b.a3(0) +s=b.c +if(s===0)return q +r=q.a +if(r!==b.a)return q.bw(b,r) +if(A.iv(q.b,p,b.b,s)>=0)return q.aU(b,r) +return b.aU(q,!r)}, +aT(a,b){var s,r,q,p,o,n,m,l=this.c,k=b.c +if(l===0||k===0)return $.b2() +s=l+k +r=this.b +q=b.b +p=new Uint16Array(s) +for(o=q.length,n=0;n0?p.a3(0):p}, +e6(a){var s,r,q,p=this +if(p.c0)q=q.aC(0,$.l_.S()) +return p.a&&q.c>0?q.a3(0):q}, +cl(a){var s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c=this,b=c.c +if(b===$.mk&&a.c===$.mm&&c.b===$.mj&&a.b===$.ml)return +s=a.b +r=a.c +q=r-1 +if(!(q>=0&&q0){o=new Uint16Array(r+5) +n=A.mi(s,r,p,o) +m=new Uint16Array(b+5) +l=A.mi(c.b,b,p,m)}else{m=A.l0(c.b,0,b,b+2) +n=r +o=s +l=b}q=n-1 +if(!(q>=0&&q=0){q&2&&A.y(m) +if(!(l>=0&&l=0&&l=0&&n0;){d=A.pB(k,m,e);--j +A.mn(d,f,0,m,j,n) +if(!(e>=0&&e=m.length)return A.b(m,0) +return B.c.j(-m[0])}m=n.b +if(0>=m.length)return A.b(m,0) +return B.c.j(m[0])}s=A.x([],t.s) +m=n.a +r=m?n.a3(0):n +for(;r.c>1;){q=$.lp() +if(q.c===0)A.H(B.w) +p=r.e6(q).j(0) +B.b.n(s,p) +o=p.length +if(o===1)B.b.n(s,"000") +if(o===2)B.b.n(s,"00") +if(o===3)B.b.n(s,"0") +r=r.dL(q)}q=r.b +if(0>=q.length)return A.b(q,0) +B.b.n(s,B.c.j(q[0])) +if(m)B.b.n(s,"-") +return new A.d0(s,t.bJ).f0(0)}, +$ibX:1, +$ia8:1} +A.iw.prototype={ +$2(a,b){a=a+b&536870911 +a=a+((a&524287)<<10)&536870911 +return a^a>>>6}, +$S:1} +A.ix.prototype={ +$1(a){a=a+((a&67108863)<<3)&536870911 +a^=a>>>11 +return a+((a&16383)<<15)&536870911}, +$S:11} +A.f2.prototype={ +cN(a){var s=this.a +if(s!=null)s.unregister(a)}} +A.bk.prototype={ +X(a,b){var s +if(b==null)return!1 +s=!1 +if(b instanceof A.bk)if(this.a===b.a)s=this.b===b.b +return s}, +gv(a){return A.lT(this.a,this.b,B.h,B.h)}, +T(a,b){var s +t.dy.a(b) +s=B.c.T(this.a,b.a) +if(s!==0)return s +return B.c.T(this.b,b.b)}, +j(a){var s=this,r=A.o4(A.m0(s)),q=A.e4(A.lZ(s)),p=A.e4(A.lW(s)),o=A.e4(A.lX(s)),n=A.e4(A.lY(s)),m=A.e4(A.m_(s)),l=A.lH(A.oC(s)),k=s.b,j=k===0?"":A.lH(k) +return r+"-"+q+"-"+p+" "+o+":"+n+":"+m+"."+l+j}, +$ia8:1} +A.b6.prototype={ +X(a,b){if(b==null)return!1 +return b instanceof A.b6&&this.a===b.a}, +gv(a){return B.c.gv(this.a)}, +T(a,b){return B.c.T(this.a,t.fu.a(b).a)}, +j(a){var s,r,q,p,o,n=this.a,m=B.c.E(n,36e8),l=n%36e8 +if(n<0){m=0-m +n=0-l +s="-"}else{n=l +s=""}r=B.c.E(n,6e7) +n%=6e7 +q=r<10?"0":"" +p=B.c.E(n,1e6) +o=p<10?"0":"" +return s+m+":"+q+r+":"+o+p+"."+B.a.f9(B.c.j(n%1e6),6,"0")}, +$ia8:1} +A.iC.prototype={ +j(a){return this.dO()}} +A.J.prototype={ +gaj(){return A.oB(this)}} +A.dN.prototype={ +j(a){var s=this.a +if(s!=null)return"Assertion failed: "+A.fV(s) +return"Assertion failed"}} +A.aV.prototype={} +A.aw.prototype={ +gbH(){return"Invalid argument"+(!this.a?"(s)":"")}, +gbG(){return""}, +j(a){var s=this,r=s.c,q=r==null?"":" ("+r+")",p=s.d,o=p==null?"":": "+A.o(p),n=s.gbH()+q+o +if(!s.a)return n +return n+s.gbG()+": "+A.fV(s.gc2())}, +gc2(){return this.b}} +A.cb.prototype={ +gc2(){return A.mW(this.b)}, +gbH(){return"RangeError"}, +gbG(){var s,r=this.e,q=this.f +if(r==null)s=q!=null?": Not less than or equal to "+A.o(q):"" +else if(q==null)s=": Not greater than or equal to "+A.o(r) +else if(q>r)s=": Not in inclusive range "+A.o(r)+".."+A.o(q) +else s=qe.length +else s=!1 +if(s)f=null +if(f==null){if(e.length>78)e=B.a.q(e,0,75)+"..." +return g+"\n"+e}for(r=e.length,q=1,p=0,o=!1,n=0;n1?g+(" (at line "+q+", character "+(f-p+1)+")\n"):g+(" (at character "+(f+1)+")\n") +for(n=f;n=0))return A.b(e,n) +m=e.charCodeAt(n) +if(m===10||m===13){r=n +break}}l="" +if(r-p>78){k="..." +if(f-p<75){j=p+75 +i=p}else{if(r-f<75){i=r-75 +j=r +k=""}else{i=f-36 +j=f+36}l="..."}}else{j=r +i=p +k=""}return g+l+B.a.q(e,i,j)+k+"\n"+B.a.aT(" ",f-i+l.length)+"^\n"}else return f!=null?g+(" (at offset "+A.o(f)+")"):g}} +A.ec.prototype={ +gaj(){return null}, +j(a){return"IntegerDivisionByZeroException"}, +$iJ:1} +A.e.prototype={ +b5(a,b){return A.dV(this,A.u(this).h("e.E"),b)}, +a6(a,b,c){var s=A.u(this) +return A.ow(this,s.t(c).h("1(e.E)").a(b),s.h("e.E"),c)}, +G(a,b){var s +for(s=this.gu(this);s.m();)if(J.V(s.gp(),b))return!0 +return!1}, +aw(a,b){var s=A.u(this).h("e.E") +if(b)s=A.kB(this,s) +else{s=A.kB(this,s) +s.$flags=1 +s=s}return s}, +d4(a){return this.aw(0,!0)}, +gk(a){var s,r=this.gu(this) +for(s=0;r.m();)++s +return s}, +gW(a){return!this.gu(this).m()}, +O(a,b){return A.m4(this,b,A.u(this).h("e.E"))}, +gH(a){var s=this.gu(this) +if(!s.m())throw A.c(A.aE()) +return s.gp()}, +C(a,b){var s,r +A.aa(b,"index") +s=this.gu(this) +for(r=b;s.m();){if(r===0)return s.gp();--r}throw A.c(A.ea(b,b-r,this,null,"index"))}, +j(a){return A.oj(this,"(",")")}} +A.K.prototype={ +j(a){return"MapEntry("+A.o(this.a)+": "+A.o(this.b)+")"}} +A.F.prototype={ +gv(a){return A.q.prototype.gv.call(this,0)}, +j(a){return"null"}} +A.q.prototype={$iq:1, +X(a,b){return this===b}, +gv(a){return A.et(this)}, +j(a){return"Instance of '"+A.hc(this)+"'"}, +gB(a){return A.nh(this)}, +toString(){return this.j(this)}} +A.fo.prototype={ +j(a){return""}, +$iaF:1} +A.ac.prototype={ +gk(a){return this.a.length}, +j(a){var s=this.a +return s.charCodeAt(0)==0?s:s}, +$ipk:1} +A.ib.prototype={ +$2(a,b){throw A.c(A.a3("Illegal IPv4 address, "+a,this.a,b))}, +$S:25} +A.ic.prototype={ +$2(a,b){throw A.c(A.a3("Illegal IPv6 address, "+a,this.a,b))}, +$S:28} +A.id.prototype={ +$2(a,b){var s +if(b-a>4)this.a.$2("an IPv6 part can only contain a maximum of 4 hex digits",a) +s=A.kc(B.a.q(this.b,a,b),16) +if(s<0||s>65535)this.a.$2("each part must be in the range of `0x0..0xFFFF`",a) +return s}, +$S:1} +A.dA.prototype={ +gcD(){var s,r,q,p,o=this,n=o.w +if(n===$){s=o.a +r=s.length!==0?""+s+":":"" +q=o.c +p=q==null +if(!p||s==="file"){s=r+"//" +r=o.b +if(r.length!==0)s=s+r+"@" +if(!p)s+=q +r=o.d +if(r!=null)s=s+":"+A.o(r)}else s=r +s+=o.e +r=o.f +if(r!=null)s=s+"?"+r +r=o.r +if(r!=null)s=s+"#"+r +n!==$&&A.fx("_text") +n=o.w=s.charCodeAt(0)==0?s:s}return n}, +gfa(){var s,r,q,p=this,o=p.x +if(o===$){s=p.e +r=s.length +if(r!==0){if(0>=r)return A.b(s,0) +r=s.charCodeAt(0)===47}else r=!1 +if(r)s=B.a.Z(s,1) +q=s.length===0?B.I:A.eh(new A.a5(A.x(s.split("/"),t.s),t.dO.a(A.qZ()),t.do),t.N) +p.x!==$&&A.fx("pathSegments") +o=p.x=q}return o}, +gv(a){var s,r=this,q=r.y +if(q===$){s=B.a.gv(r.gcD()) +r.y!==$&&A.fx("hashCode") +r.y=s +q=s}return q}, +gd6(){return this.b}, +gbd(){var s=this.c +if(s==null)return"" +if(B.a.J(s,"["))return B.a.q(s,1,s.length-1) +return s}, +gc7(){var s=this.d +return s==null?A.mD(this.a):s}, +gd0(){var s=this.f +return s==null?"":s}, +gcS(){var s=this.r +return s==null?"":s}, +gcX(){if(this.a!==""){var s=this.r +s=(s==null?"":s)===""}else s=!1 +return s}, +gcU(){return this.c!=null}, +gcW(){return this.f!=null}, +gcV(){return this.r!=null}, +fn(){var s,r=this,q=r.a +if(q!==""&&q!=="file")throw A.c(A.U("Cannot extract a file path from a "+q+" URI")) +q=r.f +if((q==null?"":q)!=="")throw A.c(A.U("Cannot extract a file path from a URI with a query component")) +q=r.r +if((q==null?"":q)!=="")throw A.c(A.U("Cannot extract a file path from a URI with a fragment component")) +if(r.c!=null&&r.gbd()!=="")A.H(A.U("Cannot extract a non-Windows file path from a file URI with an authority")) +s=r.gfa() +A.pZ(s,!1) +q=A.kS(B.a.J(r.e,"/")?""+"/":"",s,"/") +q=q.charCodeAt(0)==0?q:q +return q}, +j(a){return this.gcD()}, +X(a,b){var s,r,q,p=this +if(b==null)return!1 +if(p===b)return!0 +s=!1 +if(t.dD.b(b))if(p.a===b.gbu())if(p.c!=null===b.gcU())if(p.b===b.gd6())if(p.gbd()===b.gbd())if(p.gc7()===b.gc7())if(p.e===b.gc6()){r=p.f +q=r==null +if(!q===b.gcW()){if(q)r="" +if(r===b.gd0()){r=p.r +q=r==null +if(!q===b.gcV()){s=q?"":r +s=s===b.gcS()}}}}return s}, +$ieK:1, +gbu(){return this.a}, +gc6(){return this.e}} +A.ia.prototype={ +gd5(){var s,r,q,p,o=this,n=null,m=o.c +if(m==null){m=o.b +if(0>=m.length)return A.b(m,0) +s=o.a +m=m[0]+1 +r=B.a.ae(s,"?",m) +q=s.length +if(r>=0){p=A.dB(s,r+1,q,256,!1,!1) +q=r}else p=n +m=o.c=new A.f0("data","",n,n,A.dB(s,m,q,128,!1,!1),p,n)}return m}, +j(a){var s,r=this.b +if(0>=r.length)return A.b(r,0) +s=this.a +return r[0]===-1?"data:"+s:s}} +A.fi.prototype={ +gcU(){return this.c>0}, +geR(){return this.c>0&&this.d+10&&this.r>=this.a.length}, +gbu(){var s=this.w +return s==null?this.w=this.dI():s}, +dI(){var s,r=this,q=r.b +if(q<=0)return"" +s=q===4 +if(s&&B.a.J(r.a,"http"))return"http" +if(q===5&&B.a.J(r.a,"https"))return"https" +if(s&&B.a.J(r.a,"file"))return"file" +if(q===7&&B.a.J(r.a,"package"))return"package" +return B.a.q(r.a,0,q)}, +gd6(){var s=this.c,r=this.b+3 +return s>r?B.a.q(this.a,r,s-1):""}, +gbd(){var s=this.c +return s>0?B.a.q(this.a,s,this.d):""}, +gc7(){var s,r=this +if(r.geR())return A.kc(B.a.q(r.a,r.d+1,r.e),null) +s=r.b +if(s===4&&B.a.J(r.a,"http"))return 80 +if(s===5&&B.a.J(r.a,"https"))return 443 +return 0}, +gc6(){return B.a.q(this.a,this.e,this.f)}, +gd0(){var s=this.f,r=this.r +return s4294967296)throw A.c(new A.cb(k,k,!1,k,k,"max must be in range 0 < max \u2264 2^32, was "+a)) +if(a>255)if(a>65535)s=a>16777215?4:3 +else s=2 +else s=1 +r=this.a +r.$flags&2&&A.y(r,11) +r.setUint32(0,0,!1) +q=4-s +p=A.d(Math.pow(256,s)) +for(o=a-1,n=(a&o)===0;!0;){crypto.getRandomValues(J.cv(B.J.gam(r),q,s)) +m=r.getUint32(0,!1) +if(n)return(m&o)>>>0 +l=m%a +if(m-l+a")),r=this.a,p=!1,o=!1,n="";s.m();){m=q.gp() +if(r.aq(m)&&o){l=A.lU(m,r) +k=n.charCodeAt(0)==0?n:n +n=B.a.q(k,0,r.av(k,!0)) +l.b=n +if(r.aN(n))B.b.l(l.e,0,r.gaA()) +n=""+l.j(0)}else if(r.a7(m)>0){o=!r.aq(m) +n=""+m}else{j=m.length +if(j!==0){if(0>=j)return A.b(m,0) +j=r.bX(m[0])}else j=!1 +if(!j)if(p)n+=r.gaA() +n+=m}p=r.aN(m)}return n.charCodeAt(0)==0?n:n}, +cZ(a){var s +if(!this.e2(a))return a +s=A.lU(a,this.a) +s.f5() +return s.j(0)}, +e2(a){var s,r,q,p,o,n,m,l,k=this.a,j=k.a7(a) +if(j!==0){if(k===$.fy())for(s=a.length,r=0;r=0))return A.b(s,r) +m=s.charCodeAt(r) +if(k.a1(m)){if(k===$.fy()&&m===47)return!0 +if(p!=null&&k.a1(p))return!0 +if(p===46)l=n==null||n===46||k.a1(n) +else l=!1 +if(l)return!0}}if(p==null)return!0 +if(k.a1(p))return!0 +if(p===46)k=n==null||k.a1(n)||n===46 +else k=!1 +if(k)return!0 +return!1}} +A.fR.prototype={ +$1(a){return A.L(a)!==""}, +$S:46} +A.k_.prototype={ +$1(a){A.jQ(a) +return a==null?"null":'"'+a+'"'}, +$S:48} +A.c5.prototype={ +dg(a){var s,r=this.a7(a) +if(r>0)return B.a.q(a,0,r) +if(this.aq(a)){if(0>=a.length)return A.b(a,0) +s=a[0]}else s=null +return s}} +A.ha.prototype={ +fi(){var s,r,q=this +while(!0){s=q.d +if(!(s.length!==0&&J.V(B.b.ga2(s),"")))break +s=q.d +if(0>=s.length)return A.b(s,-1) +s.pop() +s=q.e +if(0>=s.length)return A.b(s,-1) +s.pop()}s=q.e +r=s.length +if(r!==0)B.b.l(s,r-1,"")}, +f5(){var s,r,q,p,o,n,m=this,l=A.x([],t.s) +for(s=m.d,r=s.length,q=0,p=0;p=n)return A.b(l,-1) +l.pop()}else ++q}else B.b.n(l,o)}if(m.b==null)B.b.eS(l,0,A.cS(q,"..",!1,t.N)) +if(l.length===0&&m.b==null)B.b.n(l,".") +m.d=l +s=m.a +m.e=A.cS(l.length+1,s.gaA(),!0,t.N) +r=m.b +if(r==null||l.length===0||!s.aN(r))B.b.l(m.e,0,"") +r=m.b +if(r!=null&&s===$.fy())m.b=A.rn(r,"/","\\") +m.fi()}, +j(a){var s,r,q,p,o,n=this.b +n=n!=null?""+n:"" +for(s=this.d,r=s.length,q=this.e,p=q.length,o=0;o=0))return A.b(a,s) +s=a.charCodeAt(s)!==47 +r=s}else r=!1 +return r}, +av(a,b){var s=a.length +if(s!==0){if(0>=s)return A.b(a,0) +s=a.charCodeAt(0)===47}else s=!1 +if(s)return 1 +return 0}, +a7(a){return this.av(a,!1)}, +aq(a){return!1}, +gc5(){return"posix"}, +gaA(){return"/"}} +A.eL.prototype={ +bX(a){return B.a.G(a,"/")}, +a1(a){return a===47}, +aN(a){var s,r=a.length +if(r===0)return!1 +s=r-1 +if(!(s>=0))return A.b(a,s) +if(a.charCodeAt(s)!==47)return!0 +return B.a.cO(a,"://")&&this.a7(a)===r}, +av(a,b){var s,r,q,p=a.length +if(p===0)return 0 +if(0>=p)return A.b(a,0) +if(a.charCodeAt(0)===47)return 1 +for(s=0;s=s)return A.b(a,0) +s=a.charCodeAt(0)===47}else s=!1 +return s}, +gc5(){return"url"}, +gaA(){return"/"}} +A.eV.prototype={ +bX(a){return B.a.G(a,"/")}, +a1(a){return a===47||a===92}, +aN(a){var s,r=a.length +if(r===0)return!1 +s=r-1 +if(!(s>=0))return A.b(a,s) +s=a.charCodeAt(s) +return!(s===47||s===92)}, +av(a,b){var s,r,q=a.length +if(q===0)return 0 +if(0>=q)return A.b(a,0) +if(a.charCodeAt(0)===47)return 1 +if(a.charCodeAt(0)===92){if(q>=2){if(1>=q)return A.b(a,1) +s=a.charCodeAt(1)!==92}else s=!0 +if(s)return 1 +r=B.a.ae(a,"\\",2) +if(r>0){r=B.a.ae(a,"\\",r+1) +if(r>0)return r}return q}if(q<3)return 0 +if(!A.nj(a.charCodeAt(0)))return 0 +if(a.charCodeAt(1)!==58)return 0 +q=a.charCodeAt(2) +if(!(q===47||q===92))return 0 +return 3}, +a7(a){return this.av(a,!1)}, +aq(a){return this.a7(a)===1}, +gc5(){return"windows"}, +gaA(){return"\\"}} +A.k2.prototype={ +$1(a){return A.qT(a)}, +$S:54} +A.e2.prototype={ +j(a){return"DatabaseException("+this.a+")"}} +A.ey.prototype={ +j(a){return this.dm(0)}, +bt(){var s=this.b +return s==null?this.b=new A.hi(this).$0():s}} +A.hi.prototype={ +$0(){var s=new A.hj(this.a.a.toLowerCase()),r=s.$1("(sqlite code ") +if(r!=null)return r +r=s.$1("(code ") +if(r!=null)return r +r=s.$1("code=") +if(r!=null)return r +return null}, +$S:33} +A.hj.prototype={ +$1(a){var s,r,q,p,o,n=this.a,m=B.a.c_(n,a) +if(!J.V(m,-1))try{p=m +if(typeof p!=="number")return p.cb() +p=B.a.fo(B.a.Z(n,p+a.length)).split(" ") +if(0>=p.length)return A.b(p,0) +s=p[0] +r=J.nS(s,")") +if(!J.V(r,-1))s=J.nU(s,0,r) +q=A.kE(s,null) +if(q!=null)return q}catch(o){}return null}, +$S:58} +A.fU.prototype={} +A.e7.prototype={ +j(a){return A.nh(this).j(0)+"("+this.a+", "+A.o(this.b)+")"}} +A.c2.prototype={} +A.aU.prototype={ +j(a){var s=this,r=t.N,q=t.X,p=A.O(r,q),o=s.y +if(o!=null){r=A.kA(o,r,q) +q=A.u(r) +o=q.h("q?") +o.a(r.I(0,"arguments")) +o.a(r.I(0,"sql")) +if(r.gf_(0))p.l(0,"details",new A.cz(r,q.h("cz")))}r=s.bt()==null?"":": "+A.o(s.bt())+", " +r=""+("SqfliteFfiException("+s.x+r+", "+s.a+"})") +q=s.r +if(q!=null){r+=" sql "+q +q=s.w +q=q==null?null:!q.gW(q) +if(q===!0){q=s.w +q.toString +q=r+(" args "+A.ne(q)) +r=q}}else r+=" "+s.dq(0) +if(p.a!==0)r+=" "+p.j(0) +return r.charCodeAt(0)==0?r:r}, +sev(a){this.y=t.fn.a(a)}} +A.hx.prototype={} +A.hy.prototype={} +A.d3.prototype={ +j(a){var s=this.a,r=this.b,q=this.c,p=q==null?null:!q.gW(q) +if(p===!0){q.toString +q=" "+A.ne(q)}else q="" +return A.o(s)+" "+(A.o(r)+q)}, +sdj(a){this.c=t.gq.a(a)}} +A.fj.prototype={} +A.fb.prototype={ +A(){var s=0,r=A.l(t.H),q=1,p=[],o=this,n,m,l,k +var $async$A=A.m(function(a,b){if(a===1){p.push(b) +s=q}while(true)switch(s){case 0:q=3 +s=6 +return A.f(o.a.$0(),$async$A) +case 6:n=b +o.b.U(n) +q=1 +s=5 +break +case 3:q=2 +k=p.pop() +m=A.N(k) +o.b.ad(m) +s=5 +break +case 2:s=1 +break +case 5:return A.j(null,r) +case 1:return A.i(p.at(-1),r)}}) +return A.k($async$A,r)}} +A.an.prototype={ +d3(){var s=this +return A.ah(["path",s.r,"id",s.e,"readOnly",s.w,"singleInstance",s.f],t.N,t.X)}, +cn(){var s,r,q=this +if(q.cp()===0)return null +s=q.x.b +r=A.d(A.p(v.G.Number(t.C.a(s.a.x2.call(null,s.b))))) +if(q.y>=1)A.au("[sqflite-"+q.e+"] Inserted "+r) +return r}, +j(a){return A.h6(this.d3())}, +aK(){var s=this +s.aW() +s.ag("Closing database "+s.j(0)) +s.x.V()}, +bI(a){var s=a==null?null:new A.ae(a.a,a.$ti.h("ae<1,q?>")) +return s==null?B.o:s}, +eK(a,b){return this.d.a0(new A.hs(this,a,b),t.H)}, +a4(a,b){return this.dV(a,b)}, +dV(a,b){var s=0,r=A.l(t.H),q,p=[],o=this,n,m,l,k +var $async$a4=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:o.c4(a,b) +if(B.a.J(a,"PRAGMA sqflite -- ")){if(a==="PRAGMA sqflite -- db_config_defensive_off"){m=o.x +l=m.b +k=l.a.dk(l.b,1010,0) +if(k!==0)A.dK(m,k,null,null,null)}}else{m=b==null?null:!b.gW(b) +l=o.x +if(m===!0){n=l.c8(a) +try{n.cP(new A.bq(o.bI(b))) +s=1 +break}finally{n.V()}}else l.ey(a)}case 1:return A.j(q,r)}}) +return A.k($async$a4,r)}, +ag(a){if(a!=null&&this.y>=1)A.au("[sqflite-"+this.e+"] "+a)}, +c4(a,b){var s +if(this.y>=1){s=b==null?null:!b.gW(b) +s=s===!0?" "+A.o(b):"" +A.au("[sqflite-"+this.e+"] "+a+s) +this.ag(null)}}, +b3(){var s=0,r=A.l(t.H),q=this +var $async$b3=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:s=q.c.length!==0?2:3 +break +case 2:s=4 +return A.f(q.as.a0(new A.hq(q),t.P),$async$b3) +case 4:case 3:return A.j(null,r)}}) +return A.k($async$b3,r)}, +aW(){var s=0,r=A.l(t.H),q=this +var $async$aW=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:s=q.c.length!==0?2:3 +break +case 2:s=4 +return A.f(q.as.a0(new A.hl(q),t.P),$async$aW) +case 4:case 3:return A.j(null,r)}}) +return A.k($async$aW,r)}, +aM(a,b){return this.eP(a,t.gJ.a(b))}, +eP(a,b){var s=0,r=A.l(t.z),q,p=2,o=[],n=[],m=this,l,k,j,i,h,g,f +var $async$aM=A.m(function(c,d){if(c===1){o.push(d) +s=p}while(true)switch(s){case 0:g=m.b +s=g==null?3:5 +break +case 3:s=6 +return A.f(b.$0(),$async$aM) +case 6:q=d +s=1 +break +s=4 +break +case 5:s=a===g||a===-1?7:9 +break +case 7:p=11 +s=14 +return A.f(b.$0(),$async$aM) +case 14:g=d +q=g +n=[1] +s=12 +break +n.push(13) +s=12 +break +case 11:p=10 +f=o.pop() +g=A.N(f) +if(g instanceof A.by){l=g +k=!1 +try{if(m.b!=null){g=m.x.b +i=A.d(A.p(g.a.cQ.call(null,g.b)))!==0}else i=!1 +k=i}catch(e){}if(k){m.b=null +g=A.mY(l) +g.d=!0 +throw A.c(g)}else throw f}else throw f +n.push(13) +s=12 +break +case 10:n=[2] +case 12:p=2 +if(m.b==null)m.b3() +s=n.pop() +break +case 13:s=8 +break +case 9:g=new A.v($.w,t.D) +B.b.n(m.c,new A.fb(b,new A.bH(g,t.ez))) +q=g +s=1 +break +case 8:case 4:case 1:return A.j(q,r) +case 2:return A.i(o.at(-1),r)}}) +return A.k($async$aM,r)}, +eL(a,b){return this.d.a0(new A.ht(this,a,b),t.I)}, +b_(a,b){return this.dW(a,b)}, +dW(a,b){var s=0,r=A.l(t.I),q,p=this,o +var $async$b_=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:if(p.w)A.H(A.ez("sqlite_error",null,"Database readonly",null)) +s=3 +return A.f(p.a4(a,b),$async$b_) +case 3:o=p.cn() +if(p.y>=1)A.au("[sqflite-"+p.e+"] Inserted id "+A.o(o)) +q=o +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$b_,r)}, +eQ(a,b){return this.d.a0(new A.hw(this,a,b),t.S)}, +b1(a,b){return this.e_(a,b)}, +e_(a,b){var s=0,r=A.l(t.S),q,p=this +var $async$b1=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:if(p.w)A.H(A.ez("sqlite_error",null,"Database readonly",null)) +s=3 +return A.f(p.a4(a,b),$async$b1) +case 3:q=p.cp() +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$b1,r)}, +eN(a,b,c){return this.d.a0(new A.hv(this,a,c,b),t.z)}, +b0(a,b){return this.dX(a,b)}, +dX(a,b){var s=0,r=A.l(t.z),q,p=[],o=this,n,m,l,k +var $async$b0=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:k=o.x.c8(a) +try{o.c4(a,b) +m=k +l=o.bI(b) +if(m.c.d)A.H(A.Q(u.n)) +m.al() +m.by(new A.bq(l)) +n=m.ea() +o.ag("Found "+n.d.length+" rows") +m=n +m=A.ah(["columns",m.a,"rows",m.d],t.N,t.X) +q=m +s=1 +break}finally{k.V()}case 1:return A.j(q,r)}}) +return A.k($async$b0,r)}, +cw(a){var s,r,q,p,o,n,m,l,k=a.a,j=k +try{s=a.d +r=s.a +q=A.x([],t.G) +for(n=a.c;!0;){if(s.m()){m=s.x +m===$&&A.aK("current") +p=m +J.lu(q,p.b)}else{a.e=!0 +break}if(J.P(q)>=n)break}o=A.ah(["columns",r,"rows",q],t.N,t.X) +if(!a.e)J.fB(o,"cursorId",k) +return o}catch(l){this.bA(j) +throw l}finally{if(a.e)this.bA(j)}}, +bK(a,b,c){return this.dY(a,b,c)}, +dY(a,b,c){var s=0,r=A.l(t.X),q,p=this,o,n,m,l,k +var $async$bK=A.m(function(d,e){if(d===1)return A.i(e,r) +while(true)switch(s){case 0:k=p.x.c8(b) +p.c4(b,c) +o=p.bI(c) +n=k.c +if(n.d)A.H(A.Q(u.n)) +k.al() +k.by(new A.bq(o)) +o=k.gbC() +k.gcB() +m=new A.eW(k,o,B.p) +m.bz() +n.c=!1 +k.f=m +n=++p.Q +l=new A.fj(n,k,a,m) +p.z.l(0,n,l) +q=p.cw(l) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$bK,r)}, +eO(a,b){return this.d.a0(new A.hu(this,b,a),t.z)}, +bL(a,b){return this.dZ(a,b)}, +dZ(a,b){var s=0,r=A.l(t.X),q,p=this,o,n +var $async$bL=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:if(p.y>=2){o=a===!0?" (cancel)":"" +p.ag("queryCursorNext "+b+o)}n=p.z.i(0,b) +if(a===!0){p.bA(b) +q=null +s=1 +break}if(n==null)throw A.c(A.Q("Cursor "+b+" not found")) +q=p.cw(n) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$bL,r)}, +bA(a){var s=this.z.I(0,a) +if(s!=null){if(this.y>=2)this.ag("Closing cursor "+a) +s.b.V()}}, +cp(){var s=this.x.b,r=A.d(A.p(s.a.x1.call(null,s.b))) +if(this.y>=1)A.au("[sqflite-"+this.e+"] Modified "+r+" rows") +return r}, +eH(a,b,c){return this.d.a0(new A.hr(this,t.Y.a(c),b,a),t.z)}, +aa(a,b,c){return this.dU(a,b,t.Y.a(c))}, +dU(b3,b4,b5){var s=0,r=A.l(t.z),q,p=2,o=[],n=this,m,l,k,j,i,h,g,f,e,d,c,b,a,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,b0,b1,b2 +var $async$aa=A.m(function(b6,b7){if(b6===1){o.push(b7) +s=p}while(true)switch(s){case 0:a8={} +a8.a=null +d=!b4 +if(d)a8.a=A.x([],t.aX) +c=b5.length,b=n.y>=1,a=n.x.b,a0=a.b,a=a.a.x1,a1="[sqflite-"+n.e+"] Modified ",a2=0 +case 3:if(!(a2")),0) +q.onmessage=A.at(new A.kg(this.b))}, +$S:4} +A.kg.prototype={ +$1(a){this.a.aP(new A.kf(t.m.a(a)),t.P)}, +$S:9} +A.kf.prototype={ +$0(){A.dF(this.a)}, +$S:4} +A.kk.prototype={ +$1(a){this.a.aP(new A.kh(t.m.a(a)),t.P)}, +$S:9} +A.kh.prototype={ +$0(){A.dF(this.a)}, +$S:4} +A.cn.prototype={} +A.aA.prototype={ +aL(a){if(typeof a=="string")return A.l2(a,null) +throw A.c(A.U("invalid encoding for bigInt "+A.o(a)))}} +A.jP.prototype={ +$2(a,b){A.d(a) +t.J.a(b) +return new A.K(b.a,b,t.dA)}, +$S:43} +A.jU.prototype={ +$2(a,b){var s,r,q +if(typeof a!="string")throw A.c(A.aM(a,null,null)) +s=A.l9(b) +if(s==null?b!=null:s!==b){r=this.a +q=r.a;(q==null?r.a=A.kA(this.b,t.N,t.X):q).l(0,a,s)}}, +$S:8} +A.jT.prototype={ +$2(a,b){var s,r,q=A.l8(b) +if(q==null?b!=null:q!==b){s=this.a +r=s.a +s=r==null?s.a=A.kA(this.b,t.N,t.X):r +s.l(0,J.aC(a),q)}}, +$S:8} +A.i2.prototype={ +$2(a,b){var s +A.L(a) +s=b==null?null:A.i1(b) +this.a[a]=s}, +$S:8} +A.i0.prototype={ +j(a){return"SqfliteFfiWebOptions(inMemory: null, sqlite3WasmUri: null, indexedDbName: null, sharedWorkerUri: null, forceAsBasicWorker: null)"}} +A.d4.prototype={} +A.eB.prototype={} +A.by.prototype={ +j(a){var s,r,q=this,p=q.e +p=p==null?"":"while "+p+", " +p="SqliteException("+q.c+"): "+p+q.a +s=q.b +if(s!=null)p=p+", "+s +s=q.f +if(s!=null){r=q.d +r=r!=null?" (at position "+A.o(r)+"): ":": " +s=p+"\n Causing statement"+r+s +p=q.r +p=p!=null?s+(", parameters: "+J.lw(p,new A.i4(),t.N).af(0,", ")):s}return p.charCodeAt(0)==0?p:p}} +A.i4.prototype={ +$1(a){if(t.p.b(a))return"blob ("+a.length+" bytes)" +else return J.aC(a)}, +$S:55} +A.eu.prototype={} +A.eC.prototype={} +A.ev.prototype={} +A.hf.prototype={} +A.cZ.prototype={} +A.hd.prototype={} +A.he.prototype={} +A.e8.prototype={ +V(){var s,r,q,p,o,n,m +for(s=this.d,r=s.length,q=0;q0)A.H(A.lI("BigInt value exceeds the range of 64 bits")) +A.d(A.p(r.c.p4.call(null,r.b,b,t.C.a(v.G.BigInt(a.j(0)))))) +break $label0$0}if(A.dG(a)){r=n.a +n=a?1:0 +A.d(A.p(r.c.p4.call(null,r.b,b,t.C.a(v.G.BigInt(n))))) +break $label0$0}if(typeof a=="number"){r=n.a +A.d(A.p(r.c.R8.call(null,r.b,b,a))) +break $label0$0}if(typeof a=="string"){r=n.a +q=B.f.an(a) +p=r.c +o=p.bV(q) +B.b.n(r.d,o) +A.d(A.fu(p.RG,"call",[null,r.b,b,o,q.length,0],t.i)) +break $label0$0}r=t.L +if(r.b(a)){p=n.a +r.a(a) +r=p.c +o=r.bV(a) +B.b.n(p.d,o) +A.d(A.fu(r.rx,"call",[null,p.b,b,o,t.C.a(v.G.BigInt(J.P(a))),0],t.i)) +break $label0$0}s=A.H(A.aM(a,"params["+b+"]","Allowed parameters must either be null or bool, int, num, String or List."))}return s}, +by(a){$label0$0:{this.dD(a.a) +break $label0$0}}, +V(){var s,r=this.c +if(!r.d){$.fA().cN(this) +r.V() +s=this.b +if(!s.r)B.b.I(s.c.d,r)}}, +cP(a){var s=this +if(s.c.d)A.H(A.Q(u.n)) +s.al() +s.by(a) +s.dQ()}} +A.eW.prototype={ +gp(){var s=this.x +s===$&&A.aK("current") +return s}, +m(){var s,r,q,p,o,n=this,m=n.r +if(m.c.d||m.f!==n)return!1 +s=m.a +r=s.c +q=s.b +p=A.d(A.p(r.k1.call(null,q))) +if(p===100){if(!n.y){n.w=A.d(A.p(r.fy.call(null,q))) +n.a=t.df.a(m.gbC()) +n.bz() +n.y=!0}s=[] +for(o=0;o=2?1:0}, +bp(){if(this.c)this.a.d.I(0,this.b)}, +bq(){return this.a.d.i(0,this.b).b}, +da(a){this.d=a}, +dd(a){}, +bs(a){var s=this.a.d,r=this.b,q=s.i(0,r) +if(q==null){s.l(0,r,new A.az(new Uint8Array(0),0)) +s.i(0,r).sk(0,a)}else q.sk(0,a)}, +de(a){this.d=a}, +aS(a,b){var s,r=this.a.d,q=this.b,p=r.i(0,q) +if(p==null){p=new A.az(new Uint8Array(0),0) +r.l(0,q,p)}s=b+a.length +if(s>p.b)p.sk(0,s) +p.R(0,b,s,a)}} +A.c_.prototype={ +bz(){var s,r,q,p,o=A.O(t.N,t.S) +for(s=this.a,r=s.length,q=0;q=0&&b>>0!==b||b>=s.length)return A.b(s,b) +return s[b]}return null}r=this.a.c.i(0,b) +if(r==null)return null +s=this.b +if(r>>>0!==r||r>=s.length)return A.b(s,r) +return s[r]}, +gN(){return this.a.a}, +ga8(){return this.b}, +$iI:1} +A.fc.prototype={ +gp(){var s=this.a,r=s.d,q=this.b +if(!(q>=0&&q=g.length){q=A.b(g,1) +s=1 +break}f=A.d(A.p(g[1])) +B.b.n(j,A.ob(new A.fH(h,k,f,Math.min(4096,A.d(l.length)-f)),e)) +s=4 +break +case 5:s=7 +return A.f(A.kv(j,e),$async$ar) +case 7:q=k +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$ar,r)}, +ab(a,b){return this.eh(a,b)}, +eh(a,b){var s=0,r=A.l(t.H),q=this,p,o,n,m,l,k,j,i +var $async$ab=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:i=q.a +i.toString +p=t.m +o=p.a(i.transaction($.kp(),"readwrite")) +n=p.a(o.objectStore("blocks")) +s=2 +return A.f(q.bQ(o,a),$async$ab) +case 2:m=d +i=b.b +l=A.u(i).h("br<1>") +k=A.kB(new A.br(i,l),l.h("e.E")) +B.b.dh(k) +i=A.a0(k) +s=3 +return A.f(A.kv(new A.a5(k,i.h("z<~>(1)").a(new A.fE(new A.fF(n,a),b)),i.h("a5<1,z<~>>")),t.H),$async$ab) +case 3:s=b.c!==A.d(m.length)?4:5 +break +case 4:j=new A.bJ(p.a(p.a(o.objectStore("files")).openCursor(a)),t.R) +s=6 +return A.f(j.m(),$async$ab) +case 6:s=7 +return A.f(A.aD(p.a(j.gp().update({name:A.L(m.name),length:b.c})),t.X),$async$ab) +case 7:case 5:return A.j(null,r)}}) +return A.k($async$ab,r)}, +ah(a,b,c){return this.fp(0,b,c)}, +fp(a,b,c){var s=0,r=A.l(t.H),q=this,p,o,n,m,l,k,j +var $async$ah=A.m(function(d,e){if(d===1)return A.i(e,r) +while(true)switch(s){case 0:j=q.a +j.toString +p=t.m +o=p.a(j.transaction($.kp(),"readwrite")) +n=p.a(o.objectStore("files")) +m=p.a(o.objectStore("blocks")) +s=2 +return A.f(q.bQ(o,b),$async$ah) +case 2:l=e +s=A.d(l.length)>c?3:4 +break +case 3:s=5 +return A.f(A.aD(p.a(m.delete(q.e5(b,B.c.E(c,4096)*4096+1))),t.X),$async$ah) +case 5:case 4:k=new A.bJ(p.a(n.openCursor(b)),t.R) +s=6 +return A.f(k.m(),$async$ah) +case 6:s=7 +return A.f(A.aD(p.a(k.gp().update({name:A.L(l.name),length:c})),t.X),$async$ah) +case 7:return A.j(null,r)}}) +return A.k($async$ah,r)}, +ba(a){return this.eu(a)}, +eu(a){var s=0,r=A.l(t.H),q=this,p,o,n,m +var $async$ba=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:m=q.a +m.toString +p=t.m +o=p.a(m.transaction(A.x(["files","blocks"],t.s),"readwrite")) +n=q.bP(a,9007199254740992,0) +m=t.X +s=2 +return A.f(A.kv(A.x([A.aD(p.a(p.a(o.objectStore("blocks")).delete(n)),m),A.aD(p.a(p.a(o.objectStore("files")).delete(a)),m)],t.W),t.H),$async$ba) +case 2:return A.j(null,r)}}) +return A.k($async$ba,r)}} +A.fG.prototype={ +$1(a){var s,r=t.m +r.a(a) +s=r.a(this.a.result) +if(A.d(a.oldVersion)===0){r.a(r.a(s.createObjectStore("files",{autoIncrement:!0})).createIndex("fileName","name",{unique:!0})) +r.a(s.createObjectStore("blocks"))}}, +$S:9} +A.fD.prototype={ +$1(a){t.A.a(a) +if(a==null)throw A.c(A.aM(this.a,"fileId","File not found in database")) +else return a}, +$S:49} +A.fH.prototype={ +$0(){var s=0,r=A.l(t.H),q=this,p,o +var $async$$0=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:p=q.a +s=A.kx(p.value,"Blob")?2:4 +break +case 2:s=5 +return A.f(A.hg(t.m.a(p.value)),$async$$0) +case 5:s=3 +break +case 4:b=t.o.a(p.value) +case 3:o=b +B.d.ai(q.b,q.c,J.cv(o,0,q.d)) +return A.j(null,r)}}) +return A.k($async$$0,r)}, +$S:2} +A.fF.prototype={ +df(a,b){var s=0,r=A.l(t.H),q=this,p,o,n,m,l,k,j +var $async$$2=A.m(function(c,d){if(c===1)return A.i(d,r) +while(true)switch(s){case 0:p=q.a +o=q.b +n=t.B +m=t.m +s=2 +return A.f(A.aD(m.a(p.openCursor(m.a(v.G.IDBKeyRange.only(A.x([o,a],n))))),t.A),$async$$2) +case 2:l=d +k=t.o.a(B.d.gam(b)) +j=t.X +s=l==null?3:5 +break +case 3:s=6 +return A.f(A.aD(m.a(p.put(k,A.x([o,a],n))),j),$async$$2) +case 6:s=4 +break +case 5:s=7 +return A.f(A.aD(m.a(l.update(k)),j),$async$$2) +case 7:case 4:return A.j(null,r)}}) +return A.k($async$$2,r)}, +$2(a,b){return this.df(a,b)}, +$S:50} +A.fE.prototype={ +$1(a){var s +A.d(a) +s=this.b.b.i(0,a) +s.toString +return this.a.$2(a,s)}, +$S:51} +A.iG.prototype={ +eg(a,b,c){B.d.ai(this.b.fb(a,new A.iH(this,a)),b,c)}, +ej(a,b){var s,r,q,p,o,n,m,l +for(s=b.length,r=0;rp)B.d.ai(s,0,J.cv(B.d.gam(r),r.byteOffset+p,Math.min(4096,q-p))) +return s}, +$S:52} +A.fa.prototype={} +A.c4.prototype={ +aJ(a){var s=this.d.a +if(s==null)A.H(A.eN(10)) +if(a.c1(this.w)){this.cA() +return a.d.a}else return A.lJ(t.H)}, +cA(){var s,r,q,p,o,n,m=this +if(m.f==null&&!m.w.gW(0)){s=m.w +r=m.f=s.gH(0) +s.I(0,r) +s=A.oa(r.gbl(),t.H) +q=t.fO.a(new A.h_(m)) +p=s.$ti +o=$.w +n=new A.v(o,p) +if(o!==B.e)q=o.fg(q,t.z) +s.aV(new A.aY(n,8,q,null,p.h("aY<1,1>"))) +r.d.U(n)}}, +ak(a){return this.dS(a)}, +dS(a){var s=0,r=A.l(t.S),q,p=this,o,n +var $async$ak=A.m(function(b,c){if(b===1)return A.i(c,r) +while(true)switch(s){case 0:n=p.y +s=n.L(a)?3:5 +break +case 3:n=n.i(0,a) +n.toString +q=n +s=1 +break +s=4 +break +case 5:s=6 +return A.f(p.d.bb(a),$async$ak) +case 6:o=c +o.toString +n.l(0,a,o) +q=o +s=1 +break +case 4:case 1:return A.j(q,r)}}) +return A.k($async$ak,r)}, +aH(){var s=0,r=A.l(t.H),q=this,p,o,n,m,l,k,j,i,h,g,f +var $async$aH=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:g=q.d +s=2 +return A.f(g.bg(),$async$aH) +case 2:f=b +q.y.bU(0,f) +p=f.gao(),p=p.gu(p),o=q.r.d,n=t.fQ.h("e") +case 3:if(!p.m()){s=4 +break}m=p.gp() +l=m.a +k=m.b +j=new A.az(new Uint8Array(0),0) +s=5 +return A.f(g.ar(k),$async$aH) +case 5:i=b +m=i.length +j.sk(0,m) +n.a(i) +h=j.b +if(m>h)A.H(A.T(m,0,h,null,null)) +B.d.D(j.a,0,m,i,0) +o.l(0,l,j) +s=3 +break +case 4:return A.j(null,r)}}) +return A.k($async$aH,r)}, +eG(){return this.aJ(new A.ck(t.M.a(new A.h0()),new A.a_(new A.v($.w,t.D),t.F)))}, +bo(a,b){return this.r.d.L(a)?1:0}, +ca(a,b){var s=this +s.r.d.I(0,a) +if(!s.x.I(0,a))s.aJ(new A.cj(s,a,new A.a_(new A.v($.w,t.D),t.F)))}, +d9(a){return $.lt().cZ("/"+a)}, +aR(a,b){var s,r,q,p=this,o=a.a +if(o==null)o=A.lK(p.b,"/") +s=p.r +r=s.d.L(o)?1:0 +q=s.aR(new A.cd(o),b) +if(r===0)if((b&8)!==0)p.x.n(0,o) +else p.aJ(new A.bI(p,o,new A.a_(new A.v($.w,t.D),t.F))) +return new A.cl(new A.f5(p,q.a,o),0)}, +dc(a){}} +A.h_.prototype={ +$0(){var s=this.a +s.f=null +s.cA()}, +$S:4} +A.h0.prototype={ +$0(){}, +$S:4} +A.f5.prototype={ +br(a,b){this.b.br(a,b)}, +gd8(){return 0}, +d7(){return this.b.d>=2?1:0}, +bp(){}, +bq(){return this.b.bq()}, +da(a){this.b.d=a +return null}, +dd(a){}, +bs(a){var s=this,r=s.a,q=r.d.a +if(q==null)A.H(A.eN(10)) +s.b.bs(a) +if(!r.x.G(0,s.c))r.aJ(new A.ck(t.M.a(new A.iT(s,a)),new A.a_(new A.v($.w,t.D),t.F)))}, +de(a){this.b.d=a +return null}, +aS(a,b){var s,r,q,p,o,n=this,m=n.a,l=m.d.a +if(l==null)A.H(A.eN(10)) +l=n.c +if(m.x.G(0,l)){n.b.aS(a,b) +return}s=m.r.d.i(0,l) +if(s==null)s=new A.az(new Uint8Array(0),0) +r=J.cv(B.d.gam(s.a),0,s.b) +n.b.aS(a,b) +q=new Uint8Array(a.length) +B.d.ai(q,0,a) +p=A.x([],t.gQ) +o=$.w +B.b.n(p,new A.fa(b,q)) +m.aJ(new A.bQ(m,l,r,p,new A.a_(new A.v(o,t.D),t.F)))}, +$ieO:1} +A.iT.prototype={ +$0(){var s=0,r=A.l(t.H),q,p=this,o,n,m +var $async$$0=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:o=p.a +n=o.a +m=n.d +s=3 +return A.f(n.ak(o.c),$async$$0) +case 3:q=m.ah(0,b,p.b) +s=1 +break +case 1:return A.j(q,r)}}) +return A.k($async$$0,r)}, +$S:2} +A.Z.prototype={ +c1(a){t.h.a(a) +a.$ti.c.a(this) +a.bM(a.c,this,!1) +return!0}} +A.ck.prototype={ +A(){return this.w.$0()}} +A.cj.prototype={ +c1(a){var s,r,q,p +t.h.a(a) +if(!a.gW(0)){s=a.ga2(0) +for(r=this.x;s!=null;)if(s instanceof A.cj)if(s.x===r)return!1 +else s=s.gaO() +else if(s instanceof A.bQ){q=s.gaO() +if(s.x===r){p=s.a +p.toString +p.bS(A.u(s).h("a4.E").a(s))}s=q}else if(s instanceof A.bI){if(s.x===r){r=s.a +r.toString +r.bS(A.u(s).h("a4.E").a(s)) +return!1}s=s.gaO()}else break}a.$ti.c.a(this) +a.bM(a.c,this,!1) +return!0}, +A(){var s=0,r=A.l(t.H),q=this,p,o,n +var $async$A=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:p=q.w +o=q.x +s=2 +return A.f(p.ak(o),$async$A) +case 2:n=b +p.y.I(0,o) +s=3 +return A.f(p.d.ba(n),$async$A) +case 3:return A.j(null,r)}}) +return A.k($async$A,r)}} +A.bI.prototype={ +A(){var s=0,r=A.l(t.H),q=this,p,o,n,m +var $async$A=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:p=q.w +o=q.x +n=p.y +m=o +s=2 +return A.f(p.d.b6(o),$async$A) +case 2:n.l(0,m,b) +return A.j(null,r)}}) +return A.k($async$A,r)}} +A.bQ.prototype={ +c1(a){var s,r +t.h.a(a) +s=a.b===0?null:a.ga2(0) +for(r=this.x;s!=null;)if(s instanceof A.bQ)if(s.x===r){B.b.bU(s.z,this.z) +return!1}else s=s.gaO() +else if(s instanceof A.bI){if(s.x===r)break +s=s.gaO()}else break +a.$ti.c.a(this) +a.bM(a.c,this,!1) +return!0}, +A(){var s=0,r=A.l(t.H),q=this,p,o,n,m,l,k +var $async$A=A.m(function(a,b){if(a===1)return A.i(b,r) +while(true)switch(s){case 0:m=q.y +l=new A.iG(m,A.O(t.S,t.p),m.length) +for(m=q.z,p=m.length,o=0;oq.c)throw A.c(A.eN(14)) +s=A.aR(t.o.a(q.d.buffer),0,null) +r=q.e +B.d.ai(s,r,p) +o=r+o +s.$flags&2&&A.y(s) +if(!(o>=0&&o864e13)A.H(A.T(s,-864e13,864e13,"millisecondsSinceEpoch",null)) +A.k3(!1,"isUtc",t.y) +r=new A.bk(s,0,!1) +q=A.oy(t.o.a(this.a.buffer),b,8) +q.$flags&2&&A.y(q) +p=q.length +if(0>=p)return A.b(q,0) +q[0]=A.m_(r) +if(1>=p)return A.b(q,1) +q[1]=A.lY(r) +if(2>=p)return A.b(q,2) +q[2]=A.lX(r) +if(3>=p)return A.b(q,3) +q[3]=A.lW(r) +if(4>=p)return A.b(q,4) +q[4]=A.lZ(r)-1 +if(5>=p)return A.b(q,5) +q[5]=A.m0(r)-1900 +o=B.c.Y(A.oD(r),7) +if(6>=p)return A.b(q,6) +q[6]=o}, +$S:63} +A.fS.prototype={ +seV(a){this.r=t.aY.a(a)}, +seT(a){this.w=t.g_.a(a)}, +seU(a){this.x=t.g5.a(a)}} +A.dT.prototype={ +aD(a,b,c){return this.dr(c.h("0/()").a(a),b,c,c)}, +a0(a,b){a.toString +return this.aD(a,null,b)}, +dr(a,b,c,d){var s=0,r=A.l(d),q,p=2,o=[],n=[],m=this,l,k,j,i,h +var $async$aD=A.m(function(e,f){if(e===1){o.push(f) +s=p}while(true)switch(s){case 0:i=m.a +h=new A.a_(new A.v($.w,t.D),t.F) +m.a=h.a +p=3 +s=i!=null?6:7 +break +case 6:s=8 +return A.f(i,$async$aD) +case 8:case 7:l=a.$0() +s=l instanceof A.v?9:11 +break +case 9:j=l +s=12 +return A.f(c.h("z<0>").b(j)?j:A.mp(c.a(j),c),$async$aD) +case 12:j=f +q=j +n=[1] +s=4 +break +s=10 +break +case 11:q=l +n=[1] +s=4 +break +case 10:n.push(5) +s=4 +break +case 3:n=[2] +case 4:p=2 +k=new A.fJ(m,h) +k.$0() +s=n.pop() +break +case 5:case 1:return A.j(q,r) +case 2:return A.i(o.at(-1),r)}}) +return A.k($async$aD,r)}, +j(a){return"Lock["+A.lm(this)+"]"}, +$iov:1} +A.fJ.prototype={ +$0(){var s=this.a,r=this.b +if(s.a===r.a)s.a=null +r.en()}, +$S:0} +A.aG.prototype={ +gk(a){return this.b}, +i(a,b){var s +if(b>=this.b)throw A.c(A.lL(b,this)) +s=this.a +if(!(b>=0&&b=s.b)throw A.c(A.lL(b,s)) +B.d.l(s.a,b,c)}, +sk(a,b){var s,r,q,p,o=this,n=o.b +if(b=0&&qn){if(n===0)p=new Uint8Array(b) +else p=o.dK(b) +B.d.R(p,0,o.b,o.a) +o.a=p}}o.b=b}, +dK(a){var s=this.a.length*2 +if(a!=null&&s").a(d) +s=this.b +if(c>s)throw A.c(A.T(c,0,s,null,null)) +s=this.a +if(d instanceof A.az)B.d.D(s,b,c,d.a,e) +else B.d.D(s,b,c,d,e)}, +R(a,b,c,d){return this.D(0,b,c,d,0)}} +A.f6.prototype={} +A.az.prototype={} +A.ku.prototype={} +A.iD.prototype={} +A.df.prototype={ +ac(){var s=this,r=A.lJ(t.H) +if(s.b==null)return r +s.ef() +s.d=s.b=null +return r}, +ee(){var s=this,r=s.d +if(r!=null&&s.a<=0)s.b.addEventListener(s.c,r,!1)}, +ef(){var s=this.d +if(s!=null)this.b.removeEventListener(this.c,s,!1)}, +$ipj:1} +A.iE.prototype={ +$1(a){return this.a.$1(t.m.a(a))}, +$S:3};(function aliases(){var s=J.b8.prototype +s.dn=s.j +s=A.r.prototype +s.cd=s.D +s=A.e2.prototype +s.dm=s.j +s=A.ey.prototype +s.dq=s.j})();(function installTearOffs(){var s=hunkHelpers._static_2,r=hunkHelpers._static_1,q=hunkHelpers._static_0,p=hunkHelpers._instance_0u +s(J,"qu","om",64) +r(A,"qU","px",10) +r(A,"qV","py",10) +r(A,"qW","pz",10) +q(A,"nf","qM",0) +r(A,"qZ","pr",44) +p(A.ck.prototype,"gbl","A",0) +p(A.cj.prototype,"gbl","A",2) +p(A.bI.prototype,"gbl","A",2) +p(A.bQ.prototype,"gbl","A",2)})();(function inheritance(){var s=hunkHelpers.mixin,r=hunkHelpers.inherit,q=hunkHelpers.inheritMany +r(A.q,null) +q(A.q,[A.ky,J.ed,J.cx,A.e,A.cy,A.D,A.b5,A.J,A.r,A.hh,A.bs,A.cT,A.bF,A.d1,A.cD,A.da,A.bp,A.af,A.bc,A.be,A.cB,A.dg,A.i8,A.h9,A.cE,A.ds,A.h3,A.cO,A.cP,A.cN,A.cJ,A.dl,A.eY,A.d6,A.fn,A.iy,A.fp,A.ay,A.f3,A.jJ,A.jH,A.db,A.dt,A.X,A.ci,A.aY,A.v,A.eZ,A.eE,A.fl,A.dD,A.cc,A.f8,A.bN,A.di,A.a4,A.dk,A.dz,A.bZ,A.e1,A.jN,A.dC,A.R,A.f2,A.bk,A.b6,A.iC,A.eq,A.d5,A.iF,A.fW,A.ec,A.K,A.F,A.fo,A.ac,A.dA,A.ia,A.fi,A.e6,A.h8,A.f7,A.ep,A.eJ,A.e0,A.i7,A.ha,A.e2,A.fU,A.e7,A.c2,A.hx,A.hy,A.d3,A.fj,A.fb,A.an,A.hk,A.cn,A.i0,A.d4,A.by,A.eu,A.eC,A.ev,A.hf,A.cZ,A.hd,A.he,A.aN,A.e3,A.i3,A.dY,A.c_,A.bD,A.dR,A.fg,A.fc,A.bq,A.d8,A.cd,A.bJ,A.eR,A.fC,A.iG,A.fa,A.f5,A.eP,A.iU,A.fS,A.dT,A.ku,A.df]) +q(J.ed,[J.ee,J.cI,J.cK,J.ag,J.c7,J.c6,J.b7]) +q(J.cK,[J.b8,J.E,A.ca,A.cV]) +q(J.b8,[J.er,J.bC,J.aO]) +r(J.h1,J.E) +q(J.c6,[J.cH,J.ef]) +q(A.e,[A.bd,A.n,A.aQ,A.io,A.aT,A.d9,A.bo,A.bM,A.eX,A.fm,A.cm,A.c8]) +q(A.bd,[A.bj,A.dE]) +r(A.de,A.bj) +r(A.dd,A.dE) +r(A.ae,A.dd) +q(A.D,[A.cz,A.cg,A.aP]) +q(A.b5,[A.dX,A.fK,A.dW,A.eG,A.k9,A.kb,A.ir,A.iq,A.jR,A.fY,A.iR,A.i5,A.jG,A.h5,A.ix,A.km,A.kn,A.fR,A.k_,A.k2,A.hj,A.hp,A.ho,A.hm,A.hn,A.hY,A.hE,A.hQ,A.hP,A.hK,A.hM,A.hS,A.hG,A.jX,A.kj,A.kg,A.kk,A.i4,A.k6,A.iA,A.iB,A.fM,A.fN,A.fO,A.fP,A.fQ,A.fG,A.fD,A.fE,A.j9,A.ja,A.jb,A.jm,A.jv,A.jw,A.jz,A.jA,A.jB,A.jc,A.jj,A.jk,A.jl,A.jn,A.jo,A.jp,A.jq,A.jr,A.js,A.jt,A.iE]) +q(A.dX,[A.fL,A.h2,A.ka,A.jS,A.k0,A.fZ,A.iS,A.h4,A.h7,A.iw,A.ib,A.ic,A.id,A.jP,A.jU,A.jT,A.i2,A.ij,A.ii,A.fF,A.jx,A.jy,A.jd,A.je,A.jf,A.jg,A.jh,A.ji,A.ju]) +q(A.J,[A.cL,A.aV,A.eg,A.eI,A.ex,A.f1,A.dN,A.aw,A.d7,A.eH,A.bz,A.e_]) +q(A.r,[A.cf,A.ch,A.aG]) +r(A.cA,A.cf) +q(A.n,[A.Y,A.bm,A.br,A.cQ,A.cM,A.dj]) +q(A.Y,[A.bA,A.a5,A.f9,A.d0]) +r(A.bl,A.aQ) +r(A.c1,A.aT) +r(A.c0,A.bo) +r(A.cR,A.cg) +r(A.bP,A.be) +q(A.bP,[A.bf,A.cl]) +r(A.cC,A.cB) +r(A.cX,A.aV) +q(A.eG,[A.eD,A.bY]) +q(A.cV,[A.cU,A.a6]) +q(A.a6,[A.dm,A.dp]) +r(A.dn,A.dm) +r(A.b9,A.dn) +r(A.dq,A.dp) +r(A.am,A.dq) +q(A.b9,[A.ei,A.ej]) +q(A.am,[A.ek,A.el,A.em,A.en,A.eo,A.cW,A.bu]) +r(A.du,A.f1) +q(A.dW,[A.is,A.it,A.jI,A.fX,A.iI,A.iN,A.iM,A.iK,A.iJ,A.iQ,A.iP,A.iO,A.i6,A.jZ,A.jF,A.jE,A.jM,A.jL,A.hi,A.hs,A.hq,A.hl,A.ht,A.hw,A.hv,A.hu,A.hr,A.hC,A.hB,A.hN,A.hH,A.hO,A.hL,A.hJ,A.hI,A.hR,A.hT,A.ki,A.kf,A.kh,A.fT,A.fH,A.iH,A.h_,A.h0,A.iT,A.j0,A.j_,A.iZ,A.iY,A.j8,A.j7,A.j6,A.j5,A.j4,A.j3,A.j2,A.j1,A.iX,A.iW,A.iV,A.fJ]) +q(A.ci,[A.bH,A.a_]) +r(A.ff,A.dD) +r(A.dr,A.cc) +r(A.dh,A.dr) +q(A.bZ,[A.dQ,A.e5]) +q(A.e1,[A.fI,A.ie]) +r(A.eM,A.e5) +q(A.aw,[A.cb,A.cF]) +r(A.f0,A.dA) +r(A.c5,A.i7) +q(A.c5,[A.es,A.eL,A.eV]) +r(A.ey,A.e2) +r(A.aU,A.ey) +r(A.fk,A.hx) +r(A.hz,A.fk) +r(A.aA,A.cn) +r(A.eB,A.d4) +q(A.aN,[A.e8,A.c3]) +r(A.ce,A.dY) +q(A.c_,[A.cG,A.fd]) +r(A.eW,A.cG) +r(A.dS,A.bD) +q(A.dS,[A.e9,A.c4]) +r(A.f4,A.dR) +r(A.fe,A.fd) +r(A.ew,A.fe) +r(A.fh,A.fg) +r(A.ab,A.fh) +r(A.cY,A.iC) +r(A.eT,A.eu) +r(A.eQ,A.ev) +r(A.im,A.hf) +r(A.eU,A.cZ) +r(A.bE,A.hd) +r(A.aX,A.he) +r(A.eS,A.i3) +r(A.Z,A.a4) +q(A.Z,[A.ck,A.cj,A.bI,A.bQ]) +r(A.f6,A.aG) +r(A.az,A.f6) +r(A.iD,A.eE) +s(A.cf,A.bc) +s(A.dE,A.r) +s(A.dm,A.r) +s(A.dn,A.af) +s(A.dp,A.r) +s(A.dq,A.af) +s(A.cg,A.dz) +s(A.fk,A.hy) +s(A.fd,A.r) +s(A.fe,A.ep) +s(A.fg,A.eJ) +s(A.fh,A.D)})() +var v={G:typeof self!="undefined"?self:globalThis,typeUniverse:{eC:new Map(),tR:{},eT:{},tPV:{},sEA:[]},mangledGlobalNames:{a:"int",B:"double",ak:"num",h:"String",aB:"bool",F:"Null",t:"List",q:"Object",I:"Map"},mangledNames:{},types:["~()","a(a,a)","z<~>()","~(C)","F()","z<@>()","F(a)","~(@)","~(@,@)","F(C)","~(~())","a(a)","z<@>(an)","F(a,a,a)","a(a,a,a)","a(a,a,a,ag)","F(@)","z()","z()","z>()","@()","a(a,a,a,a,a)","a(a,a,a,a)","aU(@)","@(h)","~(h,a)","z()","z()","~(h,a?)","F(@,aF)","I(aU)","~(@[@])","@(@,h)","a?()","I<@,@>(a)","~(I<@,@>)","~(a,@)","z(an)","z(an)","z(an)","z()","~(c2)","~(q,aF)","K(a,aA)","h(h)","~(aN)","aB(h)","~(h,I)","h(h?)","C(C?)","z<~>(a,bB)","z<~>(a)","bB()","F(~())","h?(q?)","h(q?)","@(@)","F(a,a)","a?(h)","a(a,ag)","~(q?,q?)","F(a,a,a,a,ag)","a?(a)","F(ag,a)","a(@,@)","~(h,q?)","F(q,aF)"],interceptorsByTag:null,leafTags:null,arrayRti:Symbol("$ti"),rttc:{"2;":(a,b)=>c=>c instanceof A.bf&&a.b(c.a)&&b.b(c.b),"2;file,outFlags":(a,b)=>c=>c instanceof A.cl&&a.b(c.a)&&b.b(c.b)}} +A.pV(v.typeUniverse,JSON.parse('{"aO":"b8","er":"b8","bC":"b8","E":{"t":["1"],"n":["1"],"C":[],"e":["1"]},"ee":{"aB":[],"G":[]},"cI":{"F":[],"G":[]},"cK":{"C":[]},"b8":{"C":[]},"h1":{"E":["1"],"t":["1"],"n":["1"],"C":[],"e":["1"]},"cx":{"A":["1"]},"c6":{"B":[],"ak":[],"a8":["ak"]},"cH":{"B":[],"a":[],"ak":[],"a8":["ak"],"G":[]},"ef":{"B":[],"ak":[],"a8":["ak"],"G":[]},"b7":{"h":[],"a8":["h"],"hb":[],"G":[]},"bd":{"e":["2"]},"cy":{"A":["2"]},"bj":{"bd":["1","2"],"e":["2"],"e.E":"2"},"de":{"bj":["1","2"],"bd":["1","2"],"n":["2"],"e":["2"],"e.E":"2"},"dd":{"r":["2"],"t":["2"],"bd":["1","2"],"n":["2"],"e":["2"]},"ae":{"dd":["1","2"],"r":["2"],"t":["2"],"bd":["1","2"],"n":["2"],"e":["2"],"r.E":"2","e.E":"2"},"cz":{"D":["3","4"],"I":["3","4"],"D.K":"3","D.V":"4"},"cL":{"J":[]},"cA":{"r":["a"],"bc":["a"],"t":["a"],"n":["a"],"e":["a"],"r.E":"a","bc.E":"a"},"n":{"e":["1"]},"Y":{"n":["1"],"e":["1"]},"bA":{"Y":["1"],"n":["1"],"e":["1"],"Y.E":"1","e.E":"1"},"bs":{"A":["1"]},"aQ":{"e":["2"],"e.E":"2"},"bl":{"aQ":["1","2"],"n":["2"],"e":["2"],"e.E":"2"},"cT":{"A":["2"]},"a5":{"Y":["2"],"n":["2"],"e":["2"],"Y.E":"2","e.E":"2"},"io":{"e":["1"],"e.E":"1"},"bF":{"A":["1"]},"aT":{"e":["1"],"e.E":"1"},"c1":{"aT":["1"],"n":["1"],"e":["1"],"e.E":"1"},"d1":{"A":["1"]},"bm":{"n":["1"],"e":["1"],"e.E":"1"},"cD":{"A":["1"]},"d9":{"e":["1"],"e.E":"1"},"da":{"A":["1"]},"bo":{"e":["+(a,1)"],"e.E":"+(a,1)"},"c0":{"bo":["1"],"n":["+(a,1)"],"e":["+(a,1)"],"e.E":"+(a,1)"},"bp":{"A":["+(a,1)"]},"cf":{"r":["1"],"bc":["1"],"t":["1"],"n":["1"],"e":["1"]},"f9":{"Y":["a"],"n":["a"],"e":["a"],"Y.E":"a","e.E":"a"},"cR":{"D":["a","1"],"dz":["a","1"],"I":["a","1"],"D.K":"a","D.V":"1"},"d0":{"Y":["1"],"n":["1"],"e":["1"],"Y.E":"1","e.E":"1"},"bf":{"bP":[],"be":[]},"cl":{"bP":[],"be":[]},"cB":{"I":["1","2"]},"cC":{"cB":["1","2"],"I":["1","2"]},"bM":{"e":["1"],"e.E":"1"},"dg":{"A":["1"]},"cX":{"aV":[],"J":[]},"eg":{"J":[]},"eI":{"J":[]},"ds":{"aF":[]},"b5":{"bn":[]},"dW":{"bn":[]},"dX":{"bn":[]},"eG":{"bn":[]},"eD":{"bn":[]},"bY":{"bn":[]},"ex":{"J":[]},"aP":{"D":["1","2"],"lS":["1","2"],"I":["1","2"],"D.K":"1","D.V":"2"},"br":{"n":["1"],"e":["1"],"e.E":"1"},"cO":{"A":["1"]},"cQ":{"n":["1"],"e":["1"],"e.E":"1"},"cP":{"A":["1"]},"cM":{"n":["K<1,2>"],"e":["K<1,2>"],"e.E":"K<1,2>"},"cN":{"A":["K<1,2>"]},"bP":{"be":[]},"cJ":{"oI":[],"hb":[]},"dl":{"d_":[],"c9":[]},"eX":{"e":["d_"],"e.E":"d_"},"eY":{"A":["d_"]},"d6":{"c9":[]},"fm":{"e":["c9"],"e.E":"c9"},"fn":{"A":["c9"]},"ca":{"C":[],"dU":[],"G":[]},"cV":{"C":[]},"fp":{"dU":[]},"cU":{"lE":[],"C":[],"G":[]},"a6":{"al":["1"],"C":[]},"b9":{"r":["B"],"a6":["B"],"t":["B"],"al":["B"],"n":["B"],"C":[],"e":["B"],"af":["B"]},"am":{"r":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"]},"ei":{"b9":[],"r":["B"],"M":["B"],"a6":["B"],"t":["B"],"al":["B"],"n":["B"],"C":[],"e":["B"],"af":["B"],"G":[],"r.E":"B"},"ej":{"b9":[],"r":["B"],"M":["B"],"a6":["B"],"t":["B"],"al":["B"],"n":["B"],"C":[],"e":["B"],"af":["B"],"G":[],"r.E":"B"},"ek":{"am":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"el":{"am":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"em":{"am":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"en":{"am":[],"kU":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"eo":{"am":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"cW":{"am":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"bu":{"am":[],"bB":[],"r":["a"],"M":["a"],"a6":["a"],"t":["a"],"al":["a"],"n":["a"],"C":[],"e":["a"],"af":["a"],"G":[],"r.E":"a"},"f1":{"J":[]},"du":{"aV":[],"J":[]},"db":{"dZ":["1"]},"dt":{"A":["1"]},"cm":{"e":["1"],"e.E":"1"},"X":{"J":[]},"ci":{"dZ":["1"]},"bH":{"ci":["1"],"dZ":["1"]},"a_":{"ci":["1"],"dZ":["1"]},"v":{"z":["1"]},"dD":{"ip":[]},"ff":{"dD":[],"ip":[]},"dh":{"cc":["1"],"kH":["1"],"n":["1"],"e":["1"]},"bN":{"A":["1"]},"c8":{"e":["1"],"e.E":"1"},"di":{"A":["1"]},"r":{"t":["1"],"n":["1"],"e":["1"]},"D":{"I":["1","2"]},"cg":{"D":["1","2"],"dz":["1","2"],"I":["1","2"]},"dj":{"n":["2"],"e":["2"],"e.E":"2"},"dk":{"A":["2"]},"cc":{"kH":["1"],"n":["1"],"e":["1"]},"dr":{"cc":["1"],"kH":["1"],"n":["1"],"e":["1"]},"dQ":{"bZ":["t","h"]},"e5":{"bZ":["h","t"]},"eM":{"bZ":["h","t"]},"bX":{"a8":["bX"]},"bk":{"a8":["bk"]},"B":{"ak":[],"a8":["ak"]},"b6":{"a8":["b6"]},"a":{"ak":[],"a8":["ak"]},"t":{"n":["1"],"e":["1"]},"ak":{"a8":["ak"]},"d_":{"c9":[]},"h":{"a8":["h"],"hb":[]},"R":{"bX":[],"a8":["bX"]},"dN":{"J":[]},"aV":{"J":[]},"aw":{"J":[]},"cb":{"J":[]},"cF":{"J":[]},"d7":{"J":[]},"eH":{"J":[]},"bz":{"J":[]},"e_":{"J":[]},"eq":{"J":[]},"d5":{"J":[]},"ec":{"J":[]},"fo":{"aF":[]},"ac":{"pk":[]},"dA":{"eK":[]},"fi":{"eK":[]},"f0":{"eK":[]},"f7":{"oF":[]},"es":{"c5":[]},"eL":{"c5":[]},"eV":{"c5":[]},"aA":{"cn":["bX"],"cn.T":"bX"},"eB":{"d4":[]},"e8":{"aN":[]},"e3":{"lG":[]},"c3":{"aN":[]},"ce":{"dY":[]},"eW":{"cG":[],"c_":[],"A":["ab"]},"e9":{"bD":[]},"f4":{"eO":[]},"ab":{"eJ":["h","@"],"D":["h","@"],"I":["h","@"],"D.K":"h","D.V":"@"},"cG":{"c_":[],"A":["ab"]},"ew":{"r":["ab"],"ep":["ab"],"t":["ab"],"n":["ab"],"c_":[],"e":["ab"],"r.E":"ab"},"fc":{"A":["ab"]},"bq":{"pi":[]},"dS":{"bD":[]},"dR":{"eO":[]},"eT":{"eu":[]},"eQ":{"ev":[]},"eU":{"cZ":[]},"ch":{"r":["aX"],"t":["aX"],"n":["aX"],"e":["aX"],"r.E":"aX"},"c4":{"bD":[]},"Z":{"a4":["Z"]},"f5":{"eO":[]},"ck":{"Z":[],"a4":["Z"],"a4.E":"Z"},"cj":{"Z":[],"a4":["Z"],"a4.E":"Z"},"bI":{"Z":[],"a4":["Z"],"a4.E":"Z"},"bQ":{"Z":[],"a4":["Z"],"a4.E":"Z"},"dT":{"ov":[]},"az":{"aG":["a"],"r":["a"],"t":["a"],"n":["a"],"e":["a"],"r.E":"a","aG.E":"a"},"aG":{"r":["1"],"t":["1"],"n":["1"],"e":["1"]},"f6":{"aG":["a"],"r":["a"],"t":["a"],"n":["a"],"e":["a"]},"iD":{"eE":["1"]},"df":{"pj":["1"]},"oi":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"bB":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"pp":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"og":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"kU":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"oh":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"po":{"M":["a"],"t":["a"],"n":["a"],"e":["a"]},"o8":{"M":["B"],"t":["B"],"n":["B"],"e":["B"]},"o9":{"M":["B"],"t":["B"],"n":["B"],"e":["B"]}}')) +A.pU(v.typeUniverse,JSON.parse('{"cf":1,"dE":2,"a6":1,"cg":2,"dr":1,"e1":2,"nW":1}')) +var u={f:"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\u03f6\x00\u0404\u03f4 \u03f4\u03f6\u01f6\u01f6\u03f6\u03fc\u01f4\u03ff\u03ff\u0584\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u05d4\u01f4\x00\u01f4\x00\u0504\u05c4\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u0400\x00\u0400\u0200\u03f7\u0200\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u03ff\u0200\u0200\u0200\u03f7\x00",c:"Error handler must accept one Object or one Object and a StackTrace as arguments, and return a value of the returned future's type",n:"Tried to operate on a released prepared statement"} +var t=(function rtii(){var s=A.b0 +return{b9:s("nW"),n:s("X"),dG:s("bX"),dI:s("dU"),gs:s("lG"),e8:s("a8<@>"),dy:s("bk"),fu:s("b6"),O:s("n<@>"),Q:s("J"),u:s("aN"),Z:s("bn"),gJ:s("z<@>()"),bd:s("c4"),cs:s("e"),bM:s("e"),hf:s("e<@>"),hb:s("e"),eV:s("E"),W:s("E>"),G:s("E>"),aX:s("E>"),eK:s("E"),bb:s("E"),s:s("E"),gQ:s("E"),bi:s("E"),B:s("E"),b:s("E<@>"),t:s("E"),c:s("E"),d4:s("E"),T:s("cI"),m:s("C"),C:s("ag"),g:s("aO"),aU:s("al<@>"),h:s("c8"),k:s("t"),Y:s("t"),df:s("t"),j:s("t<@>"),L:s("t"),ee:s("t"),dA:s("K"),dY:s("I"),g6:s("I"),f:s("I<@,@>"),f6:s("I>"),a:s("I"),do:s("a5"),o:s("ca"),aS:s("b9"),eB:s("am"),bm:s("bu"),P:s("F"),K:s("q"),gT:s("rw"),bQ:s("+()"),cz:s("d_"),gy:s("rx"),bJ:s("d0"),fI:s("ab"),e:s("d4"),gR:s("eC"),l:s("aF"),N:s("h"),dm:s("G"),bV:s("aV"),fQ:s("az"),p:s("bB"),ak:s("bC"),dD:s("eK"),fL:s("bD"),cG:s("eO"),h2:s("eP"),g9:s("eR"),ab:s("eS"),gV:s("aX"),eJ:s("d9"),x:s("ip"),ez:s("bH<~>"),J:s("aA"),cl:s("R"),R:s("bJ"),et:s("v"),ek:s("v"),_:s("v<@>"),fJ:s("v"),D:s("v<~>"),aT:s("fj"),eC:s("a_"),fa:s("a_"),F:s("a_<~>"),y:s("aB"),al:s("aB(q)"),i:s("B"),z:s("@"),fO:s("@()"),v:s("@(q)"),U:s("@(q,aF)"),dO:s("@(h)"),S:s("a"),eH:s("z?"),A:s("C?"),bE:s("t<@>?"),gq:s("t?"),fn:s("I?"),X:s("q?"),dk:s("h?"),fN:s("az?"),E:s("ip?"),q:s("rN?"),d:s("aY<@,@>?"),V:s("f8?"),a6:s("aB?"),cD:s("B?"),I:s("a?"),g_:s("a()?"),cg:s("ak?"),g5:s("~()?"),w:s("~(C)?"),aY:s("~(a,h,a)?"),r:s("ak"),H:s("~"),M:s("~()")}})();(function constants(){var s=hunkHelpers.makeConstList +B.E=J.ed.prototype +B.b=J.E.prototype +B.c=J.cH.prototype +B.F=J.c6.prototype +B.a=J.b7.prototype +B.G=J.aO.prototype +B.H=J.cK.prototype +B.J=A.cU.prototype +B.d=A.bu.prototype +B.t=J.er.prototype +B.k=J.bC.prototype +B.a_=new A.fI() +B.u=new A.dQ() +B.v=new A.cD(A.b0("cD<0&>")) +B.w=new A.ec() +B.m=function getTagFallback(o) { + var s = Object.prototype.toString.call(o); + return s.substring(8, s.length - 1); +} +B.x=function() { + var toStringFunction = Object.prototype.toString; + function getTag(o) { + var s = toStringFunction.call(o); + return s.substring(8, s.length - 1); + } + function getUnknownTag(object, tag) { + if (/^HTML[A-Z].*Element$/.test(tag)) { + var name = toStringFunction.call(object); + if (name == "[object Object]") return null; + return "HTMLElement"; + } + } + function getUnknownTagGenericBrowser(object, tag) { + if (object instanceof HTMLElement) return "HTMLElement"; + return getUnknownTag(object, tag); + } + function prototypeForTag(tag) { + if (typeof window == "undefined") return null; + if (typeof window[tag] == "undefined") return null; + var constructor = window[tag]; + if (typeof constructor != "function") return null; + return constructor.prototype; + } + function discriminator(tag) { return null; } + var isBrowser = typeof HTMLElement == "function"; + return { + getTag: getTag, + getUnknownTag: isBrowser ? getUnknownTagGenericBrowser : getUnknownTag, + prototypeForTag: prototypeForTag, + discriminator: discriminator }; +} +B.C=function(getTagFallback) { + return function(hooks) { + if (typeof navigator != "object") return hooks; + var userAgent = navigator.userAgent; + if (typeof userAgent != "string") return hooks; + if (userAgent.indexOf("DumpRenderTree") >= 0) return hooks; + if (userAgent.indexOf("Chrome") >= 0) { + function confirm(p) { + return typeof window == "object" && window[p] && window[p].name == p; + } + if (confirm("Window") && confirm("HTMLElement")) return hooks; + } + hooks.getTag = getTagFallback; + }; +} +B.y=function(hooks) { + if (typeof dartExperimentalFixupGetTag != "function") return hooks; + hooks.getTag = dartExperimentalFixupGetTag(hooks.getTag); +} +B.B=function(hooks) { + if (typeof navigator != "object") return hooks; + var userAgent = navigator.userAgent; + if (typeof userAgent != "string") return hooks; + if (userAgent.indexOf("Firefox") == -1) return hooks; + var getTag = hooks.getTag; + var quickMap = { + "BeforeUnloadEvent": "Event", + "DataTransfer": "Clipboard", + "GeoGeolocation": "Geolocation", + "Location": "!Location", + "WorkerMessageEvent": "MessageEvent", + "XMLDocument": "!Document"}; + function getTagFirefox(o) { + var tag = getTag(o); + return quickMap[tag] || tag; + } + hooks.getTag = getTagFirefox; +} +B.A=function(hooks) { + if (typeof navigator != "object") return hooks; + var userAgent = navigator.userAgent; + if (typeof userAgent != "string") return hooks; + if (userAgent.indexOf("Trident/") == -1) return hooks; + var getTag = hooks.getTag; + var quickMap = { + "BeforeUnloadEvent": "Event", + "DataTransfer": "Clipboard", + "HTMLDDElement": "HTMLElement", + "HTMLDTElement": "HTMLElement", + "HTMLPhraseElement": "HTMLElement", + "Position": "Geoposition" + }; + function getTagIE(o) { + var tag = getTag(o); + var newTag = quickMap[tag]; + if (newTag) return newTag; + if (tag == "Object") { + if (window.DataView && (o instanceof window.DataView)) return "DataView"; + } + return tag; + } + function prototypeForTagIE(tag) { + var constructor = window[tag]; + if (constructor == null) return null; + return constructor.prototype; + } + hooks.getTag = getTagIE; + hooks.prototypeForTag = prototypeForTagIE; +} +B.z=function(hooks) { + var getTag = hooks.getTag; + var prototypeForTag = hooks.prototypeForTag; + function getTagFixed(o) { + var tag = getTag(o); + if (tag == "Document") { + if (!!o.xmlVersion) return "!Document"; + return "!HTMLDocument"; + } + return tag; + } + function prototypeForTagFixed(tag) { + if (tag == "Document") return null; + return prototypeForTag(tag); + } + hooks.getTag = getTagFixed; + hooks.prototypeForTag = prototypeForTagFixed; +} +B.l=function(hooks) { return hooks; } + +B.D=new A.eq() +B.h=new A.hh() +B.i=new A.eM() +B.f=new A.ie() +B.e=new A.ff() +B.j=new A.fo() +B.n=new A.b6(0) +B.I=A.x(s([]),t.s) +B.o=A.x(s([]),t.c) +B.K={} +B.p=new A.cC(B.K,[],A.b0("cC")) +B.q=new A.cY("readOnly") +B.L=new A.cY("readWrite") +B.r=new A.cY("readWriteCreate") +B.M=A.av("dU") +B.N=A.av("lE") +B.O=A.av("o8") +B.P=A.av("o9") +B.Q=A.av("og") +B.R=A.av("oh") +B.S=A.av("oi") +B.T=A.av("C") +B.U=A.av("q") +B.V=A.av("kU") +B.W=A.av("po") +B.X=A.av("pp") +B.Y=A.av("bB") +B.Z=new A.d8(522)})();(function staticFields(){$.jC=null +$.ar=A.x([],A.b0("E")) +$.nm=null +$.lV=null +$.lC=null +$.lB=null +$.ni=null +$.nd=null +$.nn=null +$.k5=null +$.kd=null +$.lj=null +$.jD=A.x([],A.b0("E?>")) +$.cq=null +$.dH=null +$.dI=null +$.lc=!1 +$.w=B.e +$.mj=null +$.mk=null +$.ml=null +$.mm=null +$.kY=A.iz("_lastQuoRemDigits") +$.kZ=A.iz("_lastQuoRemUsed") +$.dc=A.iz("_lastRemUsed") +$.l_=A.iz("_lastRem_nsh") +$.md="" +$.me=null +$.nc=null +$.n3=null +$.ng=A.O(t.S,A.b0("an")) +$.fv=A.O(t.dk,A.b0("an")) +$.n4=0 +$.ke=0 +$.ad=null +$.np=A.O(t.N,t.X) +$.nb=null +$.dJ="/shw2"})();(function lazyInitializers(){var s=hunkHelpers.lazyFinal,r=hunkHelpers.lazy +s($,"rt","cu",()=>A.r7("_$dart_dartClosure")) +s($,"rD","nv",()=>A.aW(A.i9({ +toString:function(){return"$receiver$"}}))) +s($,"rE","nw",()=>A.aW(A.i9({$method$:null, +toString:function(){return"$receiver$"}}))) +s($,"rF","nx",()=>A.aW(A.i9(null))) +s($,"rG","ny",()=>A.aW(function(){var $argumentsExpr$="$arguments$" +try{null.$method$($argumentsExpr$)}catch(q){return q.message}}())) +s($,"rJ","nB",()=>A.aW(A.i9(void 0))) +s($,"rK","nC",()=>A.aW(function(){var $argumentsExpr$="$arguments$" +try{(void 0).$method$($argumentsExpr$)}catch(q){return q.message}}())) +s($,"rI","nA",()=>A.aW(A.ma(null))) +s($,"rH","nz",()=>A.aW(function(){try{null.$method$}catch(q){return q.message}}())) +s($,"rM","nE",()=>A.aW(A.ma(void 0))) +s($,"rL","nD",()=>A.aW(function(){try{(void 0).$method$}catch(q){return q.message}}())) +s($,"rO","lo",()=>A.pw()) +s($,"rY","nK",()=>A.oz(4096)) +s($,"rW","nI",()=>new A.jM().$0()) +s($,"rX","nJ",()=>new A.jL().$0()) +s($,"rP","nF",()=>new Int8Array(A.ql(A.x([-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-2,-2,-2,-2,-2,62,-2,62,-2,63,52,53,54,55,56,57,58,59,60,61,-2,-2,-2,-1,-2,-2,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-2,-2,-2,-2,63,-2,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-2,-2,-2,-2,-2],t.t)))) +s($,"rU","b2",()=>A.iu(0)) +s($,"rT","fz",()=>A.iu(1)) +s($,"rR","lq",()=>$.fz().a3(0)) +s($,"rQ","lp",()=>A.iu(1e4)) +r($,"rS","nG",()=>A.ax("^\\s*([+-]?)((0x[a-f0-9]+)|(\\d+)|([a-z0-9]+))\\s*$",!1)) +s($,"rV","nH",()=>typeof FinalizationRegistry=="function"?FinalizationRegistry:null) +s($,"t2","ks",()=>A.lm(B.U)) +s($,"rv","ns",()=>{var q=new A.f7(new DataView(new ArrayBuffer(A.qi(8)))) +q.dw() +return q}) +s($,"t8","lt",()=>{var q=$.kr() +return new A.e0(q)}) +s($,"t5","ls",()=>new A.e0($.nt())) +s($,"rA","nu",()=>new A.es(A.ax("/",!0),A.ax("[^/]$",!0),A.ax("^/",!0))) +s($,"rC","fy",()=>new A.eV(A.ax("[/\\\\]",!0),A.ax("[^/\\\\]$",!0),A.ax("^(\\\\\\\\[^\\\\]+\\\\[^\\\\/]+|[a-zA-Z]:[/\\\\])",!0),A.ax("^[/\\\\](?![/\\\\])",!0))) +s($,"rB","kr",()=>new A.eL(A.ax("/",!0),A.ax("(^[a-zA-Z][-+.a-zA-Z\\d]*://|[^/])$",!0),A.ax("[a-zA-Z][-+.a-zA-Z\\d]*://[^/]*",!0),A.ax("^/",!0))) +s($,"rz","nt",()=>A.pm()) +s($,"t1","nN",()=>A.kD()) +r($,"rZ","lr",()=>A.x([new A.aA("BigInt")],A.b0("E"))) +r($,"t_","nL",()=>{var q=$.lr() +return A.ot(q,A.a0(q).c).f3(0,new A.jP(),t.N,t.J)}) +r($,"t0","nM",()=>A.mf("sqlite3.wasm")) +s($,"t4","nP",()=>A.lz("-9223372036854775808")) +s($,"t3","nO",()=>A.lz("9223372036854775807")) +s($,"t7","fA",()=>{var q=$.nH() +q=q==null?null:new q(A.bS(A.rq(new A.k6(),t.u),1)) +return new A.f2(q,A.b0("f2"))}) +s($,"rs","kq",()=>$.ns()) +s($,"rr","kp",()=>A.ou(A.x(["files","blocks"],t.s),t.N)) +s($,"ru","nr",()=>new A.e6(new WeakMap(),A.b0("e6")))})();(function nativeSupport(){!function(){var s=function(a){var m={} +m[a]=1 +return Object.keys(hunkHelpers.convertToFastObject(m))[0]} +v.getIsolateTag=function(a){return s("___dart_"+a+v.isolateTag)} +var r="___dart_isolate_tags_" +var q=Object[r]||(Object[r]=Object.create(null)) +var p="_ZxYxX" +for(var o=0;;o++){var n=s(p+"_"+o+"_") +if(!(n in q)){q[n]=1 +v.isolateTag=n +break}}v.dispatchPropertyName=v.getIsolateTag("dispatch_record")}() +hunkHelpers.setOrUpdateInterceptorsByTag({ArrayBuffer:A.ca,ArrayBufferView:A.cV,DataView:A.cU,Float32Array:A.ei,Float64Array:A.ej,Int16Array:A.ek,Int32Array:A.el,Int8Array:A.em,Uint16Array:A.en,Uint32Array:A.eo,Uint8ClampedArray:A.cW,CanvasPixelArray:A.cW,Uint8Array:A.bu}) +hunkHelpers.setOrUpdateLeafTags({ArrayBuffer:true,ArrayBufferView:false,DataView:true,Float32Array:true,Float64Array:true,Int16Array:true,Int32Array:true,Int8Array:true,Uint16Array:true,Uint32Array:true,Uint8ClampedArray:true,CanvasPixelArray:true,Uint8Array:false}) +A.a6.$nativeSuperclassTag="ArrayBufferView" +A.dm.$nativeSuperclassTag="ArrayBufferView" +A.dn.$nativeSuperclassTag="ArrayBufferView" +A.b9.$nativeSuperclassTag="ArrayBufferView" +A.dp.$nativeSuperclassTag="ArrayBufferView" +A.dq.$nativeSuperclassTag="ArrayBufferView" +A.am.$nativeSuperclassTag="ArrayBufferView"})() +Function.prototype.$1=function(a){return this(a)} +Function.prototype.$2=function(a,b){return this(a,b)} +Function.prototype.$0=function(){return this()} +Function.prototype.$1$1=function(a){return this(a)} +Function.prototype.$3$1=function(a){return this(a)} +Function.prototype.$2$1=function(a){return this(a)} +Function.prototype.$3=function(a,b,c){return this(a,b,c)} +Function.prototype.$4=function(a,b,c,d){return this(a,b,c,d)} +Function.prototype.$3$3=function(a,b,c){return this(a,b,c)} +Function.prototype.$2$2=function(a,b){return this(a,b)} +Function.prototype.$1$0=function(){return this()} +Function.prototype.$5=function(a,b,c,d,e){return this(a,b,c,d,e)} +convertAllToFastObject(w) +convertToFastObject($);(function(a){if(typeof document==="undefined"){a(null) +return}if(typeof document.currentScript!="undefined"){a(document.currentScript) +return}var s=document.scripts +function onLoad(b){for(var q=0;q:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) + +# Install SQLite3 DLL +find_file(SQLITE3_DLL + NAMES "sqlite3.dll" + PATHS + "${CMAKE_CURRENT_SOURCE_DIR}" + DOC "Path to SQLite3 DLL" +) + +if(SQLITE3_DLL) + install(FILES "${SQLITE3_DLL}" + DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + message(STATUS "Found SQLite3 DLL at: ${SQLITE3_DLL}") +else() + message(WARNING "sqlite3.dll not found. The application may not work correctly.") +endif() diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..1f7a531 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,26 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterInappwebviewWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterInappwebviewWindowsPluginCApi")); + ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi")); + SharePlusWindowsPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); + WindowManagerPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("WindowManagerPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..5f2b33f --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,28 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_inappwebview_windows + screen_retriever_windows + share_plus + url_launcher_windows + window_manager +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/packaging/exe/make_config.yaml b/windows/packaging/exe/make_config.yaml new file mode 100644 index 0000000..37c4518 --- /dev/null +++ b/windows/packaging/exe/make_config.yaml @@ -0,0 +1,16 @@ +# AppId 的值唯一标识此应用。 +# 不要在其他应用的安装程序中使用相同的 AppId 值。 +app_id: f2821c52-2345-4ef6-99f2-b22c561359e6 +publisher: YourName +publisher_url: https://github.com/yourusername/chatmcp +display_name: ChatMCP +create_desktop_icon: true +# 这里的路径是相对于项目根目录的路径;图标格式必须是ico格式,不能是png或其它 +setup_icon_file: windows/runner/resources/app_icon.ico +locales: + - en + - zh +# 添加额外文件配置 +extra_files: + - source: "windows/sqlite3.dll" + destination: "." \ No newline at end of file diff --git a/windows/packaging/msix/make_config.yaml b/windows/packaging/msix/make_config.yaml new file mode 100644 index 0000000..64de65c --- /dev/null +++ b/windows/packaging/msix/make_config.yaml @@ -0,0 +1,3 @@ +display_name: ChatMCP +msix_version: 1.0.0.0 +# logo_path: C:\path\to\logo.png \ No newline at end of file diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..96e61cb --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "run.daodao" "\0" + VALUE "FileDescription", "chatmcp" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "chatmcp" "\0" + VALUE "LegalCopyright", "Copyright (C) 2024 run.daodao. All rights reserved." "\0" + VALUE "OriginalFilename", "chatmcp.exe" "\0" + VALUE "ProductName", "chatmcp" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..966ffdd --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"chatmcp", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..e73f4fd Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/windows/sqlite3.dll b/windows/sqlite3.dll new file mode 100644 index 0000000..ad8714f Binary files /dev/null and b/windows/sqlite3.dll differ