[
  {
    "path": ".github/workflows/build.yaml",
    "content": "name: Build and Release\n\non:\n  push:\n    tags:\n      - \"v*\"\n\npermissions:\n  contents: write\n\njobs:\n  build-apk:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Clone repository\n        uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n\n      - name: Setup JDK17\n        uses: actions/setup-java@v4\n        with:\n          distribution: \"zulu\"\n          java-version: \"17\"\n\n      - name: Setup Flutter\n        uses: subosito/flutter-action@v2\n        with:\n          flutter-version: 3.24.5\n\n      - name: Setup signing\n        run: |\n          echo \"${{ secrets.KEYSTORE_BASE64 }}\" | base64 --decode > android/app/keystore.jks\n          echo \"storePassword=${{ secrets.KEYSTORE_PASSWORD }}\" > android/key.properties\n          echo \"keyPassword=${{ secrets.KEY_PASSWORD }}\" >> android/key.properties\n          echo \"keyAlias=${{ secrets.KEY_ALIAS }}\" >> android/key.properties\n          echo \"storeFile=keystore.jks\" >> android/key.properties\n\n      - name: Build\n        run: |\n          flutter pub get\n          flutter build apk --split-per-abi\n\n      - name: ChangeLog\n        id: changelog\n        run: |\n          echo \"latest<<EOF\" >> $GITHUB_OUTPUT\n          awk '/^[0-9]/{i++}i==1' CHANGELOG | sed '${/^$/d}' >> $GITHUB_OUTPUT\n          echo \"EOF\" >> $GITHUB_OUTPUT\n\n      - name: Release\n        uses: softprops/action-gh-release@v2\n        with:\n          files: |\n            build/app/outputs/flutter-apk/app-arm64-v8a-release.apk\n            build/app/outputs/flutter-apk/app-arm64-v8a-release.apk.sha1\n            build/app/outputs/flutter-apk/app-x86_64-release.apk\n            build/app/outputs/flutter-apk/app-x86_64-release.apk.sha1\n          body: ${{ steps.changelog.outputs.latest }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Miscellaneous\n*.log\n*.pyc\n*.swp\n*.class\n.history\n.DS_Store\n.svn/\n.atom/\n.buildlog/\nmigrate_working_dir/\n\n# IntelliJ related\n*.iml\n*.ipr\n*.iws\n.idea/\n\n\n# Flutter/Dart/Pub related\n**/doc/api/\n**/ios/Flutter/.last_build_id\n.flutter-plugins\ndevtools_options.yaml\n.flutter-plugins-dependencies\n.pub/\n/build/\n.pub-cache/\n.dart_tool/\n\n# Obfuscation related\napp.*.map.json\n\n# Symbolication related\napp.*.symbols\n\n# Android Studio related\n/android/app/debug\n/android/app/profile\n/android/app/release\n"
  },
  {
    "path": ".metadata",
    "content": "# This file tracks properties of this Flutter project.\n# Used by Flutter tool to assess capabilities and perform upgrades etc.\n#\n# This file should be version controlled and should not be manually edited.\n\nversion:\n  revision: \"dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\"\n  channel: \"stable\"\n\nproject_type: app\n\n# Tracks metadata for the flutter migrate command\nmigration:\n  platforms:\n    - platform: root\n      create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n      base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n    - platform: linux\n      create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n      base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n    - platform: windows\n      create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n      base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668\n\n  # User provided section\n\n  # List of Local paths (relative to this file) that should be\n  # ignored by the migrate tool.\n  #\n  # Files that are not part of the templates will be ignored by default.\n  unmanaged_files:\n    - 'lib/main.dart'\n    - 'ios/Runner.xcodeproj/project.pbxproj'\n"
  },
  {
    "path": "CHANGELOG",
    "content": "0.3.5 (2025-01-10)\n\n    * Add: General Web Search.\n    * Improve: Additional page details.\n\n    * 增加：通用联网搜索\n    * 改进：更多页面细节\n\n0.3.4 (2025-01-02)\n\n    * Improve: Chat Settings.\n    * Improve: Model Settings.\n    * Add: Data Clearing.\n\n    * 改进：对话设置页面\n    * 改进：模型设置功能\n    * 增加：清除数据功能\n\n0.3.3 (2024-12-27)\n\n    * Improve: Chat Settings Page.\n    * Improve: Input Widget.\n\n    * 改进：对话设置页面\n    * 改进：输入组件\n\n0.3.2 (2024-12-25)\n\n    * Add: Title Generation.\n    * Improve: Input Widget.\n    * Fix: Google Gemini API proxy not working.\n\n    * 增加：标题生成\n    * 改进：输入组件\n    * 修复：Google Gemini 接口代理无效。\n\n0.3.1 (2024-12-17)\n\n    * Add: Workspace.\n    * Improve: Input Widget.\n\n    * 增加：工作空间\n    * 改进：输入组件\n\n0.2.10 (2024-12-13)\n\n    * Add: Checking for updates.\n    * Improve: Images display.\n\n    * 增加：检查更新\n    * 改进：图片显示\n\n0.2.9 (2024-12-13)\n\n    * Add: Google Search support (gemini-2.0-flash-exp only)\n    * Add: Support for sending multiple images.\n\n    * 增加：支持 GoogleSearch（仅 gemini-2.0-flash-exp）\n    * 增加：支持发送多张图片\n\n0.2.8 (2024-12-09)\n\n    * Add: Support Google Gemini API.\n    * Improve: Chat Response.\n\n    * 增加：支持 Google Gemini 接口\n    * 改进：对话响应\n\n0.2.7 (2024-12-06)\n\n    * Add: Export chat as image.\n    * Improve: Refine UI details.\n\n    * 增加：将对话导出为图片\n    * 改进：调整了界面细节\n\n0.2.6 (2024-12-04)\n\n    * Improve: LaTeX Rendering.\n\n    * 改进：LaTeX 渲染\n\n0.2.5 (2024-12-04)\n\n    * Add: Image Generation.\n    * Improve: Message List.\n    * Improve: Configuration Loading and Export.\n\n    * 增加：图像生成\n    * 改进：消息列表\n    * 改进：配置加载及导出\n\n0.2.4 (2024-11-29)\n\n    * Add: Image compression controls.\n    * Improve: Redesigned settings page.\n\n    * 增加：图片压缩控制\n    * 改进：重新设计的设置页\n\n0.2.3 (2024-11-27)\n\n    * Add: A new app icon.\n    * Improve: Remove unnecessary animations.\n\n    * 增加：新的应用图标\n    * 改进：删除不必要的动画\n\n0.2.2 (2024-11-25)\n\n    * Add: Chat clone and clear functionality.\n    * Improve: More animations.\n\n    * 增加：对话复制和清空\n    * 改进：更多动画\n\n0.2.1 (2024-11-23)\n\n    * Improve: The Reanswering can be stopped.\n\n    * 改进：可以终止重新回答\n\n0.2.0 (2024-11-23)\n\n    * Add: Reanswer.\n    * Improve: TTS button.\n\n    * 增加：重新回答\n    * 改进：文本转语音按钮\n\n0.1.11 (2024-11-22)\n\n    * Add: More informative error messages.\n    * Improve: Style of the Message Widget.\n\n    * 增加：更多错误提示\n    * 改进：消息卡片组件样式\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README",
    "content": "This project is no longer maintained.\n\nChatBot is licensed under the GNU General Public License v3.0 - see the COPYING file for details.\n"
  },
  {
    "path": "analysis_options.yaml",
    "content": "include: package:flutter_lints/flutter.yaml\n\nlinter:\n  rules:\n\nanalyzer:\n  plugins:\n"
  },
  {
    "path": "android/.gitignore",
    "content": "gradle-wrapper.jar\n/.gradle\n/captures/\n/gradlew\n/gradlew.bat\n/local.properties\nGeneratedPluginRegistrant.java\n\n# Remember to never publicly share your keystore.\n# See https://flutter.dev/to/reference-keystore\nkey.properties\n**/*.keystore\n**/*.jks\n"
  },
  {
    "path": "android/app/build.gradle",
    "content": "plugins {\n    id \"kotlin-android\"\n    id \"com.android.application\"\n    id \"dev.flutter.flutter-gradle-plugin\"\n}\n\ndef keystoreProperties = new Properties()\ndef keystorePropertiesFile = rootProject.file(\"key.properties\")\nif (keystorePropertiesFile.exists()) {\n    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))\n}\n\nandroid {\n    namespace = \"cc.arthur63.chatbot\"\n    compileSdk = flutter.compileSdkVersion\n\n    compileOptions {\n        sourceCompatibility = JavaVersion.VERSION_17\n        targetCompatibility = JavaVersion.VERSION_17\n    }\n\n    kotlinOptions {\n        jvmTarget = JavaVersion.VERSION_17\n    }\n\n    defaultConfig {\n        minSdk = flutter.minSdkVersion\n        versionCode = flutter.versionCode\n        versionName = flutter.versionName\n        targetSdk = flutter.targetSdkVersion\n        applicationId = \"cc.arthur63.chatbot\"\n    }\n\n    signingConfigs {\n        release {\n            keyAlias keystoreProperties[\"keyAlias\"]\n            keyPassword keystoreProperties[\"keyPassword\"]\n            storePassword keystoreProperties[\"storePassword\"]\n            storeFile keystoreProperties[\"storeFile\"] ? file(keystoreProperties[\"storeFile\"]) : null\n        }\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled true\n            shrinkResources true\n            signingConfig signingConfigs.release\n        }\n    }\n}\n\nflutter {\n    source = \"../..\"\n}\n"
  },
  {
    "path": "android/app/src/debug/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <uses-permission android:name=\"android.permission.INTERNET\"/>\n</manifest>\n"
  },
  {
    "path": "android/app/src/main/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <application\n        android:label=\"ChatBot\"\n        android:name=\"${applicationName}\"\n        android:icon=\"@mipmap/ic_launcher\">\n        <activity\n            android:taskAffinity=\"\"\n            android:exported=\"true\"\n            android:name=\".MainActivity\"\n            android:launchMode=\"singleTop\"\n            android:theme=\"@style/LaunchTheme\"\n            android:hardwareAccelerated=\"true\"\n            android:windowSoftInputMode=\"adjustResize\"\n            android:configChanges=\"orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode\">\n            <meta-data\n                android:name=\"io.flutter.embedding.android.NormalTheme\"\n                android:resource=\"@style/NormalTheme\"/>\n            <intent-filter>\n                <category android:name=\"android.intent.category.LAUNCHER\"/>\n                <action android:name=\"android.intent.action.MAIN\"/>\n            </intent-filter>\n            <intent-filter>\n                <category android:name=\"android.intent.category.BROWSABLE\"/>\n                <category android:name=\"android.intent.category.DEFAULT\"/>\n                <action android:name=\"android.intent.action.VIEW\"/>\n                <data android:scheme=\"https\"/>\n            </intent-filter>\n            <intent-filter>\n                <category android:name=\"android.intent.category.BROWSABLE\"/>\n                <category android:name=\"android.intent.category.DEFAULT\"/>\n                <action android:name=\"android.intent.action.VIEW\"/>\n                <data android:scheme=\"http\"/>\n            </intent-filter>\n        </activity>\n        <meta-data\n            android:name=\"flutterEmbedding\"\n            android:value=\"2\"/>\n    </application>\n\n    <queries>\n        <intent>\n            <category android:name=\"android.intent.category.BROWSABLE\"/>\n            <action android:name=\"android.intent.action.VIEW\"/>\n            <data android:scheme=\"https\"/>\n        </intent>\n        <intent>\n            <category android:name=\"android.intent.category.BROWSABLE\"/>\n            <action android:name=\"android.intent.action.VIEW\"/>\n            <data android:scheme=\"http\"/>\n        </intent>\n    </queries>\n\n    <uses-permission android:name=\"android.permission.INTERNET\"/>\n</manifest>\n"
  },
  {
    "path": "android/app/src/main/kotlin/cc/arthur63/chatbot/MainActivity.kt",
    "content": "package cc.arthur63.chatbot\n\nimport io.flutter.embedding.android.FlutterActivity\n\nclass MainActivity: FlutterActivity()\n"
  },
  {
    "path": "android/app/src/main/res/drawable-v21/launch_background.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <item android:drawable=\"?android:colorBackground\" />\n</layer-list>\n"
  },
  {
    "path": "android/app/src/main/res/values/styles.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <style name=\"LaunchTheme\" parent=\"@android:style/Theme.Light.NoTitleBar\">\n        <item name=\"android:windowBackground\">@drawable/launch_background</item>\n    </style>\n\n    <style name=\"NormalTheme\" parent=\"@android:style/Theme.Light.NoTitleBar\">\n        <item name=\"android:windowBackground\">?android:colorBackground</item>\n    </style>\n</resources>\n"
  },
  {
    "path": "android/app/src/main/res/values-night/styles.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <style name=\"LaunchTheme\" parent=\"@android:style/Theme.Black.NoTitleBar\">\n        <item name=\"android:windowBackground\">@drawable/launch_background</item>\n    </style>\n\n    <style name=\"NormalTheme\" parent=\"@android:style/Theme.Black.NoTitleBar\">\n        <item name=\"android:windowBackground\">?android:colorBackground</item>\n    </style>\n</resources>\n"
  },
  {
    "path": "android/app/src/profile/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <uses-permission android:name=\"android.permission.INTERNET\"/>\n</manifest>\n"
  },
  {
    "path": "android/build.gradle",
    "content": "allprojects {\n    repositories {\n        google()\n        mavenCentral()\n    }\n}\n\nrootProject.buildDir = \"../build\"\n\nsubprojects {\n    project.buildDir = \"${rootProject.buildDir}/${project.name}\"\n}\n\nsubprojects {\n    project.evaluationDependsOn(\":app\")\n}\n\ntasks.register(\"clean\", Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "android/gradle/wrapper/gradle-wrapper.properties",
    "content": "zipStorePath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionBase=GRADLE_USER_HOME\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.4-all.zip\n"
  },
  {
    "path": "android/gradle.properties",
    "content": "android.useAndroidX=true\nandroid.enableJetifier=true\norg.gradle.daemon=false\norg.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G\n"
  },
  {
    "path": "android/settings.gradle",
    "content": "pluginManagement {\n    def flutterSdkPath = {\n        def properties = new Properties()\n        file(\"local.properties\").withInputStream { properties.load(it) }\n        def flutterSdkPath = properties.getProperty(\"flutter.sdk\")\n        assert flutterSdkPath != null, \"flutter.sdk not set in local.properties\"\n        return flutterSdkPath\n    }()\n\n    includeBuild(\"$flutterSdkPath/packages/flutter_tools/gradle\")\n\n    repositories {\n        google()\n        mavenCentral()\n        gradlePluginPortal()\n    }\n}\n\nplugins {\n    id \"dev.flutter.flutter-plugin-loader\" version \"1.0.0\"\n    id \"com.android.application\" version \"8.3.2\" apply false\n    id \"org.jetbrains.kotlin.android\" version \"1.8.22\" apply false\n}\n\ninclude \":app\"\n"
  },
  {
    "path": "lib/chat/chat.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"input.dart\";\nimport \"message.dart\";\nimport \"current.dart\";\nimport \"settings.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../settings/api.dart\";\n\nimport \"dart:io\";\nimport \"package:flutter/material.dart\";\nimport \"package:screenshot/screenshot.dart\";\nimport \"package:animate_do/animate_do.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nfinal chatProvider =\n    NotifierProvider.autoDispose<ChatNotifier, void>(ChatNotifier.new);\n\nfinal chatsProvider =\n    NotifierProvider.autoDispose<ChatsNotifier, void>(ChatsNotifier.new);\n\nfinal messagesProvider =\n    NotifierProvider.autoDispose<MessagesNotifier, void>(MessagesNotifier.new);\n\nclass ChatNotifier extends AutoDisposeNotifier<void> {\n  @override\n  void build() => ref.listen(apisProvider, (p, n) => notify());\n  void notify() => ref.notifyListeners();\n}\n\nclass ChatsNotifier extends AutoDisposeNotifier<void> {\n  @override\n  void build() {}\n  void notify() => ref.notifyListeners();\n}\n\nclass MessagesNotifier extends AutoDisposeNotifier<void> {\n  @override\n  void build() {}\n  void notify() => ref.notifyListeners();\n}\n\nclass ChatPage extends ConsumerStatefulWidget {\n  const ChatPage({super.key});\n\n  @override\n  ConsumerState<ChatPage> createState() => _ChatPageState();\n}\n\nclass _ChatPageState extends ConsumerState<ChatPage> {\n  final List<ChatConfig> _chats = Config.chats;\n  final List<Message> _messages = Current.messages;\n  final ScrollController _scrollCtrl = ScrollController();\n\n  @override\n  void initState() {\n    super.initState();\n\n    WidgetsBinding.instance.addPostFrameCallback((_) {\n      Util.checkUpdate(context: context, notify: false);\n    });\n\n    _scrollCtrl.addListener(() {\n      final show = ref.read(_toBottomProvider);\n      if (_scrollCtrl.position.pixels < 200) {\n        if (show) ref.read(_toBottomProvider.notifier).hide();\n      } else {\n        if (!show) ref.read(_toBottomProvider.notifier).show();\n      }\n    });\n  }\n\n  @override\n  void dispose() {\n    _scrollCtrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: _buildAppBar(),\n      drawer: Drawer(\n        shape: const RoundedRectangleBorder(\n          borderRadius: BorderRadius.zero,\n        ),\n        child: SafeArea(child: _buildDrawer()),\n      ),\n      body: _buildBody(),\n    );\n  }\n\n  AppBar _buildAppBar() {\n    return AppBar(\n      title: Row(\n        children: [\n          Flexible(\n            child: Consumer(\n              builder: (context, ref, child) {\n                ref.watch(chatProvider);\n                final id = Current.model;\n                final config = Config.models[id];\n\n                return Column(\n                  crossAxisAlignment: CrossAxisAlignment.start,\n                  children: [\n                    Text(\n                      Current.title ?? S.of(context).new_chat,\n                      maxLines: 1,\n                      overflow: TextOverflow.ellipsis,\n                      style: Theme.of(context).textTheme.titleMedium,\n                    ),\n                    Text(\n                      config?.name ?? id ?? S.of(context).no_model,\n                      overflow: TextOverflow.ellipsis,\n                      style: Theme.of(context).textTheme.labelSmall,\n                    )\n                  ],\n                );\n              },\n            ),\n          ),\n          const SizedBox(width: 8),\n          SizedBox.square(\n            dimension: 32,\n            child: IconButton(\n              icon: const Icon(Icons.edit, size: 16),\n              padding: EdgeInsets.zero,\n              onPressed: () {\n                InputWidget.unFocus();\n                showModalBottomSheet(\n                  context: context,\n                  useSafeArea: true,\n                  isScrollControlled: true,\n                  builder: (context) => Padding(\n                    padding: EdgeInsets.only(\n                      bottom: MediaQuery.of(context).viewInsets.bottom,\n                    ),\n                    child: ChatSettings(),\n                  ),\n                );\n              },\n            ),\n          ),\n        ],\n      ),\n      leading: Builder(\n        builder: (context) => IconButton(\n          icon: const Icon(Icons.menu),\n          onPressed: () {\n            InputWidget.unFocus();\n            Scaffold.of(context).openDrawer();\n          },\n        ),\n      ),\n      actions: [\n        PopupMenuButton(\n          icon: const Icon(Icons.more_horiz),\n          shape: const RoundedRectangleBorder(\n            borderRadius: BorderRadius.all(Radius.circular(8)),\n          ),\n          onOpened: () => InputWidget.unFocus(),\n          color: Theme.of(context).colorScheme.surfaceContainerLow,\n          itemBuilder: (context) => <PopupMenuItem>[\n            PopupMenuItem(\n              padding: EdgeInsets.zero,\n              child: ListTile(\n                contentPadding:\n                    const EdgeInsets.symmetric(horizontal: 16, vertical: 0),\n                leading: const Icon(Icons.file_copy, size: 20),\n                title: Text(S.of(context).clone_chat),\n                minTileHeight: 0,\n              ),\n              onTap: () {\n                InputWidget.unFocus();\n                if (!Current.hasChat) return;\n\n                Current.newChat(Current.title!);\n                Current.save();\n\n                Util.showSnackBar(\n                  context: context,\n                  content: Text(S.of(context).cloned_successfully),\n                );\n                ref.read(chatsProvider.notifier).notify();\n              },\n            ),\n            PopupMenuItem(\n              padding: EdgeInsets.zero,\n              child: ListTile(\n                contentPadding:\n                    const EdgeInsets.symmetric(horizontal: 16, vertical: 0),\n                leading: const Icon(Icons.delete, size: 24),\n                title: Text(S.of(context).clear_chat),\n                minTileHeight: 0,\n              ),\n              onTap: () async {\n                InputWidget.unFocus();\n                if (_messages.isEmpty) return;\n\n                final result = await showDialog<bool>(\n                  context: context,\n                  builder: (context) => AlertDialog(\n                    title: Text(S.of(context).clear_chat),\n                    content: Text(S.of(context).ensure_clear_chat),\n                    actions: [\n                      TextButton(\n                        onPressed: Navigator.of(context).pop,\n                        child: Text(S.of(context).cancel),\n                      ),\n                      TextButton(\n                        onPressed: () => Navigator.of(context).pop(true),\n                        child: Text(S.of(context).clear),\n                      ),\n                    ],\n                  ),\n                );\n                if (!(result ?? false)) return;\n\n                _messages.clear();\n                Current.save();\n\n                ref.read(messagesProvider.notifier).notify();\n              },\n            ),\n            PopupMenuItem(\n              height: 1,\n              padding: EdgeInsets.zero,\n              child: const Divider(height: 1),\n            ),\n            PopupMenuItem(\n              padding: EdgeInsets.zero,\n              onTap: _exportChatAsImage,\n              child: ListTile(\n                contentPadding:\n                    const EdgeInsets.symmetric(horizontal: 16, vertical: 0),\n                leading: const Icon(Icons.photo_library, size: 20),\n                title: Text(S.of(context).export_chat_as_image),\n                minTileHeight: 0,\n              ),\n            ),\n          ],\n        ),\n      ],\n    );\n  }\n\n  Widget _buildDrawer() {\n    return Column(\n      children: [\n        ListTile(\n          title: Text(\n            \"ChatBot\",\n            style: Theme.of(context).textTheme.titleLarge,\n          ),\n          trailing: IconButton(\n            icon: const Icon(Icons.settings),\n            onPressed: () => Navigator.of(context).pushNamed(\"/settings\"),\n          ),\n          contentPadding: const EdgeInsets.only(left: 16, right: 8),\n        ),\n        Divider(),\n        ListView(\n          shrinkWrap: true,\n          padding: EdgeInsets.only(left: 8, right: 8),\n          children: [\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).new_chat),\n              leading: const Icon(Icons.article_outlined),\n              onTap: () {\n                if (Current.chatStatus.isResponding) return;\n                Current.clear();\n                ref.read(chatProvider.notifier).notify();\n                ref.read(chatsProvider.notifier).notify();\n                ref.read(messagesProvider.notifier).notify();\n              },\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).workspace),\n              leading: const Icon(Icons.workspaces_outlined),\n              onTap: () => Navigator.of(context).pushNamed(\"/workspace\"),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).image_generation),\n              leading: const Icon(Icons.image_outlined),\n              onTap: () => Navigator.of(context).pushNamed(\"/image\"),\n            ),\n          ],\n        ),\n        Container(\n          alignment: Alignment.topLeft,\n          padding: const EdgeInsets.only(left: 16, top: 8, bottom: 4),\n          child: Text(\n            S.of(context).all_chats,\n            style: Theme.of(context).textTheme.labelSmall,\n          ),\n        ),\n        Expanded(\n          child: Consumer(\n            builder: (context, ref, child) {\n              ref.watch(chatsProvider);\n\n              return ListView.builder(\n                itemCount: _chats.length,\n                itemBuilder: (context, index) => _buildChatItem(index),\n                padding: EdgeInsets.only(left: 8, right: 8, bottom: 8),\n              );\n            },\n          ),\n        ),\n      ],\n    );\n  }\n\n  Widget _buildChatItem(int index) {\n    final chat = _chats[index];\n\n    return Container(\n      margin: EdgeInsets.only(top: 4),\n      child: ListTile(\n        dense: true,\n        minTileHeight: 48,\n        shape: const StadiumBorder(),\n        leading: const Icon(Icons.article),\n        selected: Current.chat == chat,\n        contentPadding: const EdgeInsets.only(left: 16, right: 8),\n        title: Text(\n          chat.title,\n          maxLines: 1,\n          softWrap: false,\n          overflow: TextOverflow.ellipsis,\n        ),\n        subtitle: Text(chat.time),\n        onTap: () async {\n          if (Current.chat == chat) return;\n\n          Current.chat = chat;\n          ref.read(chatsProvider.notifier).notify();\n\n          await Current.load(chat);\n          ref.read(chatProvider.notifier).notify();\n          ref.read(messagesProvider.notifier).notify();\n        },\n        trailing: IconButton(\n          icon: const Icon(Icons.delete),\n          onPressed: () {\n            _chats.removeAt(index);\n            ref.read(chatsProvider.notifier).notify();\n\n            Config.save();\n            File(Config.chatFilePath(chat.fileName)).delete();\n\n            if (Current.chat == chat) {\n              Current.clear();\n              ref.read(chatProvider.notifier).notify();\n              ref.read(messagesProvider.notifier).notify();\n            }\n          },\n        ),\n      ),\n    );\n  }\n\n  Widget _buildBody() {\n    return Column(\n      children: [\n        Expanded(\n          child: Stack(\n            alignment: Alignment.topCenter,\n            children: [\n              Consumer(\n                builder: (context, ref, child) {\n                  ref.watch(messagesProvider);\n\n                  final length = _messages.length;\n                  return ListView.separated(\n                    reverse: true,\n                    shrinkWrap: true,\n                    controller: _scrollCtrl,\n                    padding: const EdgeInsets.all(16),\n                    separatorBuilder: (context, index) =>\n                        const SizedBox(height: 16),\n                    itemCount: length,\n                    itemBuilder: (context, index) {\n                      final message = _messages[length - index - 1];\n                      return MessageWidget(\n                        key: ValueKey(message),\n                        message: message,\n                      );\n                    },\n                  );\n                },\n              ),\n              Positioned(\n                bottom: 8,\n                child: Consumer(\n                  builder: (context, ref, child) {\n                    final show = ref.watch(_toBottomProvider);\n\n                    final child = ElevatedButton(\n                      style: ElevatedButton.styleFrom(\n                        elevation: 2,\n                        shape: const CircleBorder(),\n                        padding: const EdgeInsets.all(8),\n                      ),\n                      onPressed: () => _scrollCtrl.jumpTo(0),\n                      child: Icon(Icons.arrow_downward_rounded, size: 20),\n                    );\n\n                    return show ? ZoomIn(child: child) : ZoomOut(child: child);\n                  },\n                ),\n              ),\n            ],\n          ),\n        ),\n        Padding(\n          padding: const EdgeInsets.only(top: 0, left: 8, right: 8, bottom: 8),\n          child: const InputWidget(),\n        ),\n      ],\n    );\n  }\n\n  Future<void> _exportChatAsImage() async {\n    InputWidget.unFocus();\n    if (Current.messages.isEmpty) return;\n\n    try {\n      Dialogs.loading(\n        context: context,\n        hint: S.of(context).exporting,\n      );\n\n      final width = MediaQuery.of(context).size.width;\n      final page = Container(\n        padding: const EdgeInsets.only(top: 16, left: 16, right: 16, bottom: 0),\n        constraints: BoxConstraints(maxWidth: width),\n        child: MediaQuery(\n          data: MediaQueryData.fromView(View.of(context)).copyWith(\n            size: Size(width, double.infinity),\n          ),\n          child: Column(\n            children: [\n              for (final message in _messages) ...[\n                MessageView(message: message),\n                const SizedBox(height: 16),\n              ]\n            ],\n          ),\n        ),\n      );\n\n      final png = await ScreenshotController().captureFromLongWidget(\n        InheritedTheme.captureAll(\n          context,\n          Material(child: page),\n        ),\n        context: context,\n        pixelRatio: MediaQuery.of(context).devicePixelRatio,\n      );\n\n      final time = DateTime.now().millisecondsSinceEpoch.toString();\n      final path = Config.cacheFilePath(\"$time.png\");\n\n      final file = File(path);\n      await file.writeAsBytes(png.toList());\n\n      if (!mounted) return;\n      Navigator.of(context).pop();\n\n      Dialogs.handleImage(context: context, path: path);\n    } catch (e) {\n      Navigator.of(context).pop();\n      Dialogs.error(context: context, error: e);\n    }\n  }\n}\n\nfinal _toBottomProvider =\n    AutoDisposeNotifierProvider<_ToBottomNotifier, bool>(_ToBottomNotifier.new);\n\nclass _ToBottomNotifier extends AutoDisposeNotifier<bool> {\n  @override\n  bool build() {\n    ref.listen(messagesProvider, (prev, next) {\n      if (state) hide();\n    });\n    return false;\n  }\n\n  void show() => state = true;\n  void hide() => state = false;\n}\n"
  },
  {
    "path": "lib/chat/current.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"message.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\n\nimport \"dart:io\";\nimport \"dart:isolate\";\nimport \"dart:convert\";\n\nclass Current {\n  static File? _file;\n  static ChatConfig? _chat;\n\n  static CoreConfig core = Config.core;\n  static final List<Message> messages = [];\n  static TtsStatus ttsStatus = TtsStatus.nothing;\n  static ChatStatus chatStatus = ChatStatus.nothing;\n\n  static Future<void> load(ChatConfig chat) async {\n    _file = File(Config.chatFilePath(chat.fileName));\n    final from = _file;\n\n    final json = await Isolate.run(() async {\n      return jsonDecode(await from!.readAsString());\n    });\n\n    final messagesJson = json[\"messages\"] ?? [];\n    final coreJson = json[\"core\"];\n\n    messages.clear();\n    for (final message in messagesJson) {\n      messages.add(Message.fromJson(message));\n    }\n\n    core = coreJson != null ? CoreConfig.fromJson(coreJson) : Config.core;\n  }\n\n  static Future<void> save() async {\n    await _file!.writeAsString(jsonEncode({\n      \"core\": core,\n      \"messages\": messages,\n    }));\n  }\n\n  static void clear() {\n    _chat = null;\n    _file = null;\n    messages.clear();\n    core = Config.core;\n  }\n\n  static void newChat(String title) {\n    final now = DateTime.now();\n    final timestamp = now.millisecondsSinceEpoch.toString();\n\n    final time = Util.formatDateTime(now);\n    final fileName = \"$timestamp.json\";\n\n    _chat = ChatConfig(\n      time: time,\n      title: title,\n      fileName: fileName,\n    );\n    _file = File(Config.chatFilePath(fileName));\n\n    Config.chats.insert(0, _chat!);\n    Config.save();\n  }\n\n  static String? get bot => core.bot;\n  static String? get api => core.api;\n  static String? get model => core.model;\n\n  static ApiConfig? get _api => Config.apis[api];\n  static BotConfig? get _bot => Config.bots[bot];\n\n  static String? get apiUrl => _api?.url;\n  static String? get apiKey => _api?.key;\n  static String? get apiType => _api?.type;\n\n  static bool? get stream => _bot?.stream;\n  static int? get maxTokens => _bot?.maxTokens;\n  static double? get temperature => _bot?.temperature;\n  static String? get systemPrompts => _bot?.systemPrompts;\n\n  static ChatConfig? get chat => _chat;\n  static set chat(ChatConfig? chat) => _chat = chat!;\n\n  static String? get title => _chat?.title;\n  static set title(String? title) => _chat?.title = title!;\n\n  static bool get hasChat => _chat != null;\n}\n\nenum TtsStatus {\n  nothing,\n  loading,\n  playing;\n\n  bool get isNothing => this == TtsStatus.nothing;\n  bool get isLoading => this == TtsStatus.loading;\n  bool get isPlaying => this == TtsStatus.playing;\n}\n\nenum ChatStatus {\n  nothing,\n  responding;\n\n  bool get isNothing => this == ChatStatus.nothing;\n  bool get isResponding => this == ChatStatus.responding;\n}\n"
  },
  {
    "path": "lib/chat/input.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"chat.dart\";\nimport \"message.dart\";\nimport \"current.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../llm/llm.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"dart:convert\";\nimport \"package:flutter/material.dart\";\nimport \"package:flutter/services.dart\";\nimport \"package:image_picker/image_picker.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\nimport \"package:flutter_image_compress/flutter_image_compress.dart\";\n\nclass InputWidget extends ConsumerStatefulWidget {\n  static final FocusNode focusNode = FocusNode();\n\n  const InputWidget({super.key});\n\n  @override\n  ConsumerState<InputWidget> createState() => _InputWidgetState();\n\n  static void unFocus() => focusNode.unfocus();\n}\n\ntypedef _Image = ({String name, MessageImage image});\n\nclass _InputWidgetState extends ConsumerState<InputWidget> {\n  String _lastText = \"\";\n  static final List<_Image> _images = [];\n  final TextEditingController _inputCtrl = TextEditingController();\n\n  @override\n  void initState() {\n    super.initState();\n    _inputCtrl.addListener(() {\n      final text = _inputCtrl.text;\n      if (_lastText.isEmpty ^ text.isEmpty) {\n        setState(() {});\n      }\n      _lastText = text;\n    });\n  }\n\n  @override\n  void dispose() {\n    _inputCtrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    ref.watch(llmProvider);\n\n    return Container(\n      constraints: BoxConstraints(\n        maxHeight: MediaQuery.of(context).size.height / 4,\n      ),\n      decoration: BoxDecoration(\n        color: Theme.of(context).colorScheme.surfaceContainerHigh,\n        borderRadius: const BorderRadius.all(Radius.circular(12)),\n        border: Border.all(\n          color: Theme.of(context).colorScheme.outlineVariant,\n        ),\n      ),\n      child: Column(\n        mainAxisSize: MainAxisSize.min,\n        children: [\n          Flexible(\n            child: TextField(\n              maxLines: null,\n              autofocus: false,\n              controller: _inputCtrl,\n              focusNode: InputWidget.focusNode,\n              keyboardType: TextInputType.multiline,\n              decoration: InputDecoration(\n                border: InputBorder.none,\n                constraints: const BoxConstraints(),\n                hintText: S.of(context).enter_message,\n                contentPadding: const EdgeInsets.only(\n                    top: 8, left: 16, right: 16, bottom: 8),\n              ),\n            ),\n          ),\n          Row(\n            children: [\n              const SizedBox(width: 8),\n              SizedBox.square(\n                dimension: 36,\n                child: IconButton(\n                  icon: const Icon(Icons.upload_file),\n                  padding: EdgeInsets.zero,\n                  onPressed: _addFile,\n                ),\n              ),\n              const SizedBox(width: 8),\n              SizedBox.square(\n                dimension: 36,\n                child: GestureDetector(\n                  onLongPress: () {\n                    final old = Preferences.googleSearch;\n                    Util.showSnackBar(\n                      context: context,\n                      content: Text(old\n                          ? S.of(context).search_general_mode\n                          : S.of(context).search_gemini_mode),\n                    );\n                    setState(() => Preferences.googleSearch = !old);\n                  },\n                  child: IconButton(\n                    icon: const Icon(Icons.language),\n                    isSelected: Preferences.search,\n                    selectedIcon: Badge(\n                      label: const Text(\"G\"),\n                      isLabelVisible: Preferences.googleSearch,\n                      child: const Icon(Icons.language),\n                    ),\n                    padding: EdgeInsets.zero,\n                    onPressed: () => setState(\n                        () => Preferences.search = !Preferences.search),\n                  ),\n                ),\n              ),\n              if (_images.isNotEmpty) ...[\n                const SizedBox(width: 8),\n                SizedBox.square(\n                  dimension: 36,\n                  child: IconButton(\n                    icon: const Icon(Icons.image_outlined),\n                    isSelected: true,\n                    padding: EdgeInsets.zero,\n                    onPressed: _editImages,\n                  ),\n                ),\n              ],\n              const Expanded(child: SizedBox()),\n              const SizedBox(width: 8),\n              SizedBox.square(\n                dimension: 36,\n                child: _buildSendButton(),\n              ),\n              const SizedBox(width: 8),\n            ],\n          ),\n          const SizedBox(height: 8),\n        ],\n      ),\n    );\n  }\n\n  Widget _buildSendButton() {\n    IconData icon;\n    Color background;\n    Color? foreground;\n\n    if (Current.chatStatus.isResponding) {\n      icon = Icons.pause;\n      background = Theme.of(context).colorScheme.primaryContainer;\n      foreground = Theme.of(context).colorScheme.onPrimaryContainer;\n    } else {\n      icon = Icons.arrow_upward;\n      if (_inputCtrl.text.isEmpty) {\n        background = Colors.grey.withOpacity(0.2);\n      } else {\n        background = Theme.of(context).colorScheme.primaryContainer;\n        foreground = Theme.of(context).colorScheme.onPrimaryContainer;\n      }\n    }\n\n    return IconButton(\n      icon: Icon(icon),\n      onPressed: _sendMessage,\n      padding: EdgeInsets.zero,\n      style: IconButton.styleFrom(\n        foregroundColor: foreground,\n        backgroundColor: background,\n      ),\n    );\n  }\n\n  Future<void> _addFile() async {\n    InputWidget.unFocus();\n\n    final result = await showModalBottomSheet<int>(\n      context: context,\n      builder: (context) => Padding(\n        padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8),\n        child: Column(\n          mainAxisSize: MainAxisSize.min,\n          children: [\n            const DragHandle(),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).camera),\n              leading: const Icon(Icons.camera_outlined),\n              onTap: () => Navigator.of(context).pop(1),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).gallery),\n              leading: const Icon(Icons.photo_library_outlined),\n              onTap: () => Navigator.of(context).pop(2),\n            ),\n          ],\n        ),\n      ),\n    );\n\n    switch (result) {\n      case 1:\n        await _addImage(ImageSource.camera);\n        break;\n\n      case 2:\n        await _addImage(ImageSource.gallery);\n        break;\n    }\n  }\n\n  Future<void> _addImage(ImageSource source) async {\n    XFile? result;\n    Uint8List? compressed;\n    final picker = ImagePicker();\n\n    try {\n      result = await picker.pickImage(source: source);\n      if (result == null) return;\n    } catch (e) {\n      return;\n    }\n\n    if (Config.cic.enable ?? true) {\n      try {\n        compressed = await FlutterImageCompress.compressWithFile(\n          result.path,\n          quality: Config.cic.quality ?? 95,\n          minWidth: Config.cic.minWidth ?? 1920,\n          minHeight: Config.cic.minHeight ?? 1080,\n        );\n        if (compressed == null) throw false;\n      } catch (e) {\n        if (mounted) {\n          Util.showSnackBar(\n            context: context,\n            content: Text(S.of(context).image_compress_failed),\n          );\n        }\n      }\n    }\n\n    final bytes = compressed ?? await result.readAsBytes();\n    final image = (\n      name: result.name,\n      image: (bytes: bytes, base64: base64Encode(bytes)),\n    );\n    setState(() => _images.add(image));\n  }\n\n  void _editImages() async {\n    InputWidget.unFocus();\n\n    showModalBottomSheet<String>(\n      context: context,\n      scrollControlDisabledMaxHeightRatio: 0.7,\n      builder: (context) => StatefulBuilder(\n        builder: (context, setState2) => Column(\n          mainAxisSize: MainAxisSize.min,\n          crossAxisAlignment: CrossAxisAlignment.start,\n          children: [\n            DialogHeader(title: S.of(context).images),\n            const Divider(height: 1),\n            ListView.builder(\n              shrinkWrap: true,\n              itemCount: _images.length,\n              itemBuilder: (context, index) => ListTile(\n                title: Text(_images[index].name),\n                contentPadding: const EdgeInsets.only(left: 24, right: 12),\n                trailing: IconButton(\n                  icon: const Icon(Icons.delete),\n                  onPressed: () {\n                    setState(() => _images.removeAt(index));\n                    if (_images.isEmpty) {\n                      Navigator.of(context).pop();\n                    } else {\n                      setState2(() {});\n                    }\n                  },\n                ),\n              ),\n            ),\n            const Divider(height: 1),\n            DialogFooter(\n              children: [\n                TextButton(\n                  onPressed: Navigator.of(context).pop,\n                  child: Text(S.of(context).cancel),\n                ),\n                TextButton(\n                  onPressed: () {\n                    setState(() => _images.clear());\n                    Navigator.of(context).pop();\n                  },\n                  child: Text(S.of(context).clear),\n                ),\n              ],\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  Future<void> _sendMessage() async {\n    if (!Current.chatStatus.isNothing) {\n      ref.read(llmProvider.notifier).stopChat();\n      return;\n    }\n\n    if (!Util.checkChat(context)) return;\n    final text = _inputCtrl.text;\n    if (text.isEmpty) return;\n\n    final messages = Current.messages;\n    final user = MessageItem(\n      text: text,\n      role: MessageRole.user,\n    );\n    for (final image in _images) {\n      user.images.add(image.image);\n    }\n    messages.add(Message.fromItem(user));\n\n    final assistant = Message.fromItem(MessageItem(\n      text: \"\",\n      model: Current.model,\n      role: MessageRole.assistant,\n      time: Util.formatDateTime(DateTime.now()),\n    ));\n    messages.add(assistant);\n    ref.read(messagesProvider.notifier).notify();\n\n    _images.clear();\n    _inputCtrl.clear();\n\n    final results = await Future.wait([\n      _generateTitle(text).catchError((e) => text),\n      ref.read(llmProvider.notifier).chat(assistant),\n    ]);\n\n    final title = results[0];\n    final error = results[1];\n\n    if (error != null && mounted) {\n      _inputCtrl.text = text;\n      Dialogs.error(context: context, error: error);\n    }\n\n    if (title != null) {\n      Current.newChat(title);\n      ref.read(chatProvider.notifier).notify();\n      ref.read(chatsProvider.notifier).notify();\n    }\n    Current.save();\n  }\n\n  Future<String?> _generateTitle(String text) async {\n    if (Current.hasChat) return null;\n    return await generateTitle(text);\n  }\n}\n"
  },
  {
    "path": "lib/chat/message.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"chat.dart\";\nimport \"input.dart\";\nimport \"current.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../llm/llm.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../markdown/util.dart\";\nimport \"../markdown/code.dart\";\nimport \"../markdown/latex.dart\";\n\nimport \"dart:async\";\nimport \"dart:convert\";\nimport \"dart:typed_data\";\nimport \"package:flutter/material.dart\";\nimport \"package:animate_do/animate_do.dart\";\nimport \"package:flutter_spinkit/flutter_spinkit.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\nimport \"package:flutter_markdown/flutter_markdown.dart\";\n\nfinal messageProvider = NotifierProvider.autoDispose\n    .family<MessageNotifier, void, Message>(MessageNotifier.new);\n\nclass MessageNotifier extends AutoDisposeFamilyNotifier<void, Message> {\n  @override\n  void build(Message arg) {}\n\n  void notify() => ref.notifyListeners();\n}\n\nenum MessageRole {\n  user,\n  assistant;\n\n  bool get isUser => this == MessageRole.user;\n  bool get isAssistant => this == MessageRole.assistant;\n}\n\nenum CitationType {\n  web,\n}\n\ntypedef MessageImage = ({\n  Uint8List bytes,\n  String base64,\n});\n\ntypedef MessageCitation = ({\n  CitationType type,\n  String content,\n  String source,\n});\n\nclass MessageItem {\n  String text;\n  String? time;\n  String? model;\n  MessageRole role;\n  List<MessageImage> images = [];\n  List<MessageCitation> citations = [];\n\n  MessageItem({\n    required this.role,\n    required this.text,\n    this.model,\n    this.time,\n  });\n\n  factory MessageItem.fromJson(Map json) {\n    final item = switch (json[\"role\"]) {\n      \"assistant\" => MessageItem(\n          time: json[\"time\"],\n          text: json[\"text\"],\n          model: json[\"model\"],\n          role: MessageRole.assistant,\n        ),\n      \"user\" => MessageItem(\n          text: json[\"text\"],\n          role: MessageRole.user,\n        ),\n      _ => throw \"bad role\",\n    };\n\n    final image = json[\"image\"];\n    final images = json[\"images\"] ?? [];\n\n    if (image != null) {\n      item.images.add((\n        bytes: base64Decode(image),\n        base64: image,\n      ));\n    }\n    for (final base64 in images) {\n      item.images.add((\n        bytes: base64Decode(base64),\n        base64: base64,\n      ));\n    }\n\n    return item;\n  }\n\n  Map toJson() => switch (role) {\n        MessageRole.assistant => {\n            \"time\": time,\n            \"text\": text,\n            \"model\": model,\n            \"role\": \"assistant\",\n          },\n        MessageRole.user => {\n            \"text\": text,\n            \"role\": \"user\",\n            \"images\": [\n              for (final image in images) image.base64,\n            ],\n          },\n      };\n}\n\nclass Message {\n  int index;\n  List<MessageItem> list;\n\n  Message({\n    required this.index,\n    required this.list,\n  });\n\n  factory Message.fromItem(MessageItem item) => Message(\n        index: 0,\n        list: [item],\n      );\n\n  factory Message.fromJson(Map json) =>\n      json[\"index\"] == null && json[\"list\"] == null\n          ? Message.fromItem(MessageItem.fromJson(json))\n          : Message(\n              index: json[\"index\"],\n              list: [\n                for (final item in json[\"list\"]) MessageItem.fromJson(item),\n              ],\n            );\n\n  Map toJson() => {\n        \"index\": index,\n        \"list\": list,\n      };\n\n  MessageItem get item => list[index];\n}\n\nclass MessageWidget extends ConsumerStatefulWidget {\n  final Message message;\n\n  const MessageWidget({\n    required this.message,\n    super.key,\n  });\n\n  @override\n  ConsumerState<MessageWidget> createState() => _MessageWidgetState();\n}\n\nclass _MessageWidgetState extends ConsumerState<MessageWidget> {\n  @override\n  Widget build(BuildContext context) {\n    final message = widget.message;\n    ref.watch(messageProvider(message));\n\n    final item = message.item;\n    final role = item.role;\n\n    return Container(\n      alignment: role.isUser ? Alignment.topRight : Alignment.topLeft,\n      child: Column(\n        crossAxisAlignment: role.isAssistant\n            ? CrossAxisAlignment.start\n            : CrossAxisAlignment.end,\n        children: [\n          if (item.images.isNotEmpty) ...[\n            _buildImages(),\n            const SizedBox(height: 8),\n          ],\n          if (role.isAssistant) ...[\n            _buildHeader(),\n            SizedBox(height: 8),\n          ],\n          _buildBody(),\n          if (Current.messages.lastOrNull == message &&\n              Current.chatStatus.isNothing) ...[\n            const SizedBox(height: 4),\n            FadeIn(child: _buildToolBar()),\n          ],\n        ],\n      ),\n    );\n  }\n\n  Widget _buildImages() {\n    final item = widget.message.item;\n\n    return LayoutBuilder(builder: (context, constraints) {\n      final n = (constraints.maxWidth / 120).ceil();\n      final width = (constraints.maxWidth - 8 * (n - 1)) / n;\n      return Wrap(\n        spacing: 8,\n        runSpacing: 8,\n        children: [\n          for (final image in item.images)\n            Ink(\n              width: width,\n              height: width,\n              decoration: BoxDecoration(\n                borderRadius: const BorderRadius.all(Radius.circular(12)),\n                image: DecorationImage(\n                  image: MemoryImage(image.bytes),\n                  fit: BoxFit.cover,\n                ),\n              ),\n              child: InkWell(\n                borderRadius: const BorderRadius.all(Radius.circular(12)),\n                onTap: () async {\n                  InputWidget.unFocus();\n\n                  final result = await showDialog<bool>(\n                    context: context,\n                    builder: (context) => AlertDialog(\n                      title: Text(S.of(context).delete_image),\n                      content: Text(S.of(context).ensure_delete_image),\n                      actions: [\n                        TextButton(\n                          onPressed: Navigator.of(context).pop,\n                          child: Text(S.of(context).cancel),\n                        ),\n                        TextButton(\n                          onPressed: () => Navigator.of(context).pop(true),\n                          child: Text(S.of(context).delete),\n                        ),\n                      ],\n                    ),\n                  );\n                  if (!(result ?? false)) return;\n\n                  setState(() => item.images.remove(image));\n                  Current.save();\n                },\n              ),\n            ),\n        ],\n      );\n    });\n  }\n\n  Widget _buildHeader() {\n    final message = widget.message;\n    final item = message.item;\n    final id = item.model;\n\n    return Row(\n      crossAxisAlignment: CrossAxisAlignment.center,\n      children: [\n        ModelAvatar(id: id),\n        const SizedBox(width: 12),\n        Flexible(\n          child: Column(\n            mainAxisAlignment: MainAxisAlignment.center,\n            crossAxisAlignment: CrossAxisAlignment.start,\n            children: [\n              const SizedBox(height: 1),\n              Text(\n                Config.models[id]?.name ?? id ?? S.of(context).no_model,\n                style: Theme.of(context).textTheme.titleMedium,\n                overflow: TextOverflow.ellipsis,\n              ),\n              const SizedBox(height: 1),\n              Text(\n                item.time ?? Util.formatDateTime(DateTime.now()),\n                style: Theme.of(context).textTheme.bodySmall,\n              ),\n              const SizedBox(height: 2),\n            ],\n          ),\n        ),\n        if (message.list.length > 1 &&\n            (Current.chatStatus.isNothing ||\n                message != Current.messages.lastOrNull)) ...[\n          const SizedBox(width: 8),\n          SizedBox(\n            width: 32,\n            height: 32,\n            child: IconButton(\n              icon: const Icon(Icons.arrow_back_ios_rounded),\n              iconSize: 16,\n              onPressed: () {\n                if (item == message.list.first) return;\n                setState(() => message.index--);\n                Current.save();\n              },\n            ),\n          ),\n          Text(\"${message.index + 1}/${message.list.length}\"),\n          SizedBox(\n            width: 32,\n            height: 32,\n            child: IconButton(\n              icon: const Icon(Icons.arrow_forward_ios_rounded),\n              iconSize: 16,\n              onPressed: () {\n                if (item == message.list.last) return;\n                setState(() => message.index++);\n                Current.save();\n              },\n            ),\n          ),\n        ],\n      ],\n    );\n  }\n\n  Widget _buildBody() {\n    final item = widget.message.item;\n    final text = item.text;\n    final role = item.role;\n\n    final colorScheme = Theme.of(context).colorScheme;\n    final markdownStyleSheet = MarkdownStyleSheet(\n      codeblockPadding: EdgeInsets.all(0),\n      codeblockDecoration: BoxDecoration(\n        color: colorScheme.surfaceContainerHighest,\n        borderRadius: const BorderRadius.all(Radius.circular(12)),\n      ),\n      blockquoteDecoration: BoxDecoration(\n        color: colorScheme.brightness == Brightness.light\n            ? Colors.blueGrey.withOpacity(0.3)\n            : Colors.black.withOpacity(0.3),\n        borderRadius: const BorderRadius.all(Radius.circular(12)),\n      ),\n    );\n\n    final radius = BorderRadius.only(\n      topLeft: const Radius.circular(12),\n      bottomLeft: const Radius.circular(12),\n      bottomRight: const Radius.circular(12),\n      topRight: Radius.circular(role.isUser ? 2 : 12),\n    );\n\n    return LayoutBuilder(\n      key: UniqueKey(),\n      builder: (context, constraints) => Ink(\n        decoration: BoxDecoration(\n          color: role.isAssistant\n              ? colorScheme.surfaceContainer\n              : colorScheme.secondaryContainer,\n          borderRadius: radius,\n        ),\n        child: InkWell(\n          borderRadius: radius,\n          onLongPress: _longPress,\n          child: Container(\n            padding: const EdgeInsets.all(12),\n            constraints: BoxConstraints(\n              maxWidth: constraints.maxWidth * (role.isUser ? 0.9 : 1),\n            ),\n            child: switch (text.isNotEmpty) {\n              true => MarkdownBody(\n                  data: text,\n                  extensionSet: mdExtensionSet,\n                  onTapLink: (text, href, title) =>\n                      Dialogs.openLink(context: context, link: href),\n                  builders: {\n                    \"pre\": CodeBlockBuilder(context: context),\n                    \"latex\": LatexElementBuilder(textScaleFactor: 1.2),\n                  },\n                  styleSheet: markdownStyleSheet,\n                  styleSheetTheme: MarkdownStyleSheetBaseTheme.material,\n                ),\n              false => SizedBox(\n                  width: 36,\n                  height: 18,\n                  child: SpinKitWave(\n                    size: 18,\n                    color: colorScheme.onSurfaceVariant,\n                  ),\n                ),\n            },\n          ),\n        ),\n      ),\n    );\n  }\n\n  Widget _buildToolBar() {\n    final item = widget.message.item;\n    final role = item.role;\n\n    return Row(\n      mainAxisAlignment:\n          role.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,\n      children: [\n        if (role.isAssistant) ...[\n          SizedBox(\n            width: 36,\n            height: 26,\n            child: IconButton(\n              icon: Icon(switch (Current.ttsStatus) {\n                TtsStatus.loading => Icons.cancel_outlined,\n                TtsStatus.nothing => Icons.volume_up_outlined,\n                TtsStatus.playing => Icons.pause_circle_outlined,\n              }),\n              iconSize: 18,\n              onPressed: _tts,\n              padding: EdgeInsets.zero,\n            ),\n          ),\n          SizedBox(\n            width: 36,\n            height: 26,\n            child: IconButton(\n              icon: const Icon(Icons.sync_outlined),\n              iconSize: 18,\n              onPressed: _reanswer,\n              padding: EdgeInsets.zero,\n            ),\n          ),\n          if (item.citations.isNotEmpty)\n            SizedBox(\n              width: 36,\n              height: 26,\n              child: IconButton(\n                icon: const Icon(Icons.find_in_page_outlined),\n                iconSize: 18,\n                onPressed: _citations,\n                padding: EdgeInsets.zero,\n              ),\n            ),\n        ],\n        SizedBox(\n          width: 36,\n          height: 26,\n          child: IconButton(\n            icon: const Icon(Icons.paste_outlined),\n            iconSize: 16,\n            onPressed: _copy,\n            padding: EdgeInsets.zero,\n          ),\n        ),\n        SizedBox(\n          width: 36,\n          height: 26,\n          child: IconButton(\n            icon: const Icon(Icons.edit_outlined),\n            iconSize: 18,\n            onPressed: _edit,\n            padding: EdgeInsets.zero,\n          ),\n        ),\n        SizedBox(\n          width: 36,\n          height: 26,\n          child: IconButton(\n            icon: const Icon(Icons.delete_outlined),\n            iconSize: 18,\n            onPressed: _delete,\n            padding: EdgeInsets.zero,\n          ),\n        ),\n      ],\n    );\n  }\n\n  void _edit() {\n    InputWidget.unFocus();\n    Navigator.of(context).push(MaterialPageRoute(\n      builder: (context) => _MessageEditor(message: widget.message),\n    ));\n  }\n\n  void _copy() {\n    Util.copyText(\n      context: context,\n      text: widget.message.item.text,\n    );\n  }\n\n  void _delete() {\n    if (!Current.chatStatus.isNothing) return;\n    if (!Current.ttsStatus.isNothing) return;\n\n    final message = widget.message;\n    final list = message.list;\n    final item = message.item;\n\n    if (list.length == 1) {\n      Current.messages.remove(message);\n      ref.read(messagesProvider.notifier).notify();\n    } else {\n      if (item == list.last) message.index--;\n      setState(() => list.remove(item));\n    }\n\n    Current.save();\n  }\n\n  void _source() {\n    InputWidget.unFocus();\n\n    showModalBottomSheet(\n      context: context,\n      useSafeArea: true,\n      showDragHandle: true,\n      scrollControlDisabledMaxHeightRatio: 1,\n      builder: (context) => ConstrainedBox(\n        constraints: BoxConstraints(\n          minWidth: double.infinity,\n          minHeight: MediaQuery.of(context).size.height * 0.6,\n        ),\n        child: SingleChildScrollView(\n          padding: const EdgeInsets.only(left: 24, right: 24),\n          child: Column(\n            mainAxisSize: MainAxisSize.min,\n            crossAxisAlignment: CrossAxisAlignment.start,\n            children: [\n              SelectableText(\n                widget.message.item.text,\n                style: Theme.of(context).textTheme.bodyLarge,\n              ),\n              const SizedBox(height: 48),\n            ],\n          ),\n        ),\n      ),\n    );\n  }\n\n  void _citations() {\n    InputWidget.unFocus();\n    final citations = widget.message.item.citations;\n\n    void onTap(MessageCitation citation) {\n      switch (citation.type) {\n        case CitationType.web:\n          Dialogs.openLink(\n            context: context,\n            link: citation.source,\n          );\n          break;\n      }\n    }\n\n    showModalBottomSheet(\n      context: context,\n      useSafeArea: true,\n      scrollControlDisabledMaxHeightRatio: 0.7,\n      builder: (context) => Column(\n        mainAxisSize: MainAxisSize.min,\n        children: [\n          DialogHeader(title: S.of(context).citations),\n          const Divider(height: 1),\n          Flexible(\n            child: ListView.separated(\n              itemCount: citations.length,\n              itemBuilder: (context, index) {\n                final citation = citations[index];\n                final content = citation.content;\n                final source = citation.source;\n\n                return Card.filled(\n                  margin: EdgeInsets.zero,\n                  color: Theme.of(context).colorScheme.surfaceContainer,\n                  child: ListTile(\n                    title: Text(\n                      source,\n                      maxLines: 1,\n                      overflow: TextOverflow.ellipsis,\n                    ),\n                    subtitle: Text(\n                      content,\n                      maxLines: 2,\n                      overflow: TextOverflow.ellipsis,\n                    ),\n                    onTap: () => onTap(citation),\n                    shape: const RoundedRectangleBorder(\n                      borderRadius: BorderRadius.all(Radius.circular(12)),\n                    ),\n                    contentPadding: const EdgeInsets.symmetric(horizontal: 12),\n                  ),\n                );\n              },\n              padding: const EdgeInsets.all(12),\n              separatorBuilder: (context, index) => const SizedBox(height: 12),\n            ),\n          ),\n        ],\n      ),\n    );\n  }\n\n  void _longPress() {\n    InputWidget.unFocus();\n\n    void invoke(VoidCallback func) {\n      Navigator.of(context).pop();\n      func();\n    }\n\n    showModalBottomSheet(\n      context: context,\n      builder: (context) => Padding(\n        padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8),\n        child: Column(\n          mainAxisSize: MainAxisSize.min,\n          children: [\n            const DragHandle(),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).edit),\n              leading: const Icon(Icons.edit_outlined),\n              onTap: () => invoke(_edit),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: StadiumBorder(),\n              title: Text(S.of(context).copy),\n              leading: const Icon(Icons.copy_all),\n              onTap: () => invoke(_copy),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).delete),\n              leading: const Icon(Icons.delete_outlined),\n              onTap: () => invoke(_delete),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: const StadiumBorder(),\n              title: Text(S.of(context).source),\n              leading: const Icon(Icons.code_outlined),\n              onTap: () => invoke(_source),\n            ),\n            if (widget.message.item.citations.isNotEmpty)\n              ListTile(\n                minTileHeight: 48,\n                shape: const StadiumBorder(),\n                title: Text(S.of(context).citations),\n                leading: const Icon(Icons.find_in_page_outlined),\n                onTap: () => invoke(_citations),\n              ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  Future<void> _tts() async {\n    if (!Current.ttsStatus.isNothing) {\n      ref.read(llmProvider.notifier).stopTts();\n      return;\n    }\n\n    final message = widget.message;\n    final text = message.item.text;\n    if (text.isEmpty) return;\n\n    final tts = Config.tts;\n    final ttsOk = tts.api != null && tts.model != null && tts.voice != null;\n\n    if (!ttsOk) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).setup_tts_first),\n      );\n      return;\n    }\n\n    final error = await ref.read(llmProvider.notifier).tts(message);\n    if (error != null && mounted) {\n      Dialogs.error(context: context, error: error);\n    }\n  }\n\n  Future<void> _reanswer() async {\n    if (!Current.chatStatus.isNothing) {\n      ref.read(llmProvider.notifier).stopChat();\n      return;\n    }\n\n    if (!Util.checkChat(context)) return;\n    final message = widget.message;\n\n    message.list.add(MessageItem(\n      text: \"\",\n      model: Current.model,\n      role: MessageRole.assistant,\n      time: Util.formatDateTime(DateTime.now()),\n    ));\n    message.index = message.list.length - 1;\n\n    final error = await ref.read(llmProvider.notifier).chat(message);\n    if (error != null && mounted) {\n      Dialogs.error(context: context, error: error);\n    }\n\n    Current.save();\n  }\n}\n\nclass MessageView extends StatelessWidget {\n  final Message message;\n  final MessageItem item;\n\n  MessageView({\n    required this.message,\n    super.key,\n  }) : item = message.item;\n\n  @override\n  Widget build(BuildContext context) {\n    final role = item.role;\n\n    return Container(\n      alignment: role.isUser ? Alignment.topRight : Alignment.topLeft,\n      child: Column(\n        crossAxisAlignment: role.isAssistant\n            ? CrossAxisAlignment.start\n            : CrossAxisAlignment.end,\n        children: [\n          if (item.images.isNotEmpty) ...[\n            _buildImages(context),\n            const SizedBox(height: 8),\n          ],\n          if (role.isAssistant) ...[\n            _buildHeader(context),\n            const SizedBox(height: 8),\n          ],\n          _buildBody(context),\n        ],\n      ),\n    );\n  }\n\n  Widget _buildImages(BuildContext context) {\n    return LayoutBuilder(builder: (context, constraints) {\n      final n = (constraints.maxWidth / 120).ceil();\n      final width = (constraints.maxWidth - 8 * (n - 1)) / n;\n\n      return Wrap(\n        spacing: 8,\n        runSpacing: 8,\n        children: [\n          for (final image in item.images)\n            ClipRRect(\n              borderRadius: const BorderRadius.all(Radius.circular(8)),\n              child: Image.memory(\n                image.bytes,\n                width: width,\n                height: width,\n                fit: BoxFit.cover,\n              ),\n            ),\n        ],\n      );\n    });\n  }\n\n  Widget _buildHeader(BuildContext context) {\n    final id = item.model;\n\n    return Row(\n      crossAxisAlignment: CrossAxisAlignment.center,\n      children: [\n        ModelAvatar(id: id),\n        const SizedBox(width: 12),\n        Column(\n          mainAxisAlignment: MainAxisAlignment.center,\n          crossAxisAlignment: CrossAxisAlignment.start,\n          children: [\n            const SizedBox(height: 1),\n            Text(\n              Config.models[id]?.name ?? id ?? S.current.no_model,\n              style: Theme.of(context).textTheme.titleMedium,\n              overflow: TextOverflow.ellipsis,\n            ),\n            const SizedBox(height: 1),\n            Text(\n              item.time ?? Util.formatDateTime(DateTime.now()),\n              style: Theme.of(context).textTheme.bodySmall,\n            ),\n            const SizedBox(height: 2),\n          ],\n        ),\n      ],\n    );\n  }\n\n  Widget _buildBody(BuildContext context) {\n    final text = item.text;\n    final role = item.role;\n\n    final colorScheme = Theme.of(context).colorScheme;\n    final markdownStyleSheet = MarkdownStyleSheet(\n      codeblockPadding: EdgeInsets.all(0),\n      codeblockDecoration: BoxDecoration(\n        color: colorScheme.surfaceContainerHighest,\n        borderRadius: const BorderRadius.all(Radius.circular(12)),\n      ),\n      blockquoteDecoration: BoxDecoration(\n        color: colorScheme.brightness == Brightness.light\n            ? Colors.blueGrey.withOpacity(0.3)\n            : Colors.black.withOpacity(0.3),\n        borderRadius: const BorderRadius.all(Radius.circular(12)),\n      ),\n    );\n\n    final radius = BorderRadius.only(\n      topLeft: const Radius.circular(12),\n      bottomLeft: const Radius.circular(12),\n      bottomRight: const Radius.circular(12),\n      topRight: Radius.circular(role.isUser ? 2 : 12),\n    );\n\n    return Container(\n      padding: const EdgeInsets.all(12),\n      constraints: BoxConstraints(\n        maxWidth: MediaQuery.of(context).size.width * (role.isUser ? 0.9 : 1),\n      ),\n      decoration: BoxDecoration(\n        borderRadius: radius,\n        color: role.isAssistant\n            ? colorScheme.surfaceContainer\n            : colorScheme.secondaryContainer,\n      ),\n      child: MarkdownBody(\n        data: text,\n        extensionSet: mdExtensionSet,\n        onTapLink: (text, href, title) =>\n            Dialogs.openLink(context: context, link: href),\n        builders: {\n          \"pre\": CodeBlockBuilder2(context: context),\n          \"latex\": LatexElementBuilder2(textScaleFactor: 1.2),\n        },\n        styleSheet: markdownStyleSheet,\n        styleSheetTheme: MarkdownStyleSheetBaseTheme.material,\n      ),\n    );\n  }\n}\n\nclass _MessageEditor extends ConsumerStatefulWidget {\n  final Message message;\n\n  const _MessageEditor({\n    required this.message,\n  });\n\n  @override\n  ConsumerState<_MessageEditor> createState() => _MessageEditorState();\n}\n\nclass _MessageEditorState extends ConsumerState<_MessageEditor> {\n  late final Message message;\n  late final UndoHistoryController _undoCtrl;\n  late final TextEditingController _editCtrl;\n\n  @override\n  void initState() {\n    super.initState();\n    message = widget.message;\n    _undoCtrl = UndoHistoryController();\n    final text = widget.message.item.text;\n    _editCtrl = TextEditingController(text: text);\n  }\n\n  @override\n  void dispose() {\n    _editCtrl.dispose();\n    _undoCtrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: Text(S.of(context).edit),\n        actions: [\n          IconButton(\n            icon: const Icon(Icons.undo),\n            onPressed: () => _undoCtrl.undo(),\n          ),\n          IconButton(\n            icon: const Icon(Icons.redo),\n            onPressed: () => _undoCtrl.redo(),\n          ),\n          IconButton(\n            icon: const Icon(Icons.done),\n            onPressed: () {\n              message.item.text = _editCtrl.text;\n              ref.read(messageProvider(message).notifier).notify();\n\n              Current.save();\n              Navigator.of(context).pop();\n            },\n          ),\n        ],\n      ),\n      body: TextField(\n        expands: true,\n        maxLines: null,\n        controller: _editCtrl,\n        undoController: _undoCtrl,\n        textAlign: TextAlign.start,\n        keyboardType: TextInputType.multiline,\n        decoration: InputDecoration(\n          border: InputBorder.none,\n          hintText: S.of(context).enter_message,\n          contentPadding:\n              const EdgeInsets.only(top: 12, left: 16, right: 16, bottom: 12),\n        ),\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/chat/settings.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"chat.dart\";\nimport \"current.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../settings/api.dart\";\nimport \"../settings/bot.dart\";\nimport \"../workspace/model.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass ChatSettings extends ConsumerStatefulWidget {\n  const ChatSettings({super.key});\n\n  @override\n  ConsumerState<ChatSettings> createState() => _ChatSettingsState();\n}\n\nclass _ChatSettingsState extends ConsumerState<ChatSettings> {\n  String? _error;\n  String? _bot = Current.bot;\n  String? _api = Current.api;\n  String? _model = Current.model;\n  final TextEditingController _ctrl =\n      TextEditingController(text: Current.title);\n\n  @override\n  void dispose() {\n    _ctrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    ref.watch(chatProvider);\n    ref.watch(botsProvider);\n    ref.watch(apisProvider);\n\n    return Column(\n      mainAxisSize: MainAxisSize.min,\n      children: [\n        DialogHeader(title: S.of(context).chat_settings),\n        const Divider(height: 1),\n        const SizedBox(height: 4),\n        Row(\n          children: [\n            const SizedBox(width: 24),\n            Expanded(\n              child: TextField(\n                controller: _ctrl,\n                decoration: InputDecoration(\n                  errorText: _error,\n                  labelText: S.of(context).chat_title,\n                  border: const UnderlineInputBorder(),\n                ),\n              ),\n            ),\n            IconButton(\n              icon: const Icon(Icons.subdirectory_arrow_left),\n              onPressed: _saveTitle,\n            ),\n            const SizedBox(width: 12),\n          ],\n        ),\n        const SizedBox(height: 12),\n        Flexible(\n          child: SingleChildScrollView(\n            padding: const EdgeInsets.only(left: 12, right: 12),\n            child: Column(\n              mainAxisSize: MainAxisSize.min,\n              children: [\n                _buildBots(),\n                const SizedBox(height: 8),\n                ConstrainedBox(\n                  constraints: const BoxConstraints(maxHeight: 320),\n                  child: IntrinsicHeight(\n                    child: Row(\n                      crossAxisAlignment: CrossAxisAlignment.start,\n                      children: [\n                        Flexible(\n                          flex: 2,\n                          child: _buildApis(),\n                        ),\n                        const SizedBox(width: 8),\n                        Flexible(\n                          flex: 3,\n                          child: _buildModels(),\n                        ),\n                      ],\n                    ),\n                  ),\n                ),\n                const SizedBox(height: 12),\n              ],\n            ),\n          ),\n        ),\n      ],\n    );\n  }\n\n  Widget _buildBots() {\n    final bots = Config.bots.keys.toList();\n\n    return Card.filled(\n      margin: EdgeInsets.zero,\n      color: Theme.of(context).colorScheme.surfaceContainer,\n      child: Column(\n        crossAxisAlignment: CrossAxisAlignment.start,\n        children: [\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              const SizedBox(width: 12),\n              Icon(\n                Icons.smart_toy,\n                color: Theme.of(context).colorScheme.primary,\n              ),\n              const SizedBox(width: 16),\n              Text(\n                S.of(context).bot,\n                style: TextStyle(\n                  color: Theme.of(context).colorScheme.primary,\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 12),\n          if (bots.isNotEmpty) ...[\n            const Divider(height: 1),\n            const SizedBox(height: 8),\n            Stack(\n              children: [\n                const IgnorePointer(\n                  child: Opacity(\n                    opacity: 0,\n                    child: ChoiceChip(\n                      label: Text(\"bot\"),\n                      padding: EdgeInsets.all(4),\n                      selected: true,\n                    ),\n                  ),\n                ),\n                const SizedBox(width: double.infinity),\n                Positioned.fill(\n                  child: ListView.separated(\n                    shrinkWrap: true,\n                    scrollDirection: Axis.horizontal,\n                    padding: const EdgeInsets.only(left: 12, right: 12),\n                    itemCount: bots.length,\n                    itemBuilder: (context, index) {\n                      final bot = bots[index];\n                      return GestureDetector(\n                        onLongPress: () =>\n                            Navigator.of(context).push(MaterialPageRoute(\n                          builder: (context) => BotSettings(bot: bot),\n                        )),\n                        child: ChoiceChip(\n                          label: Text(bot),\n                          padding: const EdgeInsets.all(4),\n                          selected: _bot == bot,\n                          onSelected: (value) {\n                            setState(() => _bot = value ? bot : null);\n                            _saveCore();\n                          },\n                        ),\n                      );\n                    },\n                    separatorBuilder: (context, index) =>\n                        const SizedBox(width: 8),\n                  ),\n                ),\n              ],\n            ),\n            const SizedBox(height: 8),\n          ],\n        ],\n      ),\n    );\n  }\n\n  Widget _buildApis() {\n    final apis = Config.apis.keys.toList();\n\n    return Card.filled(\n      margin: EdgeInsets.zero,\n      color: Theme.of(context).colorScheme.surfaceContainer,\n      child: Column(\n        crossAxisAlignment: CrossAxisAlignment.start,\n        children: [\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              const SizedBox(width: 12),\n              Icon(\n                Icons.api,\n                color: Theme.of(context).colorScheme.primary,\n              ),\n              const SizedBox(width: 16),\n              Text(\n                S.of(context).api,\n                style: TextStyle(\n                  color: Theme.of(context).colorScheme.primary,\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 12),\n          if (apis.isNotEmpty) ...[\n            const Divider(height: 1),\n            Flexible(\n              child: SingleChildScrollView(\n                child: Column(\n                  children: [\n                    for (final api in apis)\n                      ListTile(\n                        title: Text(api),\n                        minTileHeight: 48,\n                        selected: _api == api,\n                        contentPadding:\n                            const EdgeInsets.only(left: 16, right: 16),\n                        onTap: () => setState(() => _api = api),\n                        onLongPress: () =>\n                            Navigator.of(context).push(MaterialPageRoute(\n                          builder: (context) => ApiSettings(api: api),\n                        )),\n                      ),\n                  ],\n                ),\n              ),\n            ),\n            const SizedBox(height: 12),\n          ],\n        ],\n      ),\n    );\n  }\n\n  Widget _buildModels() {\n    final ids = Config.apis[_api]?.models ?? [];\n    final models = <({String id, String name})>[];\n\n    for (final it in ids) {\n      final config = Config.models[it];\n      if (config == null) {\n        models.add((id: it, name: it));\n      } else if (config.chat) {\n        models.add((id: it, name: config.name));\n      }\n    }\n\n    return Card.filled(\n      margin: EdgeInsets.zero,\n      color: Theme.of(context).colorScheme.surfaceContainer,\n      child: Column(\n        crossAxisAlignment: CrossAxisAlignment.start,\n        children: [\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              const SizedBox(width: 12),\n              Icon(\n                Icons.face,\n                color: Theme.of(context).colorScheme.primary,\n              ),\n              const SizedBox(width: 16),\n              Text(\n                S.of(context).model,\n                style: TextStyle(\n                  color: Theme.of(context).colorScheme.primary,\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 12),\n          if (ids.isNotEmpty) ...[\n            const Divider(height: 1),\n            Flexible(\n              child: SingleChildScrollView(\n                child: Column(\n                  children: [\n                    for (final model in models)\n                      ListTile(\n                        title: Text(model.name),\n                        minTileHeight: 48,\n                        selected: _model == model.id,\n                        contentPadding:\n                            const EdgeInsets.only(left: 16, right: 16),\n                        onTap: () {\n                          setState(() => _model = model.id);\n                          _saveCore();\n                        },\n                        onLongPress: () => showModalBottomSheet(\n                          context: context,\n                          useSafeArea: true,\n                          isScrollControlled: true,\n                          builder: (context) => Padding(\n                            padding: EdgeInsets.only(\n                              bottom: MediaQuery.of(context).viewInsets.bottom,\n                            ),\n                            child: ModelSettings(id: model.id),\n                          ),\n                        ),\n                      ),\n                  ],\n                ),\n              ),\n            ),\n            const SizedBox(height: 12),\n          ],\n        ],\n      ),\n    );\n  }\n\n  void _saveCore() {\n    final oldModel = Current.model;\n\n    Current.core = CoreConfig(\n      bot: _bot,\n      api: _api,\n      model: _model,\n    );\n\n    if (_model != oldModel) {\n      ref.read(chatProvider.notifier).notify();\n    }\n\n    if (Current.hasChat) Current.save();\n  }\n\n  void _saveTitle() {\n    final title = _ctrl.text;\n    final hasChat = Current.hasChat;\n    final oldTitle = Current.title ?? \"\";\n\n    if (title.isEmpty && hasChat) {\n      final error = S.of(context).enter_a_title;\n      setState(() => _error = error);\n      return;\n    }\n\n    if (title != oldTitle) {\n      if (hasChat) {\n        Current.title = title;\n      } else {\n        Current.newChat(title);\n      }\n      ref.read(chatProvider.notifier).notify();\n      ref.read(chatsProvider.notifier).notify();\n    }\n\n    setState(() => _error = null);\n    if (Current.hasChat) Current.save();\n  }\n}\n"
  },
  {
    "path": "lib/config.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"dart:io\";\nimport \"dart:convert\";\nimport \"dart:isolate\";\nimport \"package:http/http.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:archive/archive_io.dart\";\nimport \"package:path_provider/path_provider.dart\";\nimport \"package:package_info_plus/package_info_plus.dart\";\nimport \"package:shared_preferences/shared_preferences.dart\";\n\nclass Config {\n  static late final TtsConfig tts;\n  static late final CicConfig cic;\n  static late final CoreConfig core;\n  static late final ImageConfig image;\n  static late final TitleConfig title;\n  static late final SearchConfig search;\n  static late final VectorConfig vector;\n  static late final DocumentConfig document;\n\n  static final List<ChatConfig> chats = [];\n  static final Map<String, BotConfig> bots = {};\n  static final Map<String, ApiConfig> apis = {};\n  static final Map<String, ModelConfig> models = {};\n\n  static late final File _file;\n  static late final String _dir;\n  static late final String _sep;\n  static late final String _cache;\n\n  static const String _chatDir = \"chat\";\n  static const String _audioDir = \"audio\";\n  static const String _imageDir = \"image\";\n  static const String _settingsFile = \"settings.json\";\n\n  static Future<void> init() async {\n    _sep = Platform.pathSeparator;\n    _cache = (await getTemporaryDirectory()).path;\n    if (Platform.isAndroid) {\n      _dir = (await getExternalStorageDirectory())!.path;\n    } else {\n      _dir = (await getApplicationSupportDirectory()).path;\n    }\n\n    _initDir();\n    _initFile();\n    _fixChatFile();\n\n    await Preferences.init();\n  }\n\n  static Future<void> save() async {\n    await _file.writeAsString(jsonEncode(toJson()));\n  }\n\n  static String chatFilePath(String fileName) =>\n      \"$_dir$_sep$_chatDir$_sep$fileName\";\n  static String audioFilePath(String fileName) =>\n      \"$_dir$_sep$_audioDir$_sep$fileName\";\n  static String imageFilePath(String fileName) =>\n      \"$_dir$_sep$_imageDir$_sep$fileName\";\n  static String cacheFilePath(String fileName) => \"$_cache$_sep$fileName\";\n\n  static Map toJson() => {\n        \"tts\": tts,\n        \"cic\": cic,\n        \"core\": core,\n        \"bots\": bots,\n        \"apis\": apis,\n        \"chats\": chats,\n        \"image\": image,\n        \"title\": title,\n        \"search\": search,\n        \"vector\": vector,\n        \"models\": models,\n        \"document\": document,\n      };\n\n  static void fromJson(Map json) {\n    final ttsJson = json[\"tts\"] ?? {};\n    final imgJson = json[\"cic\"] ?? {};\n    final coreJson = json[\"core\"] ?? {};\n    final botsJson = json[\"bots\"] ?? {};\n    final apisJson = json[\"apis\"] ?? {};\n    final chatsJson = json[\"chats\"] ?? [];\n    final imageJson = json[\"image\"] ?? {};\n    final titleJson = json[\"title\"] ?? {};\n    final searchJson = json[\"search\"] ?? {};\n    final vectorJson = json[\"vector\"] ?? {};\n    final modelsJson = json[\"models\"] ?? {};\n    final documentJson = json[\"document\"] ?? {};\n\n    tts = TtsConfig.fromJson(ttsJson);\n    cic = CicConfig.fromJson(imgJson);\n    core = CoreConfig.fromJson(coreJson);\n    image = ImageConfig.fromJson(imageJson);\n    title = TitleConfig.fromJson(titleJson);\n    search = SearchConfig.fromJson(searchJson);\n    vector = VectorConfig.fromJson(vectorJson);\n    document = DocumentConfig.fromJson(documentJson);\n\n    for (final chat in chatsJson) {\n      chats.add(ChatConfig.fromJson(chat));\n    }\n    for (final pair in botsJson.entries) {\n      bots[pair.key] = BotConfig.fromJson(pair.value);\n    }\n    for (final pair in apisJson.entries) {\n      apis[pair.key] = ApiConfig.fromJson(pair.value);\n    }\n    for (final pair in modelsJson.entries) {\n      models[pair.key] = ModelConfig.fromJson(pair.value);\n    }\n  }\n\n  static void _initDir() {\n    final chatPath = \"$_dir$_sep$_chatDir\";\n    final chatDir = Directory(chatPath);\n    if (!(chatDir.existsSync())) {\n      chatDir.createSync();\n    }\n\n    final imagePath = \"$_dir$_sep$_imageDir\";\n    final imageDir = Directory(imagePath);\n    if (!(imageDir.existsSync())) {\n      imageDir.createSync();\n    }\n\n    final audioPath = \"$_dir$_sep$_audioDir\";\n    final audioDir = Directory(audioPath);\n    if (!(audioDir.existsSync())) {\n      audioDir.createSync();\n    }\n  }\n\n  static void _initFile() {\n    final path = \"$_dir$_sep$_settingsFile\";\n    _file = File(path);\n\n    if (_file.existsSync()) {\n      final data = _file.readAsStringSync();\n      fromJson(jsonDecode(data));\n    } else {\n      fromJson({});\n    }\n  }\n\n  static void _fixChatFile() {\n    for (final chat in chats) {\n      final fileName = chat.fileName;\n      final oldPath = \"$_dir$_sep$fileName\";\n      final newPath = chatFilePath(fileName);\n\n      final file = File(oldPath);\n      if (file.existsSync()) {\n        file.renameSync(newPath);\n      }\n    }\n  }\n}\n\nclass Backup {\n  static Future<void> exportConfig(String to) async {\n    final time = DateTime.now().millisecondsSinceEpoch.toString();\n    final path = \"$to${Config._sep}chatbot-backup-$time.zip\";\n    final root = Directory(Config._dir);\n\n    await Isolate.run(() async {\n      final encoder = ZipFileEncoder();\n      encoder.create(path);\n\n      await for (final entity in root.list()) {\n        if (entity is File) {\n          encoder.addFile(entity);\n        } else if (entity is Directory) {\n          encoder.addDirectory(entity);\n        }\n      }\n      await encoder.close();\n    });\n  }\n\n  static Future<void> importConfig(String from) async {\n    final root = Config._dir;\n\n    await Isolate.run(() async {\n      await extractFileToDisk(from, root);\n    });\n  }\n\n  static Future<void> clearData(List<String> dirs) async {\n    final root = Config._dir;\n    final sep = Config._sep;\n\n    await Isolate.run(() async {\n      for (final dir in dirs) {\n        final directory = Directory(\"$root$sep$dir\");\n        if (!directory.existsSync()) continue;\n        directory.deleteSync(recursive: true);\n      }\n    });\n\n    Config._initDir();\n  }\n}\n\nclass Updater {\n  static List<int>? versionCode;\n  static const String latestUrl =\n      \"https://github.com/fanenr/flutter-chatbot/releases/latest\";\n  static const String apiEndPoint =\n      \"https://api.github.com/repos/fanenr/flutter-chatbot/releases/latest\";\n\n  static Future<Map?> check() async {\n    if (versionCode == null) {\n      final version = (await PackageInfo.fromPlatform()).version;\n      versionCode = version.split('.').map(int.parse).toList();\n    }\n\n    final client = Client();\n    final response = await client.get(Uri.parse(apiEndPoint));\n\n    if (response.statusCode != 200) {\n      throw \"${response.statusCode} ${response.body}\";\n    }\n\n    final json = jsonDecode(response.body);\n    return _isNewer(json[\"tag_name\"]) ? json : null;\n  }\n\n  static bool _isNewer(String latest) {\n    final latestCode = latest.substring(1).split('.').map(int.parse).toList();\n    for (int i = 0; i < 3; i++) {\n      if (latestCode[i] < versionCode![i]) return false;\n      if (latestCode[i] > versionCode![i]) return true;\n    }\n    return false;\n  }\n}\n\nclass Preferences {\n  static late bool _search;\n  static late bool _googleSearch;\n  static late SharedPreferencesAsync _prefs;\n\n  static Future<void> init() async {\n    SharedPreferences.setPrefix(\"chatbot\");\n    _prefs = SharedPreferencesAsync();\n    await _init();\n  }\n\n  static bool get search => _search;\n  static bool get googleSearch => _googleSearch;\n\n  static set search(bool value) {\n    _search = value;\n    _prefs.setBool(\"search\", value);\n  }\n\n  static set googleSearch(bool value) {\n    _googleSearch = value;\n    _prefs.setBool(\"googleSearch\", value);\n  }\n\n  static Future<void> _init() async {\n    _search = await _prefs.getBool(\"search\") ?? false;\n    _googleSearch = await _prefs.getBool(\"googleSearch\") ?? false;\n  }\n}\n\nclass BotConfig {\n  bool? stream;\n  int? maxTokens;\n  double? temperature;\n  String? systemPrompts;\n\n  BotConfig({\n    this.stream,\n    this.maxTokens,\n    this.temperature,\n    this.systemPrompts,\n  });\n\n  Map toJson() => {\n        \"stream\": stream,\n        \"maxTokens\": maxTokens,\n        \"temperature\": temperature,\n        \"systemPrompts\": systemPrompts,\n      };\n\n  factory BotConfig.fromJson(Map json) => BotConfig(\n        stream: json[\"stream\"],\n        maxTokens: json[\"maxTokens\"],\n        temperature: json[\"temperature\"],\n        systemPrompts: json[\"systemPrompts\"],\n      );\n}\n\nclass ApiConfig {\n  String url;\n  String key;\n  String? type;\n  List<String> models;\n\n  ApiConfig({\n    required this.url,\n    required this.key,\n    required this.models,\n    this.type,\n  });\n\n  Map toJson() => {\n        \"url\": url,\n        \"key\": key,\n        \"type\": type,\n        \"models\": models,\n      };\n\n  factory ApiConfig.fromJson(Map json) => ApiConfig(\n        url: json[\"url\"],\n        key: json[\"key\"],\n        type: json[\"type\"],\n        models: json[\"models\"].cast<String>(),\n      );\n}\n\nclass CoreConfig {\n  String? _bot;\n  String? _api;\n  String? _model;\n\n  CoreConfig({\n    String? bot,\n    String? api,\n    String? model,\n  })  : _bot = bot,\n        _api = api,\n        _model = model;\n\n  String? get bot => Config.bots.containsKey(_bot) ? _bot : null;\n  String? get api => Config.apis.containsKey(_api) ? _api : null;\n  String? get model =>\n      (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null;\n\n  set bot(String? value) => _bot = value;\n  set api(String? value) => _api = value;\n  set model(String? value) => _model = value;\n\n  Map toJson() => {\n        \"bot\": bot,\n        \"api\": api,\n        \"model\": model,\n      };\n\n  factory CoreConfig.fromJson(Map json) => CoreConfig(\n        bot: json[\"bot\"],\n        api: json[\"api\"],\n        model: json[\"model\"],\n      );\n}\n\nclass ChatConfig {\n  String time;\n  String title;\n  String fileName;\n\n  ChatConfig({\n    required this.time,\n    required this.title,\n    required this.fileName,\n  });\n\n  Map toJson() => {\n        \"time\": time,\n        \"title\": title,\n        \"fileName\": fileName,\n      };\n\n  factory ChatConfig.fromJson(Map json) => ChatConfig(\n        time: json[\"time\"],\n        title: json[\"title\"],\n        fileName: json[\"fileName\"],\n      );\n}\n\nclass TtsConfig {\n  String? _api;\n  String? _model;\n  String? voice;\n\n  TtsConfig({\n    String? api,\n    String? model,\n    this.voice,\n  })  : _api = api,\n        _model = model;\n\n  String? get api => Config.apis.containsKey(_api) ? _api : null;\n  String? get model =>\n      (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null;\n\n  set api(String? value) => _api = value;\n  set model(String? value) => _model = value;\n\n  Map toJson() => {\n        \"api\": api,\n        \"model\": model,\n        \"voice\": voice,\n      };\n\n  factory TtsConfig.fromJson(Map json) => TtsConfig(\n        api: json[\"api\"],\n        model: json[\"model\"],\n        voice: json[\"voice\"],\n      );\n}\n\nclass CicConfig {\n  bool? enable;\n  int? quality;\n  int? minWidth;\n  int? minHeight;\n\n  CicConfig({\n    this.enable,\n    this.quality,\n    this.minWidth,\n    this.minHeight,\n  });\n\n  Map toJson() => {\n        \"enable\": enable,\n        \"quality\": quality,\n        \"minWidth\": minWidth,\n        \"minHeight\": minHeight,\n      };\n\n  factory CicConfig.fromJson(Map json) => CicConfig(\n        enable: json[\"enable\"],\n        quality: json[\"quality\"],\n        minWidth: json[\"minWidth\"],\n        minHeight: json[\"minHeight\"],\n      );\n}\n\nclass ImageConfig {\n  String? _api;\n  String? _model;\n  String? size;\n  String? style;\n  String? quality;\n\n  ImageConfig({\n    String? api,\n    String? model,\n    this.size,\n    this.style,\n    this.quality,\n  })  : _api = api,\n        _model = model;\n\n  String? get api => Config.apis.containsKey(_api) ? _api : null;\n  String? get model =>\n      (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null;\n\n  set api(String? value) => _api = value;\n  set model(String? value) => _model = value;\n\n  Map toJson() => {\n        \"api\": api,\n        \"model\": model,\n        \"size\": size,\n        \"style\": style,\n        \"quality\": quality,\n      };\n\n  factory ImageConfig.fromJson(Map json) => ImageConfig(\n        api: json[\"api\"],\n        size: json[\"size\"],\n        model: json[\"model\"],\n        style: json[\"style\"],\n        quality: json[\"quality\"],\n      );\n}\n\nclass ModelConfig {\n  bool chat;\n  String name;\n\n  ModelConfig({\n    required this.chat,\n    required this.name,\n  });\n\n  Map toJson() => {\n        \"chat\": chat,\n        \"name\": name,\n      };\n\n  factory ModelConfig.fromJson(Map json) => ModelConfig(\n        chat: json[\"chat\"],\n        name: json[\"name\"],\n      );\n}\n\nclass TitleConfig {\n  bool? enable;\n  String? _api;\n  String? _model;\n  String? prompt;\n\n  TitleConfig({\n    String? api,\n    String? model,\n    this.enable,\n    this.prompt,\n  })  : _api = api,\n        _model = model;\n\n  String? get api => Config.apis.containsKey(_api) ? _api : null;\n  String? get model =>\n      (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null;\n\n  set api(String? value) => _api = value;\n  set model(String? value) => _model = value;\n\n  Map toJson() => {\n        \"api\": api,\n        \"model\": model,\n        \"prompt\": prompt,\n        \"enable\": enable,\n      };\n\n  factory TitleConfig.fromJson(Map json) => TitleConfig(\n        api: json[\"api\"],\n        model: json[\"model\"],\n        prompt: json[\"prompt\"],\n        enable: json[\"enable\"],\n      );\n}\n\nclass SearchConfig {\n  int? n;\n  bool? vector;\n  int? queryTime;\n  int? fetchTime;\n  String? prompt;\n  String? searxng;\n\n  SearchConfig({\n    this.n,\n    this.vector,\n    this.prompt,\n    this.searxng,\n    this.queryTime,\n    this.fetchTime,\n  });\n\n  Map toJson() => {\n        \"n\": n,\n        \"vector\": vector,\n        \"prompt\": prompt,\n        \"query\": queryTime,\n        \"fetch\": fetchTime,\n        \"searxng\": searxng,\n      };\n\n  factory SearchConfig.fromJson(Map json) => SearchConfig(\n        n: json[\"n\"],\n        vector: json[\"vector\"],\n        prompt: json[\"prompt\"],\n        queryTime: json[\"query\"],\n        fetchTime: json[\"fetch\"],\n        searxng: json[\"searxng\"],\n      );\n}\n\nclass VectorConfig {\n  String? _api;\n  String? _model;\n  int? batchSize;\n  int? dimensions;\n\n  VectorConfig({\n    String? api,\n    String? model,\n    this.batchSize,\n    this.dimensions,\n  })  : _api = api,\n        _model = model;\n\n  String? get api => Config.apis.containsKey(_api) ? _api : null;\n  String? get model =>\n      (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null;\n\n  set api(String? value) => _api = value;\n  set model(String? value) => _model = value;\n\n  factory VectorConfig.fromJson(Map json) => VectorConfig(\n        api: json[\"api\"],\n        model: json[\"model\"],\n        batchSize: json[\"batchSize\"],\n        dimensions: json[\"dimensions\"],\n      );\n\n  Map toJson() => {\n        \"api\": api,\n        \"model\": model,\n        \"batchSize\": batchSize,\n        \"dimensions\": dimensions,\n      };\n}\n\nclass DocumentConfig {\n  int? n;\n  int? size;\n  int? overlap;\n\n  DocumentConfig({\n    this.n,\n    this.size,\n    this.overlap,\n  });\n\n  Map toJson() => {\n        \"n\": n,\n        \"size\": size,\n        \"overlap\": overlap,\n      };\n\n  factory DocumentConfig.fromJson(Map json) => DocumentConfig(\n        n: json[\"n\"],\n        size: json[\"size\"],\n        overlap: json[\"overlap\"],\n      );\n}\n\nconst _baseColor = Colors.indigo;\n\nfinal ColorScheme darkColorScheme = ColorScheme.fromSeed(\n  brightness: Brightness.dark,\n  seedColor: _baseColor,\n);\n\nfinal ColorScheme lightColorScheme = ColorScheme.fromSeed(\n  brightness: Brightness.light,\n  seedColor: _baseColor,\n);\n\nfinal darkTheme = ThemeData.dark(useMaterial3: true).copyWith(\n  colorScheme: darkColorScheme,\n  bottomSheetTheme: BottomSheetThemeData(\n    backgroundColor: darkColorScheme.surface,\n  ),\n  appBarTheme: AppBarTheme(color: darkColorScheme.primaryContainer),\n);\n\nfinal lightTheme = ThemeData.light(useMaterial3: true).copyWith(\n  colorScheme: lightColorScheme,\n  bottomSheetTheme: BottomSheetThemeData(\n    backgroundColor: lightColorScheme.surface,\n  ),\n  appBarTheme: AppBarTheme(color: lightColorScheme.primaryContainer),\n);\n"
  },
  {
    "path": "lib/gen/intl/messages_all.dart",
    "content": "// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart\n// This is a library that looks up messages for specific locales by\n// delegating to the appropriate library.\n\n// Ignore issues from commonly used lints in this file.\n// ignore_for_file:implementation_imports, file_names, unnecessary_new\n// ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering\n// ignore_for_file:argument_type_not_assignable, invalid_assignment\n// ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases\n// ignore_for_file:comment_references\n\nimport 'dart:async';\n\nimport 'package:flutter/foundation.dart';\nimport 'package:intl/intl.dart';\nimport 'package:intl/message_lookup_by_library.dart';\nimport 'package:intl/src/intl_helpers.dart';\n\nimport 'messages_en.dart' as messages_en;\nimport 'messages_zh_CN.dart' as messages_zh_cn;\n\ntypedef Future<dynamic> LibraryLoader();\nMap<String, LibraryLoader> _deferredLibraries = {\n  'en': () => new SynchronousFuture(null),\n  'zh_CN': () => new SynchronousFuture(null),\n};\n\nMessageLookupByLibrary? _findExact(String localeName) {\n  switch (localeName) {\n    case 'en':\n      return messages_en.messages;\n    case 'zh_CN':\n      return messages_zh_cn.messages;\n    default:\n      return null;\n  }\n}\n\n/// User programs should call this before using [localeName] for messages.\nFuture<bool> initializeMessages(String localeName) {\n  var availableLocale = Intl.verifiedLocale(\n      localeName, (locale) => _deferredLibraries[locale] != null,\n      onFailure: (_) => null);\n  if (availableLocale == null) {\n    return new SynchronousFuture(false);\n  }\n  var lib = _deferredLibraries[availableLocale];\n  lib == null ? new SynchronousFuture(false) : lib();\n  initializeInternalMessageLookup(() => new CompositeMessageLookup());\n  messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor);\n  return new SynchronousFuture(true);\n}\n\nbool _messagesExistFor(String locale) {\n  try {\n    return _findExact(locale) != null;\n  } catch (e) {\n    return false;\n  }\n}\n\nMessageLookupByLibrary? _findGeneratedMessagesFor(String locale) {\n  var actualLocale =\n      Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null);\n  if (actualLocale == null) return null;\n  return _findExact(actualLocale);\n}\n"
  },
  {
    "path": "lib/gen/intl/messages_en.dart",
    "content": "// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart\n// This is a library that provides messages for a en locale. All the\n// messages from the main program should be duplicated here with the same\n// function name.\n\n// Ignore issues from commonly used lints in this file.\n// ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new\n// ignore_for_file:prefer_single_quotes,comment_references, directives_ordering\n// ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases\n// ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes\n// ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes\n\nimport 'package:intl/intl.dart';\nimport 'package:intl/message_lookup_by_library.dart';\n\nfinal messages = new MessageLookup();\n\ntypedef String MessageIfAbsent(String messageStr, List<dynamic> args);\n\nclass MessageLookup extends MessageLookupByLibrary {\n  String get localeName => 'en';\n\n  static String m0(pages, text) =>\n      \"In the prompt template, the ${pages} placeholder will be replaced with web page content, and the ${text} placeholder will be replaced with the user message. If unsure, leave it empty to use the built-in template.\";\n\n  static String m1(text) =>\n      \"In the prompt template, The ${text} placeholder will be replaced with the user\\'s message. If unsure, leave empty to use the built-in template.\";\n\n  final messages = _notInlinedMessages(_notInlinedMessages);\n  static Map<String, Function> _notInlinedMessages(_) => <String, Function>{\n        \"all_chats\": MessageLookupByLibrary.simpleMessage(\"All Chats\"),\n        \"api\": MessageLookupByLibrary.simpleMessage(\"API\"),\n        \"api_key\": MessageLookupByLibrary.simpleMessage(\"API Key\"),\n        \"api_type\": MessageLookupByLibrary.simpleMessage(\"API Type\"),\n        \"api_url\": MessageLookupByLibrary.simpleMessage(\"API Url\"),\n        \"apis\": MessageLookupByLibrary.simpleMessage(\"APIs\"),\n        \"base_config\": MessageLookupByLibrary.simpleMessage(\"Base Config\"),\n        \"bot\": MessageLookupByLibrary.simpleMessage(\"Bot\"),\n        \"bots\": MessageLookupByLibrary.simpleMessage(\"Bots\"),\n        \"camera\": MessageLookupByLibrary.simpleMessage(\"Camera\"),\n        \"cancel\": MessageLookupByLibrary.simpleMessage(\"Cancel\"),\n        \"cannot_open\": MessageLookupByLibrary.simpleMessage(\"Cannot Open\"),\n        \"chat_image_compress\":\n            MessageLookupByLibrary.simpleMessage(\"Chat Image Compress\"),\n        \"chat_model\": MessageLookupByLibrary.simpleMessage(\"Chat Model\"),\n        \"chat_model_hint\":\n            MessageLookupByLibrary.simpleMessage(\"Is it a Chat Model?\"),\n        \"chat_settings\": MessageLookupByLibrary.simpleMessage(\"Chat Settings\"),\n        \"chat_title\": MessageLookupByLibrary.simpleMessage(\"Chat Title\"),\n        \"check_for_updates\":\n            MessageLookupByLibrary.simpleMessage(\"Check for Updates\"),\n        \"choose_api\": MessageLookupByLibrary.simpleMessage(\"Choose API\"),\n        \"choose_bot\": MessageLookupByLibrary.simpleMessage(\"Choose Bot\"),\n        \"choose_model\": MessageLookupByLibrary.simpleMessage(\"Choose Model\"),\n        \"chunk_n\": MessageLookupByLibrary.simpleMessage(\"Number of Chunks\"),\n        \"chunk_n_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Number of chunks to be integrated into the context\"),\n        \"chunk_overlap\": MessageLookupByLibrary.simpleMessage(\"Chunk Overlap\"),\n        \"chunk_overlap_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Size of the overlapping portion with the previous chunk\"),\n        \"chunk_size\": MessageLookupByLibrary.simpleMessage(\"Chunk Size\"),\n        \"chunk_size_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Maximum number of characters a single chunk can contain\"),\n        \"citations\": MessageLookupByLibrary.simpleMessage(\"Citations\"),\n        \"clear\": MessageLookupByLibrary.simpleMessage(\"Clear\"),\n        \"clear_chat\": MessageLookupByLibrary.simpleMessage(\"Clear Chat\"),\n        \"clear_data\": MessageLookupByLibrary.simpleMessage(\"Clear Data\"),\n        \"clear_data_audio\":\n            MessageLookupByLibrary.simpleMessage(\"All TTS cache files\"),\n        \"clear_data_chat\":\n            MessageLookupByLibrary.simpleMessage(\"All chat history\"),\n        \"clear_data_image\":\n            MessageLookupByLibrary.simpleMessage(\"All generated images\"),\n        \"cleared_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Cleared Successfully\"),\n        \"clearing\": MessageLookupByLibrary.simpleMessage(\"Clearing...\"),\n        \"clone_chat\": MessageLookupByLibrary.simpleMessage(\"Clone Chat\"),\n        \"cloned_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Cloned Successfully\"),\n        \"complete_all_fields\":\n            MessageLookupByLibrary.simpleMessage(\"Please complete all fields\"),\n        \"config\": MessageLookupByLibrary.simpleMessage(\"Config\"),\n        \"config_hint\": MessageLookupByLibrary.simpleMessage(\n            \"To avoid export failures, it\\'s recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.\"),\n        \"config_import_export\":\n            MessageLookupByLibrary.simpleMessage(\"Config Import and Export\"),\n        \"copied_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Copied Successfully\"),\n        \"copy\": MessageLookupByLibrary.simpleMessage(\"Copy\"),\n        \"default_config\":\n            MessageLookupByLibrary.simpleMessage(\"Default Config\"),\n        \"delete\": MessageLookupByLibrary.simpleMessage(\"Delete\"),\n        \"delete_image\": MessageLookupByLibrary.simpleMessage(\"Delete image\"),\n        \"document\": MessageLookupByLibrary.simpleMessage(\"Document\"),\n        \"document_config\":\n            MessageLookupByLibrary.simpleMessage(\"Document Config\"),\n        \"document_config_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.\"),\n        \"download\": MessageLookupByLibrary.simpleMessage(\"Download\"),\n        \"duplicate_api_name\":\n            MessageLookupByLibrary.simpleMessage(\"Duplicate API name\"),\n        \"duplicate_bot_name\":\n            MessageLookupByLibrary.simpleMessage(\"Duplicate Bot name\"),\n        \"edit\": MessageLookupByLibrary.simpleMessage(\"Edit\"),\n        \"embedding_vector\":\n            MessageLookupByLibrary.simpleMessage(\"Embedding Vector\"),\n        \"embedding_vector_info\": MessageLookupByLibrary.simpleMessage(\n            \"Batch size is limited by the API service provider. It\\'s recommended to check and modify accordingly. Vector dimension is an advanced option and should only be filled if necessary.\"),\n        \"empty\": MessageLookupByLibrary.simpleMessage(\"Empty\"),\n        \"empty_link\": MessageLookupByLibrary.simpleMessage(\"Empty Link\"),\n        \"enable\": MessageLookupByLibrary.simpleMessage(\"Enable\"),\n        \"ensure_clear_chat\": MessageLookupByLibrary.simpleMessage(\n            \"Are you sure to clear the chat?\"),\n        \"ensure_delete_image\": MessageLookupByLibrary.simpleMessage(\n            \"Are you sure to delete the image?\"),\n        \"enter_a_name\":\n            MessageLookupByLibrary.simpleMessage(\"Please enter a name\"),\n        \"enter_a_title\":\n            MessageLookupByLibrary.simpleMessage(\"Please enter a title\"),\n        \"enter_message\":\n            MessageLookupByLibrary.simpleMessage(\"Enter your message\"),\n        \"enter_prompts\":\n            MessageLookupByLibrary.simpleMessage(\"Enter your prompts\"),\n        \"error\": MessageLookupByLibrary.simpleMessage(\"Error\"),\n        \"export_chat_as_image\":\n            MessageLookupByLibrary.simpleMessage(\"Export Image\"),\n        \"export_config\": MessageLookupByLibrary.simpleMessage(\"Export Config\"),\n        \"exported_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Exported Successfully\"),\n        \"exporting\": MessageLookupByLibrary.simpleMessage(\"Exporting...\"),\n        \"failed_to_export\": MessageLookupByLibrary.simpleMessage(\n            \"Can\\'t write to that directory.\"),\n        \"gallery\": MessageLookupByLibrary.simpleMessage(\"Gallery\"),\n        \"generate\": MessageLookupByLibrary.simpleMessage(\"Generate\"),\n        \"image_compress_failed\":\n            MessageLookupByLibrary.simpleMessage(\"Failed to comprese image\"),\n        \"image_enable_hint\": MessageLookupByLibrary.simpleMessage(\n            \"The original image will be used if compression fails\"),\n        \"image_generation\":\n            MessageLookupByLibrary.simpleMessage(\"Image Generation\"),\n        \"image_hint\": MessageLookupByLibrary.simpleMessage(\n            \"The Quality should be between 1 and 100, with lower values resulting in higher compression. Minimum Width and Minimum Height restrict image resizing. Leave these fields empty if you\\'re unsure.\"),\n        \"image_quality\": MessageLookupByLibrary.simpleMessage(\"Image Quality\"),\n        \"image_size\": MessageLookupByLibrary.simpleMessage(\"Image Size\"),\n        \"image_style\": MessageLookupByLibrary.simpleMessage(\"Image Style\"),\n        \"images\": MessageLookupByLibrary.simpleMessage(\"Images\"),\n        \"import_config\": MessageLookupByLibrary.simpleMessage(\"Import Config\"),\n        \"imported_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Imported Successfully\"),\n        \"importing\": MessageLookupByLibrary.simpleMessage(\"Importing...\"),\n        \"invalid_max_tokens\":\n            MessageLookupByLibrary.simpleMessage(\"Invalid Max Tokens\"),\n        \"invalid_temperature\":\n            MessageLookupByLibrary.simpleMessage(\"Invalid Temperature\"),\n        \"link\": MessageLookupByLibrary.simpleMessage(\"Link\"),\n        \"max_tokens\": MessageLookupByLibrary.simpleMessage(\"Max Tokens\"),\n        \"min_height\": MessageLookupByLibrary.simpleMessage(\"Minimal Height\"),\n        \"min_width\": MessageLookupByLibrary.simpleMessage(\"Minimal Width\"),\n        \"min_width_height\":\n            MessageLookupByLibrary.simpleMessage(\"Minimal Size\"),\n        \"model\": MessageLookupByLibrary.simpleMessage(\"Model\"),\n        \"model_avatar\": MessageLookupByLibrary.simpleMessage(\"Model Avatar\"),\n        \"model_list\": MessageLookupByLibrary.simpleMessage(\"Model List\"),\n        \"model_name\": MessageLookupByLibrary.simpleMessage(\"Model Name\"),\n        \"name\": MessageLookupByLibrary.simpleMessage(\"Name\"),\n        \"new_api\": MessageLookupByLibrary.simpleMessage(\"New API\"),\n        \"new_bot\": MessageLookupByLibrary.simpleMessage(\"New Bot\"),\n        \"new_chat\": MessageLookupByLibrary.simpleMessage(\"New Chat\"),\n        \"no_model\": MessageLookupByLibrary.simpleMessage(\"no model\"),\n        \"not_implemented_yet\":\n            MessageLookupByLibrary.simpleMessage(\"Not implemented yet\"),\n        \"ok\": MessageLookupByLibrary.simpleMessage(\"Ok\"),\n        \"open\": MessageLookupByLibrary.simpleMessage(\"Open\"),\n        \"optional_config\":\n            MessageLookupByLibrary.simpleMessage(\"Optional Config\"),\n        \"other\": MessageLookupByLibrary.simpleMessage(\"Other\"),\n        \"play\": MessageLookupByLibrary.simpleMessage(\"Play\"),\n        \"please_input\": MessageLookupByLibrary.simpleMessage(\"Please Input\"),\n        \"quality\": MessageLookupByLibrary.simpleMessage(\"Quality\"),\n        \"reanswer\": MessageLookupByLibrary.simpleMessage(\"Reanswer\"),\n        \"reset\": MessageLookupByLibrary.simpleMessage(\"Reset\"),\n        \"restart_app\": MessageLookupByLibrary.simpleMessage(\n            \"Please restart App to load the new settings.\"),\n        \"save\": MessageLookupByLibrary.simpleMessage(\"Save\"),\n        \"saved_successfully\":\n            MessageLookupByLibrary.simpleMessage(\"Saved Successfully\"),\n        \"search_gemini_mode\":\n            MessageLookupByLibrary.simpleMessage(\"Google Search Mode\"),\n        \"search_general_mode\":\n            MessageLookupByLibrary.simpleMessage(\"General Mode\"),\n        \"search_n\": MessageLookupByLibrary.simpleMessage(\"Number of Pages\"),\n        \"search_n_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Maximum number of web pages to retrieve\"),\n        \"search_prompt\": MessageLookupByLibrary.simpleMessage(\"Prompt\"),\n        \"search_prompt_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Template for context synthesis\"),\n        \"search_prompt_info\": m0,\n        \"search_searxng\": MessageLookupByLibrary.simpleMessage(\"SearXNG\"),\n        \"search_searxng_base\": MessageLookupByLibrary.simpleMessage(\"Base URL\"),\n        \"search_searxng_extra\":\n            MessageLookupByLibrary.simpleMessage(\"Additional Parameters\"),\n        \"search_searxng_extra_help\": MessageLookupByLibrary.simpleMessage(\n            \"For example: engines=google&language=en\"),\n        \"search_searxng_hint\":\n            MessageLookupByLibrary.simpleMessage(\"SearXNG instance\"),\n        \"search_timeout\": MessageLookupByLibrary.simpleMessage(\"Timeout\"),\n        \"search_timeout_fetch\":\n            MessageLookupByLibrary.simpleMessage(\"Fetch Timeout\"),\n        \"search_timeout_fetch_help\": MessageLookupByLibrary.simpleMessage(\n            \"Timeout duration for fetching web page content\"),\n        \"search_timeout_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Retrieval timeout in milliseconds\"),\n        \"search_timeout_query\":\n            MessageLookupByLibrary.simpleMessage(\"Query Timeout\"),\n        \"search_timeout_query_help\": MessageLookupByLibrary.simpleMessage(\n            \"Timeout duration for SearXNG requests\"),\n        \"search_vector\":\n            MessageLookupByLibrary.simpleMessage(\"Embedding Vector\"),\n        \"search_vector_hint\":\n            MessageLookupByLibrary.simpleMessage(\"Recommended to enable\"),\n        \"select_models\": MessageLookupByLibrary.simpleMessage(\"Select Models\"),\n        \"settings\": MessageLookupByLibrary.simpleMessage(\"Settings\"),\n        \"setup_api_model_first\": MessageLookupByLibrary.simpleMessage(\n            \"Set up the API and Model first\"),\n        \"setup_searxng_first\":\n            MessageLookupByLibrary.simpleMessage(\"Set up the SearXNG first\"),\n        \"setup_tts_first\":\n            MessageLookupByLibrary.simpleMessage(\"Set up the TTS first\"),\n        \"setup_vector_first\": MessageLookupByLibrary.simpleMessage(\n            \"Set up the embedding vector API and model first\"),\n        \"share\": MessageLookupByLibrary.simpleMessage(\"Share\"),\n        \"source\": MessageLookupByLibrary.simpleMessage(\"Source\"),\n        \"streaming_response\":\n            MessageLookupByLibrary.simpleMessage(\"Streaming Response\"),\n        \"system_prompts\":\n            MessageLookupByLibrary.simpleMessage(\"System Prompts\"),\n        \"task\": MessageLookupByLibrary.simpleMessage(\"Task\"),\n        \"temperature\": MessageLookupByLibrary.simpleMessage(\"Temperature\"),\n        \"text_to_speech\":\n            MessageLookupByLibrary.simpleMessage(\"Text To Speech\"),\n        \"title\": MessageLookupByLibrary.simpleMessage(\"ChatBot\"),\n        \"title_enable_hint\": MessageLookupByLibrary.simpleMessage(\n            \"If disabled, the user\\'s message will be used as the title\"),\n        \"title_generation\":\n            MessageLookupByLibrary.simpleMessage(\"Title Generation\"),\n        \"title_generation_hint\": m1,\n        \"title_prompt\": MessageLookupByLibrary.simpleMessage(\"Prompt\"),\n        \"title_prompt_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Template for the title generation prompt\"),\n        \"up_to_date\":\n            MessageLookupByLibrary.simpleMessage(\"You are up to date\"),\n        \"vector_batch_size\": MessageLookupByLibrary.simpleMessage(\"Batch Size\"),\n        \"vector_batch_size_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Maximum number of chunks that can be submitted in a single request\"),\n        \"vector_dimensions\":\n            MessageLookupByLibrary.simpleMessage(\"Vector Dimensions\"),\n        \"vector_dimensions_hint\": MessageLookupByLibrary.simpleMessage(\n            \"Output dimension of the embedding vector model\"),\n        \"voice\": MessageLookupByLibrary.simpleMessage(\"Voice\"),\n        \"web_search\": MessageLookupByLibrary.simpleMessage(\"Web Search\"),\n        \"workspace\": MessageLookupByLibrary.simpleMessage(\"Workspace\")\n      };\n}\n"
  },
  {
    "path": "lib/gen/intl/messages_zh_CN.dart",
    "content": "// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart\n// This is a library that provides messages for a zh_CN locale. All the\n// messages from the main program should be duplicated here with the same\n// function name.\n\n// Ignore issues from commonly used lints in this file.\n// ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new\n// ignore_for_file:prefer_single_quotes,comment_references, directives_ordering\n// ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases\n// ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes\n// ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes\n\nimport 'package:intl/intl.dart';\nimport 'package:intl/message_lookup_by_library.dart';\n\nfinal messages = new MessageLookup();\n\ntypedef String MessageIfAbsent(String messageStr, List<dynamic> args);\n\nclass MessageLookup extends MessageLookupByLibrary {\n  String get localeName => 'zh_CN';\n\n  static String m0(pages, text) =>\n      \"提示词模板中的 ${pages} 占位变量会被网页内容替换，${text} 占位变量会被用户消息替换。如不清楚，可留空以使用内置模板。\";\n\n  static String m1(text) => \"提示词模板中的 ${text} 占位变量会被用户消息替换。如不清楚，可留空以使用内置模板。\";\n\n  final messages = _notInlinedMessages(_notInlinedMessages);\n  static Map<String, Function> _notInlinedMessages(_) => <String, Function>{\n        \"all_chats\": MessageLookupByLibrary.simpleMessage(\"所有对话\"),\n        \"api\": MessageLookupByLibrary.simpleMessage(\"接口\"),\n        \"api_key\": MessageLookupByLibrary.simpleMessage(\"接口密钥\"),\n        \"api_type\": MessageLookupByLibrary.simpleMessage(\"接口类型\"),\n        \"api_url\": MessageLookupByLibrary.simpleMessage(\"接口地址\"),\n        \"apis\": MessageLookupByLibrary.simpleMessage(\"接口\"),\n        \"base_config\": MessageLookupByLibrary.simpleMessage(\"基本配置\"),\n        \"bot\": MessageLookupByLibrary.simpleMessage(\"角色\"),\n        \"bots\": MessageLookupByLibrary.simpleMessage(\"角色\"),\n        \"camera\": MessageLookupByLibrary.simpleMessage(\"相机\"),\n        \"cancel\": MessageLookupByLibrary.simpleMessage(\"取消\"),\n        \"cannot_open\": MessageLookupByLibrary.simpleMessage(\"无法打开\"),\n        \"chat_image_compress\": MessageLookupByLibrary.simpleMessage(\"对话图片压缩\"),\n        \"chat_model\": MessageLookupByLibrary.simpleMessage(\"对话模型\"),\n        \"chat_model_hint\": MessageLookupByLibrary.simpleMessage(\"是否是对话模型？\"),\n        \"chat_settings\": MessageLookupByLibrary.simpleMessage(\"对话设置\"),\n        \"chat_title\": MessageLookupByLibrary.simpleMessage(\"对话标题\"),\n        \"check_for_updates\": MessageLookupByLibrary.simpleMessage(\"检查更新\"),\n        \"choose_api\": MessageLookupByLibrary.simpleMessage(\"选择接口\"),\n        \"choose_bot\": MessageLookupByLibrary.simpleMessage(\"选择角色\"),\n        \"choose_model\": MessageLookupByLibrary.simpleMessage(\"选择模型\"),\n        \"chunk_n\": MessageLookupByLibrary.simpleMessage(\"块数量\"),\n        \"chunk_n_hint\": MessageLookupByLibrary.simpleMessage(\"集成到上下文中的块数量\"),\n        \"chunk_overlap\": MessageLookupByLibrary.simpleMessage(\"块重叠\"),\n        \"chunk_overlap_hint\":\n            MessageLookupByLibrary.simpleMessage(\"与上一块重叠部分的大小\"),\n        \"chunk_size\": MessageLookupByLibrary.simpleMessage(\"块大小\"),\n        \"chunk_size_hint\": MessageLookupByLibrary.simpleMessage(\"单块能包含的最大字符数\"),\n        \"citations\": MessageLookupByLibrary.simpleMessage(\"引用\"),\n        \"clear\": MessageLookupByLibrary.simpleMessage(\"清空\"),\n        \"clear_chat\": MessageLookupByLibrary.simpleMessage(\"清空对话\"),\n        \"clear_data\": MessageLookupByLibrary.simpleMessage(\"清理数据\"),\n        \"clear_data_audio\": MessageLookupByLibrary.simpleMessage(\"所有的 TTS 缓存\"),\n        \"clear_data_chat\": MessageLookupByLibrary.simpleMessage(\"所有的对话数据\"),\n        \"clear_data_image\": MessageLookupByLibrary.simpleMessage(\"所有的图片生成结果\"),\n        \"cleared_successfully\": MessageLookupByLibrary.simpleMessage(\"清理成功\"),\n        \"clearing\": MessageLookupByLibrary.simpleMessage(\"清理中...\"),\n        \"clone_chat\": MessageLookupByLibrary.simpleMessage(\"复制对话\"),\n        \"cloned_successfully\": MessageLookupByLibrary.simpleMessage(\"复制成功\"),\n        \"complete_all_fields\": MessageLookupByLibrary.simpleMessage(\"请填写所有字段\"),\n        \"config\": MessageLookupByLibrary.simpleMessage(\"配置\"),\n        \"config_hint\": MessageLookupByLibrary.simpleMessage(\n            \"为避免导出失败，建议将配置导出到 Documents 目录，或在 Download 下创建 ChatBot 子目录。\"),\n        \"config_import_export\": MessageLookupByLibrary.simpleMessage(\"配置导入导出\"),\n        \"copied_successfully\": MessageLookupByLibrary.simpleMessage(\"拷贝成功\"),\n        \"copy\": MessageLookupByLibrary.simpleMessage(\"拷贝\"),\n        \"default_config\": MessageLookupByLibrary.simpleMessage(\"默认配置\"),\n        \"delete\": MessageLookupByLibrary.simpleMessage(\"删除\"),\n        \"delete_image\": MessageLookupByLibrary.simpleMessage(\"删除图片\"),\n        \"document\": MessageLookupByLibrary.simpleMessage(\"文档\"),\n        \"document_config\": MessageLookupByLibrary.simpleMessage(\"文档配置\"),\n        \"document_config_hint\": MessageLookupByLibrary.simpleMessage(\n            \"文档会被划分为若干块，经过搜索比较后，最合适的几个块会被补充进上下文。\"),\n        \"download\": MessageLookupByLibrary.simpleMessage(\"下载\"),\n        \"duplicate_api_name\": MessageLookupByLibrary.simpleMessage(\"接口名重复\"),\n        \"duplicate_bot_name\": MessageLookupByLibrary.simpleMessage(\"角色名重复\"),\n        \"edit\": MessageLookupByLibrary.simpleMessage(\"编辑\"),\n        \"embedding_vector\": MessageLookupByLibrary.simpleMessage(\"嵌入向量\"),\n        \"embedding_vector_info\": MessageLookupByLibrary.simpleMessage(\n            \"批大小受限于接口服务商，建议查询后修改。向量维度为专业选项，非必要请勿填写。\"),\n        \"empty\": MessageLookupByLibrary.simpleMessage(\"空\"),\n        \"empty_link\": MessageLookupByLibrary.simpleMessage(\"空链接\"),\n        \"enable\": MessageLookupByLibrary.simpleMessage(\"启用\"),\n        \"ensure_clear_chat\": MessageLookupByLibrary.simpleMessage(\"确定要清空对话？\"),\n        \"ensure_delete_image\": MessageLookupByLibrary.simpleMessage(\"确定要删除图片？\"),\n        \"enter_a_name\": MessageLookupByLibrary.simpleMessage(\"请输入名称\"),\n        \"enter_a_title\": MessageLookupByLibrary.simpleMessage(\"请输入标题\"),\n        \"enter_message\": MessageLookupByLibrary.simpleMessage(\"输入你的消息\"),\n        \"enter_prompts\": MessageLookupByLibrary.simpleMessage(\"请输入提示词\"),\n        \"error\": MessageLookupByLibrary.simpleMessage(\"错误\"),\n        \"export_chat_as_image\": MessageLookupByLibrary.simpleMessage(\"导出图片\"),\n        \"export_config\": MessageLookupByLibrary.simpleMessage(\"导出配置\"),\n        \"exported_successfully\": MessageLookupByLibrary.simpleMessage(\"导出成功\"),\n        \"exporting\": MessageLookupByLibrary.simpleMessage(\"正在导出...\"),\n        \"failed_to_export\":\n            MessageLookupByLibrary.simpleMessage(\"无法在该目录下写入文件。\"),\n        \"gallery\": MessageLookupByLibrary.simpleMessage(\"图库\"),\n        \"generate\": MessageLookupByLibrary.simpleMessage(\"生成\"),\n        \"image_compress_failed\": MessageLookupByLibrary.simpleMessage(\"图片压缩失败\"),\n        \"image_enable_hint\": MessageLookupByLibrary.simpleMessage(\"压缩失败则将使用原图\"),\n        \"image_generation\": MessageLookupByLibrary.simpleMessage(\"图像生成\"),\n        \"image_hint\": MessageLookupByLibrary.simpleMessage(\n            \"质量范围应在 1-100，质量越低压缩率越高。最小宽度与最小高度用于限制图片缩放，如不清楚，请留空。\"),\n        \"image_quality\": MessageLookupByLibrary.simpleMessage(\"图像质量\"),\n        \"image_size\": MessageLookupByLibrary.simpleMessage(\"图像尺寸\"),\n        \"image_style\": MessageLookupByLibrary.simpleMessage(\"图像风格\"),\n        \"images\": MessageLookupByLibrary.simpleMessage(\"图片\"),\n        \"import_config\": MessageLookupByLibrary.simpleMessage(\"导入配置\"),\n        \"imported_successfully\": MessageLookupByLibrary.simpleMessage(\"导入成功\"),\n        \"importing\": MessageLookupByLibrary.simpleMessage(\"正在导入...\"),\n        \"invalid_max_tokens\": MessageLookupByLibrary.simpleMessage(\"非法的最大输出\"),\n        \"invalid_temperature\": MessageLookupByLibrary.simpleMessage(\"非法的温度\"),\n        \"link\": MessageLookupByLibrary.simpleMessage(\"链接\"),\n        \"max_tokens\": MessageLookupByLibrary.simpleMessage(\"最大输出\"),\n        \"min_height\": MessageLookupByLibrary.simpleMessage(\"最小高度\"),\n        \"min_width\": MessageLookupByLibrary.simpleMessage(\"最小宽度\"),\n        \"min_width_height\": MessageLookupByLibrary.simpleMessage(\"最小宽高\"),\n        \"model\": MessageLookupByLibrary.simpleMessage(\"模型\"),\n        \"model_avatar\": MessageLookupByLibrary.simpleMessage(\"模型头像\"),\n        \"model_list\": MessageLookupByLibrary.simpleMessage(\"模型列表\"),\n        \"model_name\": MessageLookupByLibrary.simpleMessage(\"模型名称\"),\n        \"name\": MessageLookupByLibrary.simpleMessage(\"名称\"),\n        \"new_api\": MessageLookupByLibrary.simpleMessage(\"新接口\"),\n        \"new_bot\": MessageLookupByLibrary.simpleMessage(\"新角色\"),\n        \"new_chat\": MessageLookupByLibrary.simpleMessage(\"新对话\"),\n        \"no_model\": MessageLookupByLibrary.simpleMessage(\"无模型\"),\n        \"not_implemented_yet\": MessageLookupByLibrary.simpleMessage(\"还未实现\"),\n        \"ok\": MessageLookupByLibrary.simpleMessage(\"确定\"),\n        \"open\": MessageLookupByLibrary.simpleMessage(\"打开\"),\n        \"optional_config\": MessageLookupByLibrary.simpleMessage(\"可选配置\"),\n        \"other\": MessageLookupByLibrary.simpleMessage(\"其他\"),\n        \"play\": MessageLookupByLibrary.simpleMessage(\"播放\"),\n        \"please_input\": MessageLookupByLibrary.simpleMessage(\"请输入\"),\n        \"quality\": MessageLookupByLibrary.simpleMessage(\"质量\"),\n        \"reanswer\": MessageLookupByLibrary.simpleMessage(\"重答\"),\n        \"reset\": MessageLookupByLibrary.simpleMessage(\"重置\"),\n        \"restart_app\": MessageLookupByLibrary.simpleMessage(\"请重启应用以加载新配置。\"),\n        \"save\": MessageLookupByLibrary.simpleMessage(\"保存\"),\n        \"saved_successfully\": MessageLookupByLibrary.simpleMessage(\"保存成功\"),\n        \"search_gemini_mode\":\n            MessageLookupByLibrary.simpleMessage(\"Google Search 模式\"),\n        \"search_general_mode\": MessageLookupByLibrary.simpleMessage(\"通用模式\"),\n        \"search_n\": MessageLookupByLibrary.simpleMessage(\"网页数量\"),\n        \"search_n_hint\": MessageLookupByLibrary.simpleMessage(\"检索的网页数量上限\"),\n        \"search_prompt\": MessageLookupByLibrary.simpleMessage(\"提示词\"),\n        \"search_prompt_hint\":\n            MessageLookupByLibrary.simpleMessage(\"用于合成上下文的提示词模板\"),\n        \"search_prompt_info\": m0,\n        \"search_searxng\": MessageLookupByLibrary.simpleMessage(\"SearXNG\"),\n        \"search_searxng_base\": MessageLookupByLibrary.simpleMessage(\"根地址\"),\n        \"search_searxng_extra\": MessageLookupByLibrary.simpleMessage(\"附加参数\"),\n        \"search_searxng_extra_help\": MessageLookupByLibrary.simpleMessage(\n            \"例如：engines=google&language=zh\"),\n        \"search_searxng_hint\":\n            MessageLookupByLibrary.simpleMessage(\"SearXNG 实例\"),\n        \"search_timeout\": MessageLookupByLibrary.simpleMessage(\"超时时间\"),\n        \"search_timeout_fetch\": MessageLookupByLibrary.simpleMessage(\"抓取超时\"),\n        \"search_timeout_fetch_help\":\n            MessageLookupByLibrary.simpleMessage(\"抓取网页内容的超时时间\"),\n        \"search_timeout_hint\": MessageLookupByLibrary.simpleMessage(\"检索的超时毫秒数\"),\n        \"search_timeout_query\": MessageLookupByLibrary.simpleMessage(\"检索超时\"),\n        \"search_timeout_query_help\":\n            MessageLookupByLibrary.simpleMessage(\"请求 SearXNG 的超时时间\"),\n        \"search_vector\": MessageLookupByLibrary.simpleMessage(\"嵌入向量\"),\n        \"search_vector_hint\": MessageLookupByLibrary.simpleMessage(\"建议开启\"),\n        \"select_models\": MessageLookupByLibrary.simpleMessage(\"选择模型\"),\n        \"settings\": MessageLookupByLibrary.simpleMessage(\"设置\"),\n        \"setup_api_model_first\":\n            MessageLookupByLibrary.simpleMessage(\"请先配置接口和模型\"),\n        \"setup_searxng_first\":\n            MessageLookupByLibrary.simpleMessage(\"请先配置 SearXNG 实例\"),\n        \"setup_tts_first\": MessageLookupByLibrary.simpleMessage(\"请先配置文本转语音\"),\n        \"setup_vector_first\":\n            MessageLookupByLibrary.simpleMessage(\"请先配置嵌入向量接口和模型\"),\n        \"share\": MessageLookupByLibrary.simpleMessage(\"分享\"),\n        \"source\": MessageLookupByLibrary.simpleMessage(\"源码\"),\n        \"streaming_response\": MessageLookupByLibrary.simpleMessage(\"流式响应\"),\n        \"system_prompts\": MessageLookupByLibrary.simpleMessage(\"系统提示词\"),\n        \"task\": MessageLookupByLibrary.simpleMessage(\"任务\"),\n        \"temperature\": MessageLookupByLibrary.simpleMessage(\"温度\"),\n        \"text_to_speech\": MessageLookupByLibrary.simpleMessage(\"文本转语音\"),\n        \"title\": MessageLookupByLibrary.simpleMessage(\"ChatBot\"),\n        \"title_enable_hint\":\n            MessageLookupByLibrary.simpleMessage(\"禁用则将以用户消息为标题\"),\n        \"title_generation\": MessageLookupByLibrary.simpleMessage(\"标题生成\"),\n        \"title_generation_hint\": m1,\n        \"title_prompt\": MessageLookupByLibrary.simpleMessage(\"提示词\"),\n        \"title_prompt_hint\":\n            MessageLookupByLibrary.simpleMessage(\"用于生成标题的提示词模板\"),\n        \"up_to_date\": MessageLookupByLibrary.simpleMessage(\"已是最新版本\"),\n        \"vector_batch_size\": MessageLookupByLibrary.simpleMessage(\"批大小\"),\n        \"vector_batch_size_hint\":\n            MessageLookupByLibrary.simpleMessage(\"单次请求能提交的最大块数量\"),\n        \"vector_dimensions\": MessageLookupByLibrary.simpleMessage(\"向量维度\"),\n        \"vector_dimensions_hint\":\n            MessageLookupByLibrary.simpleMessage(\"嵌入向量模型输出向量的维度\"),\n        \"voice\": MessageLookupByLibrary.simpleMessage(\"音色\"),\n        \"web_search\": MessageLookupByLibrary.simpleMessage(\"联网搜索\"),\n        \"workspace\": MessageLookupByLibrary.simpleMessage(\"工作空间\")\n      };\n}\n"
  },
  {
    "path": "lib/gen/l10n.dart",
    "content": "// GENERATED CODE - DO NOT MODIFY BY HAND\nimport 'package:flutter/material.dart';\nimport 'package:intl/intl.dart';\nimport 'intl/messages_all.dart';\n\n// **************************************************************************\n// Generator: Flutter Intl IDE plugin\n// Made by Localizely\n// **************************************************************************\n\n// ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars\n// ignore_for_file: join_return_with_assignment, prefer_final_in_for_each\n// ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes\n\nclass S {\n  S();\n\n  static S? _current;\n\n  static S get current {\n    assert(_current != null,\n        'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.');\n    return _current!;\n  }\n\n  static const AppLocalizationDelegate delegate = AppLocalizationDelegate();\n\n  static Future<S> load(Locale locale) {\n    final name = (locale.countryCode?.isEmpty ?? false)\n        ? locale.languageCode\n        : locale.toString();\n    final localeName = Intl.canonicalizedLocale(name);\n    return initializeMessages(localeName).then((_) {\n      Intl.defaultLocale = localeName;\n      final instance = S();\n      S._current = instance;\n\n      return instance;\n    });\n  }\n\n  static S of(BuildContext context) {\n    final instance = S.maybeOf(context);\n    assert(instance != null,\n        'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?');\n    return instance!;\n  }\n\n  static S? maybeOf(BuildContext context) {\n    return Localizations.of<S>(context, S);\n  }\n\n  /// `ChatBot`\n  String get title {\n    return Intl.message(\n      'ChatBot',\n      name: 'title',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Ok`\n  String get ok {\n    return Intl.message(\n      'Ok',\n      name: 'ok',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Copy`\n  String get copy {\n    return Intl.message(\n      'Copy',\n      name: 'copy',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Edit`\n  String get edit {\n    return Intl.message(\n      'Edit',\n      name: 'edit',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Play`\n  String get play {\n    return Intl.message(\n      'Play',\n      name: 'play',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Source`\n  String get source {\n    return Intl.message(\n      'Source',\n      name: 'source',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Delete`\n  String get delete {\n    return Intl.message(\n      'Delete',\n      name: 'delete',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Images`\n  String get images {\n    return Intl.message(\n      'Images',\n      name: 'images',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Camera`\n  String get camera {\n    return Intl.message(\n      'Camera',\n      name: 'camera',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Gallery`\n  String get gallery {\n    return Intl.message(\n      'Gallery',\n      name: 'gallery',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Settings`\n  String get settings {\n    return Intl.message(\n      'Settings',\n      name: 'settings',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Bot`\n  String get bot {\n    return Intl.message(\n      'Bot',\n      name: 'bot',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Bots`\n  String get bots {\n    return Intl.message(\n      'Bots',\n      name: 'bots',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `APIs`\n  String get apis {\n    return Intl.message(\n      'APIs',\n      name: 'apis',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Config`\n  String get config {\n    return Intl.message(\n      'Config',\n      name: 'config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Open`\n  String get open {\n    return Intl.message(\n      'Open',\n      name: 'open',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Save`\n  String get save {\n    return Intl.message(\n      'Save',\n      name: 'save',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Reset`\n  String get reset {\n    return Intl.message(\n      'Reset',\n      name: 'reset',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Error`\n  String get error {\n    return Intl.message(\n      'Error',\n      name: 'error',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Share`\n  String get share {\n    return Intl.message(\n      'Share',\n      name: 'share',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Clear`\n  String get clear {\n    return Intl.message(\n      'Clear',\n      name: 'clear',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Cancel`\n  String get cancel {\n    return Intl.message(\n      'Cancel',\n      name: 'cancel',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Reanswer`\n  String get reanswer {\n    return Intl.message(\n      'Reanswer',\n      name: 'reanswer',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Citations`\n  String get citations {\n    return Intl.message(\n      'Citations',\n      name: 'citations',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `API`\n  String get api {\n    return Intl.message(\n      'API',\n      name: 'api',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Model`\n  String get model {\n    return Intl.message(\n      'Model',\n      name: 'model',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Voice`\n  String get voice {\n    return Intl.message(\n      'Voice',\n      name: 'voice',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Max Tokens`\n  String get max_tokens {\n    return Intl.message(\n      'Max Tokens',\n      name: 'max_tokens',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Temperature`\n  String get temperature {\n    return Intl.message(\n      'Temperature',\n      name: 'temperature',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `System Prompts`\n  String get system_prompts {\n    return Intl.message(\n      'System Prompts',\n      name: 'system_prompts',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Streaming Response`\n  String get streaming_response {\n    return Intl.message(\n      'Streaming Response',\n      name: 'streaming_response',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Link`\n  String get link {\n    return Intl.message(\n      'Link',\n      name: 'link',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Name`\n  String get name {\n    return Intl.message(\n      'Name',\n      name: 'name',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `New Bot`\n  String get new_bot {\n    return Intl.message(\n      'New Bot',\n      name: 'new_bot',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `New API`\n  String get new_api {\n    return Intl.message(\n      'New API',\n      name: 'new_api',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `New Chat`\n  String get new_chat {\n    return Intl.message(\n      'New Chat',\n      name: 'new_chat',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `API Url`\n  String get api_url {\n    return Intl.message(\n      'API Url',\n      name: 'api_url',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `API Key`\n  String get api_key {\n    return Intl.message(\n      'API Key',\n      name: 'api_key',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `API Type`\n  String get api_type {\n    return Intl.message(\n      'API Type',\n      name: 'api_type',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Model List`\n  String get model_list {\n    return Intl.message(\n      'Model List',\n      name: 'model_list',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Select Models`\n  String get select_models {\n    return Intl.message(\n      'Select Models',\n      name: 'select_models',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Please enter a name`\n  String get enter_a_name {\n    return Intl.message(\n      'Please enter a name',\n      name: 'enter_a_name',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Please enter a title`\n  String get enter_a_title {\n    return Intl.message(\n      'Please enter a title',\n      name: 'enter_a_title',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Duplicate Bot name`\n  String get duplicate_bot_name {\n    return Intl.message(\n      'Duplicate Bot name',\n      name: 'duplicate_bot_name',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Duplicate API name`\n  String get duplicate_api_name {\n    return Intl.message(\n      'Duplicate API name',\n      name: 'duplicate_api_name',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Please complete all fields`\n  String get complete_all_fields {\n    return Intl.message(\n      'Please complete all fields',\n      name: 'complete_all_fields',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `no model`\n  String get no_model {\n    return Intl.message(\n      'no model',\n      name: 'no_model',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `All Chats`\n  String get all_chats {\n    return Intl.message(\n      'All Chats',\n      name: 'all_chats',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chat Title`\n  String get chat_title {\n    return Intl.message(\n      'Chat Title',\n      name: 'chat_title',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Default Config`\n  String get default_config {\n    return Intl.message(\n      'Default Config',\n      name: 'default_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Text To Speech`\n  String get text_to_speech {\n    return Intl.message(\n      'Text To Speech',\n      name: 'text_to_speech',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chat Image Compress`\n  String get chat_image_compress {\n    return Intl.message(\n      'Chat Image Compress',\n      name: 'chat_image_compress',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Config Import and Export`\n  String get config_import_export {\n    return Intl.message(\n      'Config Import and Export',\n      name: 'config_import_export',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Choose Bot`\n  String get choose_bot {\n    return Intl.message(\n      'Choose Bot',\n      name: 'choose_bot',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Choose API`\n  String get choose_api {\n    return Intl.message(\n      'Choose API',\n      name: 'choose_api',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Choose Model`\n  String get choose_model {\n    return Intl.message(\n      'Choose Model',\n      name: 'choose_model',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Quality`\n  String get quality {\n    return Intl.message(\n      'Quality',\n      name: 'quality',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Minimal Width`\n  String get min_width {\n    return Intl.message(\n      'Minimal Width',\n      name: 'min_width',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Minimal Height`\n  String get min_height {\n    return Intl.message(\n      'Minimal Height',\n      name: 'min_height',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Minimal Size`\n  String get min_width_height {\n    return Intl.message(\n      'Minimal Size',\n      name: 'min_width_height',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Export Config`\n  String get export_config {\n    return Intl.message(\n      'Export Config',\n      name: 'export_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Import Config`\n  String get import_config {\n    return Intl.message(\n      'Import Config',\n      name: 'import_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Exporting...`\n  String get exporting {\n    return Intl.message(\n      'Exporting...',\n      name: 'exporting',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Importing...`\n  String get importing {\n    return Intl.message(\n      'Importing...',\n      name: 'importing',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Empty`\n  String get empty {\n    return Intl.message(\n      'Empty',\n      name: 'empty',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Enable`\n  String get enable {\n    return Intl.message(\n      'Enable',\n      name: 'enable',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Please Input`\n  String get please_input {\n    return Intl.message(\n      'Please Input',\n      name: 'please_input',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `The original image will be used if compression fails`\n  String get image_enable_hint {\n    return Intl.message(\n      'The original image will be used if compression fails',\n      name: 'image_enable_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `The Quality should be between 1 and 100, with lower values resulting in higher compression. Minimum Width and Minimum Height restrict image resizing. Leave these fields empty if you're unsure.`\n  String get image_hint {\n    return Intl.message(\n      'The Quality should be between 1 and 100, with lower values resulting in higher compression. Minimum Width and Minimum Height restrict image resizing. Leave these fields empty if you\\'re unsure.',\n      name: 'image_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `To avoid export failures, it's recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.`\n  String get config_hint {\n    return Intl.message(\n      'To avoid export failures, it\\'s recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.',\n      name: 'config_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Exported Successfully`\n  String get exported_successfully {\n    return Intl.message(\n      'Exported Successfully',\n      name: 'exported_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Imported Successfully`\n  String get imported_successfully {\n    return Intl.message(\n      'Imported Successfully',\n      name: 'imported_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Please restart App to load the new settings.`\n  String get restart_app {\n    return Intl.message(\n      'Please restart App to load the new settings.',\n      name: 'restart_app',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Can't write to that directory.`\n  String get failed_to_export {\n    return Intl.message(\n      'Can\\'t write to that directory.',\n      name: 'failed_to_export',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Generate`\n  String get generate {\n    return Intl.message(\n      'Generate',\n      name: 'generate',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Image Size`\n  String get image_size {\n    return Intl.message(\n      'Image Size',\n      name: 'image_size',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Image Style`\n  String get image_style {\n    return Intl.message(\n      'Image Style',\n      name: 'image_style',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Image Quality`\n  String get image_quality {\n    return Intl.message(\n      'Image Quality',\n      name: 'image_quality',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Base Config`\n  String get base_config {\n    return Intl.message(\n      'Base Config',\n      name: 'base_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Optional Config`\n  String get optional_config {\n    return Intl.message(\n      'Optional Config',\n      name: 'optional_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Image Generation`\n  String get image_generation {\n    return Intl.message(\n      'Image Generation',\n      name: 'image_generation',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Enter your prompts`\n  String get enter_prompts {\n    return Intl.message(\n      'Enter your prompts',\n      name: 'enter_prompts',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Clone Chat`\n  String get clone_chat {\n    return Intl.message(\n      'Clone Chat',\n      name: 'clone_chat',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Clear Chat`\n  String get clear_chat {\n    return Intl.message(\n      'Clear Chat',\n      name: 'clear_chat',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chat Settings`\n  String get chat_settings {\n    return Intl.message(\n      'Chat Settings',\n      name: 'chat_settings',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Export Image`\n  String get export_chat_as_image {\n    return Intl.message(\n      'Export Image',\n      name: 'export_chat_as_image',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Cloned Successfully`\n  String get cloned_successfully {\n    return Intl.message(\n      'Cloned Successfully',\n      name: 'cloned_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Are you sure to clear the chat?`\n  String get ensure_clear_chat {\n    return Intl.message(\n      'Are you sure to clear the chat?',\n      name: 'ensure_clear_chat',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Saved Successfully`\n  String get saved_successfully {\n    return Intl.message(\n      'Saved Successfully',\n      name: 'saved_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Copied Successfully`\n  String get copied_successfully {\n    return Intl.message(\n      'Copied Successfully',\n      name: 'copied_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Not implemented yet`\n  String get not_implemented_yet {\n    return Intl.message(\n      'Not implemented yet',\n      name: 'not_implemented_yet',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Empty Link`\n  String get empty_link {\n    return Intl.message(\n      'Empty Link',\n      name: 'empty_link',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Cannot Open`\n  String get cannot_open {\n    return Intl.message(\n      'Cannot Open',\n      name: 'cannot_open',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Invalid Max Tokens`\n  String get invalid_max_tokens {\n    return Intl.message(\n      'Invalid Max Tokens',\n      name: 'invalid_max_tokens',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Invalid Temperature`\n  String get invalid_temperature {\n    return Intl.message(\n      'Invalid Temperature',\n      name: 'invalid_temperature',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Enter your message`\n  String get enter_message {\n    return Intl.message(\n      'Enter your message',\n      name: 'enter_message',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Failed to comprese image`\n  String get image_compress_failed {\n    return Intl.message(\n      'Failed to comprese image',\n      name: 'image_compress_failed',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Set up the TTS first`\n  String get setup_tts_first {\n    return Intl.message(\n      'Set up the TTS first',\n      name: 'setup_tts_first',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Set up the API and Model first`\n  String get setup_api_model_first {\n    return Intl.message(\n      'Set up the API and Model first',\n      name: 'setup_api_model_first',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Other`\n  String get other {\n    return Intl.message(\n      'Other',\n      name: 'other',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Download`\n  String get download {\n    return Intl.message(\n      'Download',\n      name: 'download',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `You are up to date`\n  String get up_to_date {\n    return Intl.message(\n      'You are up to date',\n      name: 'up_to_date',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Check for Updates`\n  String get check_for_updates {\n    return Intl.message(\n      'Check for Updates',\n      name: 'check_for_updates',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Delete image`\n  String get delete_image {\n    return Intl.message(\n      'Delete image',\n      name: 'delete_image',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Are you sure to delete the image?`\n  String get ensure_delete_image {\n    return Intl.message(\n      'Are you sure to delete the image?',\n      name: 'ensure_delete_image',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Task`\n  String get task {\n    return Intl.message(\n      'Task',\n      name: 'task',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Document`\n  String get document {\n    return Intl.message(\n      'Document',\n      name: 'document',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Workspace`\n  String get workspace {\n    return Intl.message(\n      'Workspace',\n      name: 'workspace',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chat Model`\n  String get chat_model {\n    return Intl.message(\n      'Chat Model',\n      name: 'chat_model',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Model Name`\n  String get model_name {\n    return Intl.message(\n      'Model Name',\n      name: 'model_name',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Model Avatar`\n  String get model_avatar {\n    return Intl.message(\n      'Model Avatar',\n      name: 'model_avatar',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Is it a Chat Model?`\n  String get chat_model_hint {\n    return Intl.message(\n      'Is it a Chat Model?',\n      name: 'chat_model_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Title Generation`\n  String get title_generation {\n    return Intl.message(\n      'Title Generation',\n      name: 'title_generation',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `If disabled, the user's message will be used as the title`\n  String get title_enable_hint {\n    return Intl.message(\n      'If disabled, the user\\'s message will be used as the title',\n      name: 'title_enable_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Prompt`\n  String get title_prompt {\n    return Intl.message(\n      'Prompt',\n      name: 'title_prompt',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Template for the title generation prompt`\n  String get title_prompt_hint {\n    return Intl.message(\n      'Template for the title generation prompt',\n      name: 'title_prompt_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `In the prompt template, The {text} placeholder will be replaced with the user's message. If unsure, leave empty to use the built-in template.`\n  String title_generation_hint(Object text) {\n    return Intl.message(\n      'In the prompt template, The $text placeholder will be replaced with the user\\'s message. If unsure, leave empty to use the built-in template.',\n      name: 'title_generation_hint',\n      desc: '',\n      args: [text],\n    );\n  }\n\n  /// `Clearing...`\n  String get clearing {\n    return Intl.message(\n      'Clearing...',\n      name: 'clearing',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Clear Data`\n  String get clear_data {\n    return Intl.message(\n      'Clear Data',\n      name: 'clear_data',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Cleared Successfully`\n  String get cleared_successfully {\n    return Intl.message(\n      'Cleared Successfully',\n      name: 'cleared_successfully',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `All chat history`\n  String get clear_data_chat {\n    return Intl.message(\n      'All chat history',\n      name: 'clear_data_chat',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `All TTS cache files`\n  String get clear_data_audio {\n    return Intl.message(\n      'All TTS cache files',\n      name: 'clear_data_audio',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `All generated images`\n  String get clear_data_image {\n    return Intl.message(\n      'All generated images',\n      name: 'clear_data_image',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Set up the embedding vector API and model first`\n  String get setup_vector_first {\n    return Intl.message(\n      'Set up the embedding vector API and model first',\n      name: 'setup_vector_first',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Embedding Vector`\n  String get search_vector {\n    return Intl.message(\n      'Embedding Vector',\n      name: 'search_vector',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Recommended to enable`\n  String get search_vector_hint {\n    return Intl.message(\n      'Recommended to enable',\n      name: 'search_vector_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Timeout`\n  String get search_timeout {\n    return Intl.message(\n      'Timeout',\n      name: 'search_timeout',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Retrieval timeout in milliseconds`\n  String get search_timeout_hint {\n    return Intl.message(\n      'Retrieval timeout in milliseconds',\n      name: 'search_timeout_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Base URL`\n  String get search_searxng_base {\n    return Intl.message(\n      'Base URL',\n      name: 'search_searxng_base',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Additional Parameters`\n  String get search_searxng_extra {\n    return Intl.message(\n      'Additional Parameters',\n      name: 'search_searxng_extra',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `For example: engines=google&language=en`\n  String get search_searxng_extra_help {\n    return Intl.message(\n      'For example: engines=google&language=en',\n      name: 'search_searxng_extra_help',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Query Timeout`\n  String get search_timeout_query {\n    return Intl.message(\n      'Query Timeout',\n      name: 'search_timeout_query',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Timeout duration for SearXNG requests`\n  String get search_timeout_query_help {\n    return Intl.message(\n      'Timeout duration for SearXNG requests',\n      name: 'search_timeout_query_help',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Fetch Timeout`\n  String get search_timeout_fetch {\n    return Intl.message(\n      'Fetch Timeout',\n      name: 'search_timeout_fetch',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Timeout duration for fetching web page content`\n  String get search_timeout_fetch_help {\n    return Intl.message(\n      'Timeout duration for fetching web page content',\n      name: 'search_timeout_fetch_help',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Embedding Vector`\n  String get embedding_vector {\n    return Intl.message(\n      'Embedding Vector',\n      name: 'embedding_vector',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Batch Size`\n  String get vector_batch_size {\n    return Intl.message(\n      'Batch Size',\n      name: 'vector_batch_size',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Maximum number of chunks that can be submitted in a single request`\n  String get vector_batch_size_hint {\n    return Intl.message(\n      'Maximum number of chunks that can be submitted in a single request',\n      name: 'vector_batch_size_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Vector Dimensions`\n  String get vector_dimensions {\n    return Intl.message(\n      'Vector Dimensions',\n      name: 'vector_dimensions',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Output dimension of the embedding vector model`\n  String get vector_dimensions_hint {\n    return Intl.message(\n      'Output dimension of the embedding vector model',\n      name: 'vector_dimensions_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Batch size is limited by the API service provider. It's recommended to check and modify accordingly. Vector dimension is an advanced option and should only be filled if necessary.`\n  String get embedding_vector_info {\n    return Intl.message(\n      'Batch size is limited by the API service provider. It\\'s recommended to check and modify accordingly. Vector dimension is an advanced option and should only be filled if necessary.',\n      name: 'embedding_vector_info',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Document Config`\n  String get document_config {\n    return Intl.message(\n      'Document Config',\n      name: 'document_config',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Number of Chunks`\n  String get chunk_n {\n    return Intl.message(\n      'Number of Chunks',\n      name: 'chunk_n',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Number of chunks to be integrated into the context`\n  String get chunk_n_hint {\n    return Intl.message(\n      'Number of chunks to be integrated into the context',\n      name: 'chunk_n_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chunk Size`\n  String get chunk_size {\n    return Intl.message(\n      'Chunk Size',\n      name: 'chunk_size',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Maximum number of characters a single chunk can contain`\n  String get chunk_size_hint {\n    return Intl.message(\n      'Maximum number of characters a single chunk can contain',\n      name: 'chunk_size_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Chunk Overlap`\n  String get chunk_overlap {\n    return Intl.message(\n      'Chunk Overlap',\n      name: 'chunk_overlap',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Size of the overlapping portion with the previous chunk`\n  String get chunk_overlap_hint {\n    return Intl.message(\n      'Size of the overlapping portion with the previous chunk',\n      name: 'chunk_overlap_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.`\n  String get document_config_hint {\n    return Intl.message(\n      'Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.',\n      name: 'document_config_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Set up the SearXNG first`\n  String get setup_searxng_first {\n    return Intl.message(\n      'Set up the SearXNG first',\n      name: 'setup_searxng_first',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Google Search Mode`\n  String get search_gemini_mode {\n    return Intl.message(\n      'Google Search Mode',\n      name: 'search_gemini_mode',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `General Mode`\n  String get search_general_mode {\n    return Intl.message(\n      'General Mode',\n      name: 'search_general_mode',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Web Search`\n  String get web_search {\n    return Intl.message(\n      'Web Search',\n      name: 'web_search',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `SearXNG`\n  String get search_searxng {\n    return Intl.message(\n      'SearXNG',\n      name: 'search_searxng',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `SearXNG instance`\n  String get search_searxng_hint {\n    return Intl.message(\n      'SearXNG instance',\n      name: 'search_searxng_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Number of Pages`\n  String get search_n {\n    return Intl.message(\n      'Number of Pages',\n      name: 'search_n',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Maximum number of web pages to retrieve`\n  String get search_n_hint {\n    return Intl.message(\n      'Maximum number of web pages to retrieve',\n      name: 'search_n_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Prompt`\n  String get search_prompt {\n    return Intl.message(\n      'Prompt',\n      name: 'search_prompt',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `Template for context synthesis`\n  String get search_prompt_hint {\n    return Intl.message(\n      'Template for context synthesis',\n      name: 'search_prompt_hint',\n      desc: '',\n      args: [],\n    );\n  }\n\n  /// `In the prompt template, the {pages} placeholder will be replaced with web page content, and the {text} placeholder will be replaced with the user message. If unsure, leave it empty to use the built-in template.`\n  String search_prompt_info(Object pages, Object text) {\n    return Intl.message(\n      'In the prompt template, the $pages placeholder will be replaced with web page content, and the $text placeholder will be replaced with the user message. If unsure, leave it empty to use the built-in template.',\n      name: 'search_prompt_info',\n      desc: '',\n      args: [pages, text],\n    );\n  }\n}\n\nclass AppLocalizationDelegate extends LocalizationsDelegate<S> {\n  const AppLocalizationDelegate();\n\n  List<Locale> get supportedLocales {\n    return const <Locale>[\n      Locale.fromSubtags(languageCode: 'en'),\n      Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'),\n    ];\n  }\n\n  @override\n  bool isSupported(Locale locale) => _isSupported(locale);\n  @override\n  Future<S> load(Locale locale) => S.load(locale);\n  @override\n  bool shouldReload(AppLocalizationDelegate old) => false;\n\n  bool _isSupported(Locale locale) {\n    for (var supportedLocale in supportedLocales) {\n      if (supportedLocale.languageCode == locale.languageCode) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n"
  },
  {
    "path": "lib/image/config.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../settings/api.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass ConfigTab extends ConsumerStatefulWidget {\n  const ConfigTab({super.key});\n\n  @override\n  ConsumerState<ConfigTab> createState() => _ConfigTabState();\n}\n\nclass _ConfigTabState extends ConsumerState<ConfigTab> {\n  @override\n  Widget build(BuildContext context) {\n    ref.watch(apisProvider);\n\n    final s = S.of(context);\n    const padding = EdgeInsets.only(left: 24, right: 24);\n    final primaryColor = Theme.of(context).colorScheme.primary;\n\n    return ListView(\n      padding: const EdgeInsets.only(top: 16, bottom: 8),\n      children: [\n        Padding(\n          padding: padding,\n          child: Text(\n            s.base_config,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.api),\n          contentPadding: padding,\n          subtitle: Text(Config.image.api ?? s.empty),\n          onTap: () async {\n            if (Config.apis.isEmpty) return;\n\n            final api = await Dialogs.select(\n              context: context,\n              list: Config.apis.keys.toList(),\n              selected: Config.image.api,\n              title: s.choose_api,\n            );\n            if (api == null) return;\n\n            setState(() => Config.image.api = api);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.model),\n          contentPadding: padding,\n          subtitle: Text(Config.image.model ?? s.empty),\n          onTap: () async {\n            final models = Config.apis[Config.image.api]?.models;\n            if (models == null) return;\n\n            final model = await Dialogs.select(\n              context: context,\n              selected: Config.image.model,\n              title: s.choose_model,\n              list: models,\n            );\n            if (model == null) return;\n\n            setState(() => Config.image.model = model);\n            Config.save();\n          },\n        ),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.optional_config,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.image_size),\n          contentPadding: padding,\n          subtitle: Text(Config.image.size ?? s.empty),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.image_size,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.image.size,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            final text = texts[0].trim();\n            final size = text.isEmpty ? null : text;\n            setState(() => Config.image.size = size);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.image_style),\n          contentPadding: padding,\n          subtitle: Text(Config.image.style ?? s.empty),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.image_style,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.image.style,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            final text = texts[0].trim();\n            final style = text.isEmpty ? null : text;\n            setState(() => Config.image.style = style);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.image_quality),\n          contentPadding: padding,\n          subtitle: Text(Config.image.quality ?? s.empty),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.image_quality,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.image.quality,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            final text = texts[0].trim();\n            final quality = text.isEmpty ? null : text;\n            setState(() => Config.image.quality = quality);\n            Config.save();\n          },\n        ),\n      ],\n    );\n  }\n}\n"
  },
  {
    "path": "lib/image/generate.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"dart:io\";\nimport \"dart:convert\";\nimport \"package:http/http.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nenum _Status {\n  nothing,\n  loading,\n  generating;\n\n  bool get isNothing => this == _Status.nothing;\n  bool get isLoading => this == _Status.loading;\n  bool get isGenerating => this == _Status.generating;\n}\n\nclass GenerateTab extends ConsumerStatefulWidget {\n  const GenerateTab({super.key});\n\n  @override\n  ConsumerState<GenerateTab> createState() => _GenerateTabState();\n}\n\nclass _GenerateTabState extends ConsumerState<GenerateTab>\n    with AutomaticKeepAliveClientMixin<GenerateTab> {\n  final TextEditingController _ctrl = TextEditingController();\n  final FocusNode _node = FocusNode();\n  _Status _status = _Status.nothing;\n  final List<String> _images = [];\n  Client? _client;\n\n  @override\n  void dispose() {\n    _node.dispose();\n    _ctrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  bool get wantKeepAlive => true;\n\n  @override\n  Widget build(BuildContext context) {\n    super.build(context);\n\n    final decoration = BoxDecoration(\n      color: Theme.of(context).colorScheme.surfaceContainerHighest,\n      borderRadius: const BorderRadius.all(Radius.circular(12)),\n    );\n\n    return ListView(\n      padding: const EdgeInsets.all(16),\n      children: [\n        Container(\n          decoration: decoration,\n          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),\n          child: TextField(\n            maxLines: 4,\n            focusNode: _node,\n            controller: _ctrl,\n            keyboardType: TextInputType.multiline,\n            decoration: InputDecoration(\n              hintText: S.of(context).enter_prompts,\n              border: InputBorder.none,\n            ),\n          ),\n        ),\n        const SizedBox(height: 12),\n        FilledButton.icon(\n          icon: Icon(_status.isNothing ? Icons.add : Icons.close),\n          label: Text(\n            _status.isNothing ? S.of(context).generate : S.of(context).cancel,\n          ),\n          onPressed: _generate,\n        ),\n        const SizedBox(height: 12),\n        if (!_status.isNothing) LinearProgressIndicator(),\n        if (_images.isNotEmpty)\n          AspectRatio(\n            aspectRatio: _getAspectRatio(),\n            child: Ink(\n              decoration: BoxDecoration(\n                borderRadius: const BorderRadius.all(Radius.circular(12)),\n                image: DecorationImage(\n                  image: FileImage(File(_images.first)),\n                  fit: BoxFit.fitWidth,\n                ),\n              ),\n              child: InkWell(\n                borderRadius: const BorderRadius.all(Radius.circular(12)),\n                onTap: () => Dialogs.handleImage(\n                  context: context,\n                  path: _images.first,\n                ),\n              ),\n            ),\n          ),\n      ],\n    );\n  }\n\n  Future<void> _generate() async {\n    if (_status.isGenerating) {\n      _status = _Status.nothing;\n      _client?.close();\n      _client = null;\n      return;\n    }\n\n    final prompt = _ctrl.text;\n    if (prompt.isEmpty) return;\n\n    final image = Config.image;\n    final model = image.model;\n    final api = Config.apis[image.api];\n\n    if (model == null || api == null) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).setup_api_model_first),\n      );\n      return;\n    }\n\n    final apiUrl = api.url;\n    final apiKey = api.key;\n    final endPoint = \"$apiUrl/images/generations\";\n\n    setState(() {\n      _images.clear();\n      _status = _Status.generating;\n    });\n\n    final size = image.size;\n    final style = image.style;\n    final quality = image.quality;\n    final optional = <String, String>{};\n\n    if (size != null) optional[\"size\"] = size;\n    if (style != null) optional[\"style\"] = style;\n    if (quality != null) optional[\"quality\"] = quality;\n\n    try {\n      _client ??= Client();\n      final genRes = await _client!.post(\n        Uri.parse(endPoint),\n        headers: {\n          \"Authorization\": \"Bearer $apiKey\",\n          \"Content-Type\": \"application/json\",\n        },\n        body: jsonEncode({\n          ...optional,\n          \"model\": model,\n          \"prompt\": prompt,\n        }),\n      );\n      if (genRes.statusCode != 200) {\n        throw \"${genRes.statusCode} ${genRes.body}\";\n      }\n\n      _status = _Status.loading;\n\n      final json = jsonDecode(genRes.body);\n      final url = json[\"data\"][0][\"url\"];\n\n      final loadRes = await _client!.get(Uri.parse(url));\n      if (loadRes.statusCode != 200) {\n        throw \"${genRes.statusCode} ${genRes.body}\";\n      }\n\n      final timestamp = DateTime.now().millisecondsSinceEpoch.toString();\n      final path = Config.imageFilePath(\"$timestamp.png\");\n\n      final file = File(path);\n      await file.writeAsBytes(loadRes.bodyBytes);\n\n      if (!mounted) return;\n      setState(() => _images.add(path));\n    } catch (e) {\n      if (!mounted) return;\n      if (_status.isGenerating) {\n        Dialogs.error(context: context, error: e);\n      }\n    }\n\n    if (!mounted) return;\n    setState(() => _status = _Status.nothing);\n  }\n\n  double _getAspectRatio() {\n    final size = Config.image.size;\n    if (size == null) return 1;\n\n    final pos = size.indexOf('x');\n    if (pos == -1) return 1;\n\n    final width = size.substring(0, pos);\n    final height = size.substring(pos + 1);\n\n    final w = int.tryParse(width);\n    final h = int.tryParse(height);\n    if (w == null || h == null) return 1;\n\n    return w / h;\n  }\n}\n"
  },
  {
    "path": "lib/image/image.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"config.dart\";\nimport \"generate.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass ImagePage extends ConsumerWidget {\n  const ImagePage({super.key});\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    return DefaultTabController(\n      length: 2,\n      child: Scaffold(\n        appBar: AppBar(\n          title: Text(S.of(context).image_generation),\n          bottom: TabBar(\n            tabs: [\n              Tab(text: S.of(context).generate),\n              Tab(text: S.of(context).config),\n            ],\n          ),\n        ),\n        body: TabBarView(\n          children: [\n            const GenerateTab(),\n            const ConfigTab(),\n          ],\n        ),\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/l10n/intl_en.arb",
    "content": "{\n    \"@@locale\": \"en\",\n    \"title\": \"ChatBot\",\n\n    \"ok\": \"Ok\",\n    \"copy\": \"Copy\",\n    \"edit\": \"Edit\",\n    \"play\": \"Play\",\n    \"source\": \"Source\",\n    \"delete\": \"Delete\",\n    \"images\": \"Images\",\n    \"camera\": \"Camera\",\n    \"gallery\": \"Gallery\",\n    \"settings\": \"Settings\",\n\n    \"bot\": \"Bot\",\n    \"bots\": \"Bots\",\n    \"apis\": \"APIs\",\n    \"config\": \"Config\",\n\n    \"open\": \"Open\",\n    \"save\": \"Save\",\n    \"reset\": \"Reset\",\n    \"error\": \"Error\",\n    \"share\": \"Share\",\n    \"clear\": \"Clear\",\n    \"cancel\": \"Cancel\",\n    \"reanswer\": \"Reanswer\",\n    \"citations\": \"Citations\",\n\n    \"api\": \"API\",\n    \"model\": \"Model\",\n    \"voice\": \"Voice\",\n    \"max_tokens\": \"Max Tokens\",\n    \"temperature\": \"Temperature\",\n    \"system_prompts\": \"System Prompts\",\n    \"streaming_response\": \"Streaming Response\",\n\n    \"link\": \"Link\",\n    \"name\": \"Name\",\n    \"new_bot\": \"New Bot\",\n    \"new_api\": \"New API\",\n    \"new_chat\": \"New Chat\",\n    \"api_url\": \"API Url\",\n    \"api_key\": \"API Key\",\n    \"api_type\": \"API Type\",\n    \"model_list\": \"Model List\",\n    \"select_models\": \"Select Models\",\n\n    \"enter_a_name\": \"Please enter a name\",\n    \"enter_a_title\": \"Please enter a title\",\n    \"duplicate_bot_name\": \"Duplicate Bot name\",\n    \"duplicate_api_name\": \"Duplicate API name\",\n    \"complete_all_fields\": \"Please complete all fields\",\n\n    \"no_model\": \"no model\",\n    \"all_chats\": \"All Chats\",\n    \"chat_title\": \"Chat Title\",\n\n    \"default_config\": \"Default Config\",\n    \"text_to_speech\": \"Text To Speech\",\n    \"chat_image_compress\": \"Chat Image Compress\",\n    \"config_import_export\": \"Config Import and Export\",\n\n    \"choose_bot\": \"Choose Bot\",\n    \"choose_api\": \"Choose API\",\n    \"choose_model\": \"Choose Model\",\n    \"quality\": \"Quality\",\n    \"min_width\": \"Minimal Width\",\n    \"min_height\": \"Minimal Height\",\n    \"min_width_height\": \"Minimal Size\",\n    \"export_config\": \"Export Config\",\n    \"import_config\": \"Import Config\",\n    \"exporting\": \"Exporting...\",\n    \"importing\": \"Importing...\",\n\n    \"empty\": \"Empty\",\n    \"enable\": \"Enable\",\n    \"please_input\": \"Please Input\",\n    \"image_enable_hint\": \"The original image will be used if compression fails\",\n    \"image_hint\": \"The Quality should be between 1 and 100, with lower values resulting in higher compression. Minimum Width and Minimum Height restrict image resizing. Leave these fields empty if you're unsure.\",\n    \"config_hint\": \"To avoid export failures, it's recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.\",\n\n    \"exported_successfully\": \"Exported Successfully\",\n    \"imported_successfully\": \"Imported Successfully\",\n    \"restart_app\": \"Please restart App to load the new settings.\",\n    \"failed_to_export\": \"Can't write to that directory.\",\n\n    \"generate\": \"Generate\",\n    \"image_size\": \"Image Size\",\n    \"image_style\": \"Image Style\",\n    \"image_quality\": \"Image Quality\",\n    \"base_config\": \"Base Config\",\n    \"optional_config\": \"Optional Config\",\n    \"image_generation\": \"Image Generation\",\n    \"enter_prompts\": \"Enter your prompts\",\n\n    \"clone_chat\": \"Clone Chat\",\n    \"clear_chat\": \"Clear Chat\",\n    \"chat_settings\": \"Chat Settings\",\n    \"export_chat_as_image\": \"Export Image\",\n    \"cloned_successfully\": \"Cloned Successfully\",\n    \"ensure_clear_chat\": \"Are you sure to clear the chat?\",\n\n    \"saved_successfully\": \"Saved Successfully\",\n    \"copied_successfully\": \"Copied Successfully\",\n    \"not_implemented_yet\": \"Not implemented yet\",\n\n    \"empty_link\": \"Empty Link\",\n    \"cannot_open\": \"Cannot Open\",\n    \"invalid_max_tokens\": \"Invalid Max Tokens\",\n    \"invalid_temperature\": \"Invalid Temperature\",\n\n    \"enter_message\": \"Enter your message\",\n    \"image_compress_failed\": \"Failed to comprese image\",\n    \"setup_tts_first\": \"Set up the TTS first\",\n    \"setup_api_model_first\": \"Set up the API and Model first\",\n\n    \"other\": \"Other\",\n    \"download\": \"Download\",\n    \"up_to_date\": \"You are up to date\",\n    \"check_for_updates\": \"Check for Updates\",\n\n    \"delete_image\": \"Delete image\",\n    \"ensure_delete_image\": \"Are you sure to delete the image?\",\n\n    \"task\": \"Task\",\n    \"document\": \"Document\",\n    \"workspace\": \"Workspace\",\n    \"chat_model\": \"Chat Model\",\n    \"model_name\": \"Model Name\",\n    \"model_avatar\": \"Model Avatar\",\n    \"chat_model_hint\": \"Is it a Chat Model?\",\n\n    \"title_generation\": \"Title Generation\",\n    \"title_enable_hint\": \"If disabled, the user's message will be used as the title\",\n    \"title_prompt\": \"Prompt\",\n    \"title_prompt_hint\": \"Template for the title generation prompt\",\n    \"title_generation_hint\": \"In the prompt template, The {text} placeholder will be replaced with the user's message. If unsure, leave empty to use the built-in template.\",\n\n    \"clearing\": \"Clearing...\",\n    \"clear_data\": \"Clear Data\",\n    \"cleared_successfully\": \"Cleared Successfully\",\n    \"clear_data_chat\": \"All chat history\",\n    \"clear_data_audio\": \"All TTS cache files\",\n    \"clear_data_image\": \"All generated images\",\n\n    \"setup_vector_first\": \"Set up the embedding vector API and model first\",\n    \"search_vector\": \"Embedding Vector\",\n    \"search_vector_hint\": \"Recommended to enable\",\n    \"search_timeout\": \"Timeout\",\n    \"search_timeout_hint\": \"Retrieval timeout in milliseconds\",\n    \"search_searxng_base\": \"Base URL\",\n    \"search_searxng_extra\": \"Additional Parameters\",\n    \"search_searxng_extra_help\": \"For example: engines=google&language=en\",\n    \"search_timeout_query\": \"Query Timeout\",\n    \"search_timeout_query_help\": \"Timeout duration for SearXNG requests\",\n    \"search_timeout_fetch\": \"Fetch Timeout\",\n    \"search_timeout_fetch_help\": \"Timeout duration for fetching web page content\",\n\n    \"embedding_vector\": \"Embedding Vector\",\n    \"vector_batch_size\": \"Batch Size\",\n    \"vector_batch_size_hint\": \"Maximum number of chunks that can be submitted in a single request\",\n    \"vector_dimensions\": \"Vector Dimensions\",\n    \"vector_dimensions_hint\": \"Output dimension of the embedding vector model\",\n    \"embedding_vector_info\": \"Batch size is limited by the API service provider. It's recommended to check and modify accordingly. Vector dimension is an advanced option and should only be filled if necessary.\",\n    \"document_config\": \"Document Config\",\n    \"chunk_n\": \"Number of Chunks\",\n    \"chunk_n_hint\": \"Number of chunks to be integrated into the context\",\n    \"chunk_size\": \"Chunk Size\",\n    \"chunk_size_hint\": \"Maximum number of characters a single chunk can contain\",\n    \"chunk_overlap\": \"Chunk Overlap\",\n    \"chunk_overlap_hint\": \"Size of the overlapping portion with the previous chunk\",\n    \"document_config_hint\": \"Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.\",\n\n    \"setup_searxng_first\": \"Set up the SearXNG first\",\n    \"search_gemini_mode\": \"Google Search Mode\",\n    \"search_general_mode\": \"General Mode\",\n    \"web_search\": \"Web Search\",\n    \"search_searxng\": \"SearXNG\",\n    \"search_searxng_hint\": \"SearXNG instance\",\n    \"search_n\": \"Number of Pages\",\n    \"search_n_hint\": \"Maximum number of web pages to retrieve\",\n    \"search_prompt\": \"Prompt\",\n    \"search_prompt_hint\": \"Template for context synthesis\",\n    \"search_prompt_info\": \"In the prompt template, the {pages} placeholder will be replaced with web page content, and the {text} placeholder will be replaced with the user message. If unsure, leave it empty to use the built-in template.\"\n}\n"
  },
  {
    "path": "lib/l10n/intl_zh_CN.arb",
    "content": "{\n    \"@@locale\": \"zh_CN\",\n    \"title\": \"ChatBot\",\n\n    \"ok\": \"确定\",\n    \"copy\": \"拷贝\",\n    \"edit\": \"编辑\",\n    \"play\": \"播放\",\n    \"source\": \"源码\",\n    \"delete\": \"删除\",\n    \"images\": \"图片\",\n    \"camera\": \"相机\",\n    \"gallery\": \"图库\",\n    \"settings\": \"设置\",\n\n    \"bot\": \"角色\",\n    \"bots\": \"角色\",\n    \"apis\": \"接口\",\n    \"config\": \"配置\",\n\n    \"open\": \"打开\",\n    \"save\": \"保存\",\n    \"reset\": \"重置\",\n    \"error\": \"错误\",\n    \"share\": \"分享\",\n    \"clear\": \"清空\",\n    \"cancel\": \"取消\",\n    \"reanswer\": \"重答\",\n    \"citations\": \"引用\",\n\n    \"api\": \"接口\",\n    \"model\": \"模型\",\n    \"voice\": \"音色\",\n    \"max_tokens\": \"最大输出\",\n    \"temperature\": \"温度\",\n    \"system_prompts\": \"系统提示词\",\n    \"streaming_response\": \"流式响应\",\n\n    \"link\": \"链接\",\n    \"name\": \"名称\",\n    \"new_bot\": \"新角色\",\n    \"new_api\": \"新接口\",\n    \"new_chat\": \"新对话\",\n    \"api_url\": \"接口地址\",\n    \"api_key\": \"接口密钥\",\n    \"api_type\": \"接口类型\",\n    \"model_list\": \"模型列表\",\n    \"select_models\": \"选择模型\",\n\n    \"enter_a_name\": \"请输入名称\",\n    \"enter_a_title\": \"请输入标题\",\n    \"duplicate_bot_name\": \"角色名重复\",\n    \"duplicate_api_name\": \"接口名重复\",\n    \"complete_all_fields\": \"请填写所有字段\",\n\n    \"no_model\": \"无模型\",\n    \"all_chats\": \"所有对话\",\n    \"chat_title\": \"对话标题\",\n\n    \"default_config\": \"默认配置\",\n    \"text_to_speech\": \"文本转语音\",\n    \"chat_image_compress\": \"对话图片压缩\",\n    \"config_import_export\": \"配置导入导出\",\n\n    \"choose_bot\": \"选择角色\",\n    \"choose_api\": \"选择接口\",\n    \"choose_model\": \"选择模型\",\n    \"quality\": \"质量\",\n    \"min_width\": \"最小宽度\",\n    \"min_height\": \"最小高度\",\n    \"min_width_height\": \"最小宽高\",\n    \"export_config\": \"导出配置\",\n    \"import_config\": \"导入配置\",\n    \"exporting\": \"正在导出...\",\n    \"importing\": \"正在导入...\",\n\n    \"empty\": \"空\",\n    \"enable\": \"启用\",\n    \"please_input\": \"请输入\",\n    \"image_enable_hint\": \"压缩失败则将使用原图\",\n    \"image_hint\": \"质量范围应在 1-100，质量越低压缩率越高。最小宽度与最小高度用于限制图片缩放，如不清楚，请留空。\",\n    \"config_hint\": \"为避免导出失败，建议将配置导出到 Documents 目录，或在 Download 下创建 ChatBot 子目录。\",\n\n    \"exported_successfully\": \"导出成功\",\n    \"imported_successfully\": \"导入成功\",\n    \"restart_app\": \"请重启应用以加载新配置。\",\n    \"failed_to_export\": \"无法在该目录下写入文件。\",\n\n    \"generate\": \"生成\",\n    \"image_size\": \"图像尺寸\",\n    \"image_style\": \"图像风格\",\n    \"image_quality\": \"图像质量\",\n    \"base_config\": \"基本配置\",\n    \"optional_config\": \"可选配置\",\n    \"image_generation\": \"图像生成\",\n    \"enter_prompts\": \"请输入提示词\",\n\n    \"clone_chat\": \"复制对话\",\n    \"clear_chat\": \"清空对话\",\n    \"chat_settings\": \"对话设置\",\n    \"export_chat_as_image\": \"导出图片\",\n    \"cloned_successfully\": \"复制成功\",\n    \"ensure_clear_chat\": \"确定要清空对话？\",\n\n    \"saved_successfully\": \"保存成功\",\n    \"copied_successfully\": \"拷贝成功\",\n    \"not_implemented_yet\": \"还未实现\",\n\n    \"empty_link\": \"空链接\",\n    \"cannot_open\": \"无法打开\",\n    \"invalid_max_tokens\": \"非法的最大输出\",\n    \"invalid_temperature\": \"非法的温度\",\n\n    \"enter_message\": \"输入你的消息\",\n    \"image_compress_failed\": \"图片压缩失败\",\n    \"setup_tts_first\": \"请先配置文本转语音\",\n    \"setup_api_model_first\": \"请先配置接口和模型\",\n\n    \"other\": \"其他\",\n    \"download\": \"下载\",\n    \"up_to_date\": \"已是最新版本\",\n    \"check_for_updates\": \"检查更新\",\n\n    \"delete_image\": \"删除图片\",\n    \"ensure_delete_image\": \"确定要删除图片？\",\n\n    \"task\": \"任务\",\n    \"document\": \"文档\",\n    \"workspace\": \"工作空间\",\n    \"chat_model\": \"对话模型\",\n    \"model_name\": \"模型名称\",\n    \"model_avatar\": \"模型头像\",\n    \"chat_model_hint\": \"是否是对话模型？\",\n\n    \"title_generation\": \"标题生成\",\n    \"title_enable_hint\": \"禁用则将以用户消息为标题\",\n    \"title_prompt\": \"提示词\",\n    \"title_prompt_hint\": \"用于生成标题的提示词模板\",\n    \"title_generation_hint\": \"提示词模板中的 {text} 占位变量会被用户消息替换。如不清楚，可留空以使用内置模板。\",\n\n    \"clearing\": \"清理中...\",\n    \"clear_data\": \"清理数据\",\n    \"cleared_successfully\": \"清理成功\",\n    \"clear_data_chat\": \"所有的对话数据\",\n    \"clear_data_audio\": \"所有的 TTS 缓存\",\n    \"clear_data_image\": \"所有的图片生成结果\",\n\n    \"setup_vector_first\": \"请先配置嵌入向量接口和模型\",\n    \"search_vector\": \"嵌入向量\",\n    \"search_vector_hint\": \"建议开启\",\n    \"search_timeout\": \"超时时间\",\n    \"search_timeout_hint\": \"检索的超时毫秒数\",\n    \"search_searxng_base\": \"根地址\",\n    \"search_searxng_extra\": \"附加参数\",\n    \"search_searxng_extra_help\": \"例如：engines=google&language=zh\",\n    \"search_timeout_query\": \"检索超时\",\n    \"search_timeout_query_help\": \"请求 SearXNG 的超时时间\",\n    \"search_timeout_fetch\": \"抓取超时\",\n    \"search_timeout_fetch_help\": \"抓取网页内容的超时时间\",\n\n    \"embedding_vector\": \"嵌入向量\",\n    \"vector_batch_size\": \"批大小\",\n    \"vector_batch_size_hint\": \"单次请求能提交的最大块数量\",\n    \"vector_dimensions\": \"向量维度\",\n    \"vector_dimensions_hint\": \"嵌入向量模型输出向量的维度\",\n    \"embedding_vector_info\": \"批大小受限于接口服务商，建议查询后修改。向量维度为专业选项，非必要请勿填写。\",\n    \"document_config\": \"文档配置\",\n    \"chunk_n\": \"块数量\",\n    \"chunk_n_hint\": \"集成到上下文中的块数量\",\n    \"chunk_size\": \"块大小\",\n    \"chunk_size_hint\": \"单块能包含的最大字符数\",\n    \"chunk_overlap\": \"块重叠\",\n    \"chunk_overlap_hint\": \"与上一块重叠部分的大小\",\n    \"document_config_hint\": \"文档会被划分为若干块，经过搜索比较后，最合适的几个块会被补充进上下文。\",\n\n    \"setup_searxng_first\": \"请先配置 SearXNG 实例\",\n    \"search_gemini_mode\": \"Google Search 模式\",\n    \"search_general_mode\": \"通用模式\",\n    \"web_search\": \"联网搜索\",\n    \"search_searxng\": \"SearXNG\",\n    \"search_searxng_hint\": \"SearXNG 实例\",\n    \"search_n\": \"网页数量\",\n    \"search_n_hint\": \"检索的网页数量上限\",\n    \"search_prompt\": \"提示词\",\n    \"search_prompt_hint\": \"用于合成上下文的提示词模板\",\n    \"search_prompt_info\": \"提示词模板中的 {pages} 占位变量会被网页内容替换，{text} 占位变量会被用户消息替换。如不清楚，可留空以使用内置模板。\"\n}\n"
  },
  {
    "path": "lib/llm/llm.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"web.dart\";\nimport \"../config.dart\";\nimport \"../chat/chat.dart\";\nimport \"../chat/current.dart\";\nimport \"../chat/message.dart\";\nimport \"../markdown/util.dart\";\n\nimport \"dart:io\";\nimport \"dart:math\";\nimport \"dart:isolate\";\nimport \"dart:convert\";\nimport \"package:http/http.dart\";\nimport \"package:langchain/langchain.dart\";\nimport \"package:audioplayers/audioplayers.dart\";\nimport \"package:langchain_openai/langchain_openai.dart\";\nimport \"package:langchain_google/langchain_google.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nfinal llmProvider =\n    AutoDisposeNotifierProvider<LlmNotifier, void>(LlmNotifier.new);\n\nclass LlmNotifier extends AutoDisposeNotifier<void> {\n  Client? _ttsClient;\n  Client? _chatClient;\n  AudioPlayer? _player;\n\n  @override\n  void build() {}\n  void notify() => ref.notifyListeners();\n\n  void updateMessage(Message message) =>\n      ref.read(messageProvider(message).notifier).notify();\n\n  Future<dynamic> tts(Message message) async {\n    dynamic error;\n\n    final tts = Config.tts;\n    final model = tts.model!;\n    final voice = tts.voice!;\n    final api = Config.apis[tts.api]!;\n\n    final apiUrl = api.url;\n    final apiKey = api.key;\n    final endPoint = \"$apiUrl/audio/speech\";\n\n    Current.ttsStatus = TtsStatus.loading;\n    updateMessage(message);\n\n    try {\n      _ttsClient ??= Client();\n      _player ??= AudioPlayer();\n      final response = await _ttsClient!.post(\n        Uri.parse(endPoint),\n        headers: {\n          \"Authorization\": \"Bearer $apiKey\",\n          \"Content-Type\": \"application/json\",\n        },\n        body: jsonEncode({\n          \"model\": model,\n          \"voice\": voice,\n          \"stream\": false,\n          \"input\": markdownToText(message.item.text),\n        }),\n      );\n\n      if (response.statusCode != 200) {\n        throw \"${response.statusCode} ${response.body}\";\n      }\n\n      final timestamp = DateTime.now().millisecondsSinceEpoch.toString();\n      final path = Config.audioFilePath(\"$timestamp.mp3\");\n\n      final file = File(path);\n      await file.writeAsBytes(response.bodyBytes);\n\n      Current.ttsStatus = TtsStatus.playing;\n      updateMessage(message);\n\n      await _player!.play(DeviceFileSource(path));\n      await _player!.onPlayerStateChanged.first;\n    } catch (e) {\n      if (!Current.ttsStatus.isNothing) error = e;\n    }\n\n    Current.ttsStatus = TtsStatus.nothing;\n    updateMessage(message);\n    return error;\n  }\n\n  void stopTts() {\n    Current.ttsStatus = TtsStatus.nothing;\n    _ttsClient?.close();\n    _ttsClient = null;\n    _player?.stop();\n  }\n\n  Future<dynamic> chat(Message message) async {\n    dynamic error;\n\n    final item = message.item;\n    final model = Current.model!;\n    final apiUrl = Current.apiUrl!;\n    final apiKey = Current.apiKey!;\n    final apiType = Current.apiType;\n    final messages = Current.messages;\n\n    Current.chatStatus = ChatStatus.responding;\n    updateMessage(message);\n    notify();\n\n    try {\n      final context = await _buildContext(messages);\n\n      _chatClient = switch (apiType) {\n        \"google\" => _GoogleClient(baseUrl: apiUrl),\n        _ => Client(),\n      };\n\n      BaseChatModel llm = switch (apiType) {\n        \"google\" => ChatGoogleGenerativeAI(\n            apiKey: apiKey,\n            baseUrl: apiUrl,\n            client: _chatClient,\n            defaultOptions: ChatGoogleGenerativeAIOptions(\n              model: model,\n              temperature: Current.temperature,\n              maxOutputTokens: Current.maxTokens,\n            ),\n          ),\n        _ => ChatOpenAI(\n            apiKey: apiKey,\n            baseUrl: apiUrl,\n            client: _chatClient,\n            defaultOptions: ChatOpenAIOptions(\n              model: model,\n              maxTokens: Current.maxTokens,\n              temperature: Current.temperature,\n            ),\n          ),\n      };\n\n      if (Current.stream ?? true) {\n        final stream = llm.stream(context);\n        await for (final chunk in stream) {\n          item.text += chunk.output.content;\n          updateMessage(message);\n        }\n      } else {\n        final result = await llm.invoke(context);\n        item.text += result.output.content;\n        updateMessage(message);\n      }\n    } catch (e) {\n      if (!Current.chatStatus.isNothing) error = e;\n      if (item.text.isEmpty) {\n        if (message.list.length == 1) {\n          messages.length -= 2;\n          ref.read(messagesProvider.notifier).notify();\n        } else {\n          message.list.removeAt(message.index--);\n          updateMessage(message);\n        }\n      }\n    }\n\n    Current.chatStatus = ChatStatus.nothing;\n    updateMessage(message);\n    notify();\n\n    return error;\n  }\n\n  void stopChat() {\n    Current.chatStatus = ChatStatus.nothing;\n    _chatClient?.close();\n    _chatClient = null;\n  }\n\n  Future<PromptValue> _buildContext(List<Message> messages) async {\n    final context = <ChatMessage>[];\n    final system = Current.systemPrompts;\n    final items = messages.map((it) => it.item).toList();\n\n    if (items.last.role.isAssistant) items.removeLast();\n\n    if (Preferences.search && !Preferences.googleSearch) {\n      items.last = await _buildWebContext(items.last);\n      messages.last.item.citations = items.last.citations;\n    }\n\n    if (system != null) context.add(ChatMessage.system(system));\n\n    for (final item in items) {\n      switch (item.role) {\n        case MessageRole.assistant:\n          context.add(ChatMessage.ai(item.text));\n          break;\n\n        case MessageRole.user:\n          if (item.images.isEmpty) {\n            context.add(ChatMessage.humanText(item.text));\n            break;\n          }\n\n          context.add(ChatMessage.human(ChatMessageContent.multiModal([\n            ChatMessageContent.text(item.text),\n            for (final image in item.images)\n              ChatMessageContent.image(\n                mimeType: \"image/jpeg\",\n                data: image.base64,\n              ),\n          ])));\n          break;\n      }\n    }\n\n    return PromptValue.chat(context);\n  }\n\n  Future<MessageItem> _buildWebContext(MessageItem origin) async {\n    final text = origin.text;\n\n    _chatClient = Client();\n    final urls = await _getWebPageUrls(\n      text,\n      Config.search.n ?? 64,\n    );\n    if (urls.isEmpty) throw \"No web page found.\";\n\n    final duration = Duration(milliseconds: Config.search.fetchTime ?? 2000);\n    var docs = await Isolate.run(() async {\n      final loader = WebLoader(urls, timeout: duration);\n      return await loader.load();\n    });\n    if (docs.isEmpty) throw \"No web content retrieved.\";\n\n    if (Config.search.vector ?? false) {\n      final vector = Config.vector;\n      final document = Config.document;\n      final api = Config.apis[vector.api]!;\n\n      final apiUrl = api.url;\n      final apiKey = api.key;\n      final apiType = api.type;\n      final model = vector.model!;\n      final dimensions = vector.dimensions;\n      final batchSize = vector.batchSize ?? 64;\n\n      final topK = document.n ?? 8;\n      final chunkSize = document.size ?? 2000;\n      final chunkOverlap = document.overlap ?? 100;\n\n      final splitter = RecursiveCharacterTextSplitter(\n        chunkSize: chunkSize,\n        chunkOverlap: chunkOverlap,\n      );\n\n      _chatClient = switch (apiType) {\n        \"google\" => _GoogleClient(\n            baseUrl: apiUrl,\n            enableSearch: false,\n          ),\n        _ => _chatClient,\n      };\n\n      final embeddings = switch (apiType) {\n        \"google\" => GoogleGenerativeAIEmbeddings(\n            model: model,\n            apiKey: apiKey,\n            baseUrl: apiUrl,\n            client: _chatClient,\n            batchSize: batchSize,\n            dimensions: dimensions,\n          ),\n        _ => OpenAIEmbeddings(\n            model: model,\n            apiKey: apiKey,\n            baseUrl: apiUrl,\n            client: _chatClient,\n            batchSize: batchSize,\n            dimensions: dimensions,\n          ),\n      };\n\n      final vectorStore = MemoryVectorStore(\n        embeddings: embeddings,\n      );\n\n      docs = await Isolate.run(() => splitter.splitDocuments(docs));\n      await vectorStore.addDocuments(documents: docs);\n\n      docs = await vectorStore.search(\n        query: text,\n        searchType: VectorStoreSearchType.similarity(\n          k: topK,\n        ),\n      );\n    }\n\n    final pages = docs.map((it) => \"<webPage>\\n${it.pageContent}\\n</webPage>\");\n    final template = Config.search.prompt ??\n        \"\"\"\nYou are now an AI model with internet search capabilities.\nYou can answer user questions based on content from the internet.\nI will provide you with some information from web pages on the internet.\nEach <webPage> tag below contains the content of a web page:\n{pages}\n\nYou need to answer the user's question based on the above content:\n{text}\n        \"\"\"\n            .trim();\n\n    final context = PromptTemplate.fromTemplate(template).format({\n      \"pages\": pages.join(\"\\n\\n\"),\n      \"text\": text,\n    });\n\n    final item = MessageItem(\n      role: MessageRole.user,\n      text: context,\n    );\n\n    for (final doc in docs) {\n      item.citations.add((\n        type: CitationType.web,\n        content: doc.pageContent,\n        source: doc.metadata[\"source\"],\n      ));\n    }\n\n    return item;\n  }\n\n  Future<List<String>> _getWebPageUrls(String query, int n) async {\n    final searxng = Config.search.searxng!;\n    final baseUrl = searxng.replaceFirst(\"{text}\", query);\n\n    final badResponse = Response(\"Request Timeout\", 408);\n    final duration = Duration(milliseconds: Config.search.queryTime ?? 3000);\n\n    Uri uriOf(int i) => Uri.parse(\"$baseUrl&pageno=$i\");\n    final responses = await Future.wait(List.generate(\n      (n / 16).ceil(),\n      (i) => _chatClient!\n          .get(uriOf(i))\n          .timeout(duration)\n          .catchError((_) => badResponse),\n    ));\n\n    final urls = <String>[];\n\n    for (final res in responses) {\n      if (res.statusCode != 200) continue;\n      final json = jsonDecode(res.body);\n      final results = json[\"results\"];\n      for (final it in results) {\n        urls.add(it[\"url\"]);\n      }\n    }\n\n    n = min(n, urls.length);\n    return urls.sublist(0, n);\n  }\n}\n\nFuture<String> generateTitle(String text) async {\n  if (!(Config.title.enable ?? false)) return text;\n\n  final model = Config.title.model;\n  final api = Config.apis[Config.title.api];\n  if (api == null || model == null) return text;\n\n  final prompt = Config.title.prompt ??\n      \"\"\"\nBased on the user input below, generate a concise and relevant title.\nNote: Only return the title text, without any additional content!\n\nOutput examples:\n1. C Language Discussion\n2. 数学问题解答\n3. 電影推薦\n\nUser input:\n{text}\n      \"\"\"\n          .trim();\n\n  final apiUrl = api.url;\n  final apiKey = api.key;\n  final apiType = api.type;\n\n  final client = switch (apiType) {\n    \"google\" => _GoogleClient(\n        baseUrl: apiUrl,\n        enableSearch: false,\n      ),\n    _ => Client(),\n  };\n\n  BaseChatModel llm = switch (apiType) {\n    \"google\" => ChatGoogleGenerativeAI(\n        apiKey: apiKey,\n        client: client,\n        baseUrl: apiUrl,\n        defaultOptions: ChatGoogleGenerativeAIOptions(\n          model: model,\n        ),\n      ),\n    _ => ChatOpenAI(\n        apiKey: apiKey,\n        client: client,\n        baseUrl: apiUrl,\n        defaultOptions: ChatOpenAIOptions(\n          model: model,\n        ),\n      ),\n  };\n\n  final chain = ChatPromptTemplate.fromTemplate(prompt).pipe(llm);\n  final res = await chain.invoke({\"text\": text});\n  return res.output.content.trim();\n}\n\nclass _GoogleClient extends BaseClient {\n  final String baseUrl;\n  final bool enableSearch;\n\n  final Client _client = Client();\n\n  _GoogleClient({\n    required this.baseUrl,\n    this.enableSearch = true,\n  });\n\n  BaseRequest _hook(BaseRequest origin) {\n    if (origin is! Request) {\n      return origin;\n    }\n\n    final request = Request(\n      origin.method,\n      Uri.parse(\"${origin.url}\".replaceFirst(\n        \"https://generativelanguage.googleapis.com/v1beta\",\n        baseUrl,\n      )),\n    );\n    request.headers.addAll(origin.headers);\n\n    final bodyJson = jsonDecode(origin.body);\n    if (enableSearch && Preferences.search && Preferences.googleSearch) {\n      bodyJson[\"tools\"] = const [\n        {\"google_search\": {}},\n      ];\n    }\n\n    request.body = jsonEncode(bodyJson);\n    return request;\n  }\n\n  @override\n  Future<StreamedResponse> send(BaseRequest request) async {\n    request = _hook(request);\n    return _client.send(request);\n  }\n\n  @override\n  void close() {\n    super.close();\n    _client.close();\n  }\n}\n"
  },
  {
    "path": "lib/llm/web.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"package:http/http.dart\";\nimport \"package:langchain_core/documents.dart\";\nimport \"package:langchain_core/document_loaders.dart\";\nimport \"package:beautiful_soup_dart/beautiful_soup.dart\";\n\nclass WebLoader extends BaseDocumentLoader {\n  const WebLoader(\n    this.urls, {\n    this.client,\n    this.requestHeaders,\n    this.timeout = const Duration(seconds: 10),\n  });\n\n  final Client? client;\n  final Duration timeout;\n  final List<String> urls;\n  final Map<String, String>? requestHeaders;\n\n  @override\n  Future<List<Document>> load() async {\n    const badDocument = Document(pageContent: \"\");\n\n    final docs = await Future.wait(urls.map(\n        (it) => _scrape(it).timeout(timeout).catchError((_) => badDocument)));\n    docs.removeWhere((it) => it.pageContent.isEmpty);\n\n    return docs;\n  }\n\n  @override\n  Stream<Document> lazyLoad() async* {\n    for (final url in urls) {\n      final doc = await _scrape(url);\n      yield doc;\n    }\n  }\n\n  Future<Document> _scrape(final String url) async {\n    final html = await _fetchUrl(url);\n    final soup = BeautifulSoup(html);\n    final body = soup.body!;\n\n    body.findAll(\"script\").forEach((e) => e.extract());\n    body.findAll(\"style\").forEach((e) => e.extract());\n\n    final content = body.getText(strip: true);\n    return Document(\n      pageContent: content,\n      metadata: _buildMetadata(url, soup),\n    );\n  }\n\n  Future<String> _fetchUrl(final String url) async {\n    final clnt = client ?? Client();\n    final res = await clnt.get(\n      Uri.parse(url),\n      headers: requestHeaders,\n    );\n    return res.body;\n  }\n\n  Map<String, dynamic> _buildMetadata(\n    final String url,\n    final BeautifulSoup soup,\n  ) {\n    final title = soup.title;\n    final language = soup.find(\"html\")?.getAttrValue(\"lang\");\n    final description = soup\n        .find(\"meta\", attrs: {\"name\": \"description\"})?.getAttrValue(\"content\");\n\n    return {\n      \"source\": url,\n      if (title != null) \"title\": title.text,\n      if (language != null) \"language\": language,\n      if (description != null) \"description\": description.trim(),\n    };\n  }\n}\n"
  },
  {
    "path": "lib/main.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"config.dart\";\nimport \"gen/l10n.dart\";\nimport \"chat/chat.dart\";\nimport \"image/image.dart\";\nimport \"settings/settings.dart\";\nimport \"workspace/workspace.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\nimport \"package:flutter_localizations/flutter_localizations.dart\";\n\nvoid main() {\n  WidgetsFlutterBinding.ensureInitialized();\n  Config.init().then((_) => runApp(const ProviderScope(child: App())));\n}\n\nclass App extends StatelessWidget {\n  const App({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: \"ChatBot\",\n      theme: lightTheme,\n      darkTheme: darkTheme,\n      themeMode: ThemeMode.system,\n      routes: {\n        \"/\": (context) => ChatPage(),\n        \"/image\": (context) => ImagePage(),\n        \"/settings\": (context) => SettingsPage(),\n        \"/workspace\": (context) => WorkspacePage(),\n      },\n      localizationsDelegates: const [\n        S.delegate,\n        GlobalWidgetsLocalizations.delegate,\n        GlobalMaterialLocalizations.delegate,\n        GlobalCupertinoLocalizations.delegate,\n      ],\n      supportedLocales: S.delegate.supportedLocales,\n    );\n  }\n}\n"
  },
  {
    "path": "lib/markdown/code.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:markdown/markdown.dart\" as md;\nimport \"package:flutter_markdown/flutter_markdown.dart\";\nimport \"package:flutter_highlighter/flutter_highlighter.dart\";\nimport \"package:flutter_highlighter/themes/atom-one-dark.dart\";\nimport \"package:flutter_highlighter/themes/atom-one-light.dart\";\n\nfinal codeDarkTheme = Map.of(atomOneDarkTheme)\n  ..[\"root\"] = TextStyle(\n      color: Colors.white.withOpacity(0.7),\n      backgroundColor: Colors.transparent);\n\nfinal codeLightTheme = Map.of(atomOneLightTheme)\n  ..[\"root\"] = TextStyle(\n      color: Colors.black.withOpacity(0.7),\n      backgroundColor: Colors.transparent);\n\nclass CodeBlockBuilder extends MarkdownElementBuilder {\n  var language = \"\";\n  final BuildContext context;\n\n  CodeBlockBuilder({required this.context});\n\n  @override\n  void visitElementBefore(md.Element element) {\n    final code = element.children?.first;\n    if (code is md.Element) {\n      final lang = code.attributes[\"class\"];\n      if (lang != null) language = lang.substring(9);\n    }\n    super.visitElementBefore(element);\n  }\n\n  @override\n  Widget? visitText(md.Text text, TextStyle? preferredStyle) {\n    final colorScheme = Theme.of(context).colorScheme;\n    final theme = switch (colorScheme.brightness) {\n      Brightness.light => codeLightTheme,\n      Brightness.dark => codeDarkTheme,\n    };\n    final content = text.textContent.trim();\n\n    return IntrinsicWidth(\n      child: Column(\n        crossAxisAlignment: CrossAxisAlignment.start,\n        children: [\n          Card.filled(\n            margin: EdgeInsets.zero,\n            color: theme == codeDarkTheme\n                ? Colors.black.withOpacity(0.3)\n                : Colors.blueGrey.withOpacity(0.3),\n            shape: const RoundedRectangleBorder(\n              borderRadius: BorderRadius.zero,\n            ),\n            child: Row(\n              children: [\n                const SizedBox(width: 16),\n                Text(language),\n                const Expanded(child: SizedBox()),\n                const SizedBox(width: 8),\n                InkWell(\n                  onTap: () => Util.copyText(\n                    context: context,\n                    text: content,\n                  ),\n                  child: Padding(\n                    padding:\n                        const EdgeInsets.symmetric(vertical: 8, horizontal: 16),\n                    child: Text(\n                      S.of(context).copy,\n                      style: Theme.of(context).textTheme.labelSmall,\n                    ),\n                  ),\n                ),\n              ],\n            ),\n          ),\n          SingleChildScrollView(\n            scrollDirection: Axis.horizontal,\n            child: HighlightView(\n              content,\n              tabSize: 2,\n              theme: theme,\n              language: language,\n              padding: const EdgeInsets.all(8),\n            ),\n          ),\n        ],\n      ),\n    );\n  }\n}\n\nclass CodeBlockBuilder2 extends MarkdownElementBuilder {\n  var language = \"\";\n  final BuildContext context;\n\n  CodeBlockBuilder2({required this.context});\n\n  @override\n  void visitElementBefore(md.Element element) {\n    final code = element.children?.first;\n    if (code is md.Element) {\n      final lang = code.attributes[\"class\"];\n      if (lang != null) language = lang.substring(9);\n    }\n    super.visitElementBefore(element);\n  }\n\n  @override\n  Widget? visitText(md.Text text, TextStyle? preferredStyle) {\n    final colorScheme = Theme.of(context).colorScheme;\n    final theme = switch (colorScheme.brightness) {\n      Brightness.light => codeLightTheme,\n      Brightness.dark => codeDarkTheme,\n    };\n    final content = text.textContent.trim();\n\n    return IntrinsicWidth(\n      child: Column(\n        crossAxisAlignment: CrossAxisAlignment.start,\n        children: [\n          ColoredBox(\n            color: theme == codeDarkTheme\n                ? Colors.black.withOpacity(0.3)\n                : Colors.blueGrey.withOpacity(0.3),\n            child: Row(\n              children: [\n                const SizedBox(width: 16),\n                Text(language),\n                const Expanded(child: SizedBox()),\n                const SizedBox(width: 8),\n                Padding(\n                  padding:\n                      const EdgeInsets.symmetric(vertical: 8, horizontal: 16),\n                  child: Text(\n                    S.current.copy,\n                    style: Theme.of(context).textTheme.labelSmall,\n                  ),\n                ),\n              ],\n            ),\n          ),\n          HighlightView(\n            content,\n            tabSize: 2,\n            theme: theme,\n            language: language,\n            padding: const EdgeInsets.all(8),\n          ),\n        ],\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/markdown/latex.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"package:markdown/markdown.dart\";\nimport \"package:flutter/material.dart\" hide Element;\nimport \"package:flutter_math_fork/flutter_math.dart\";\nimport \"package:flutter_markdown/flutter_markdown.dart\";\n\nclass LatexElementBuilder extends MarkdownElementBuilder {\n  final TextStyle? textStyle;\n  final double? textScaleFactor;\n\n  LatexElementBuilder({\n    this.textStyle,\n    this.textScaleFactor,\n  });\n\n  @override\n  Widget visitElementAfterWithContext(\n    BuildContext context,\n    Element element,\n    TextStyle? preferredStyle,\n    TextStyle? parentStyle,\n  ) {\n    final String text = element.textContent.trim();\n    if (text.isEmpty) return const SizedBox();\n\n    final mathStyle = switch (element.attributes[\"MathStyle\"]) {\n      \"display\" => MathStyle.display,\n      _ => MathStyle.text,\n    };\n\n    return SingleChildScrollView(\n      scrollDirection: Axis.horizontal,\n      clipBehavior: Clip.antiAlias,\n      child: Math.tex(\n        text,\n        mathStyle: mathStyle,\n        textStyle: textStyle,\n        textScaleFactor: textScaleFactor,\n      ),\n    );\n  }\n}\n\nclass LatexElementBuilder2 extends MarkdownElementBuilder {\n  final TextStyle? textStyle;\n  final double? textScaleFactor;\n\n  LatexElementBuilder2({\n    this.textStyle,\n    this.textScaleFactor,\n  });\n\n  @override\n  Widget visitElementAfterWithContext(\n    BuildContext context,\n    Element element,\n    TextStyle? preferredStyle,\n    TextStyle? parentStyle,\n  ) {\n    final String text = element.textContent.trim();\n    if (text.isEmpty) return const SizedBox();\n\n    final mathStyle = switch (element.attributes[\"MathStyle\"]) {\n      \"display\" => MathStyle.display,\n      _ => MathStyle.text,\n    };\n\n    return Wrap(\n      runSpacing: 8,\n      crossAxisAlignment: WrapCrossAlignment.center,\n      children: Math.tex(\n        text,\n        mathStyle: mathStyle,\n        textStyle: textStyle,\n        textScaleFactor: textScaleFactor,\n      ).texBreak().parts,\n    );\n  }\n}\n\nclass _LatexDelimiter {\n  final String left;\n  final String right;\n  final bool display;\n\n  const _LatexDelimiter({\n    required this.left,\n    required this.right,\n    required this.display,\n  });\n}\n\nclass LatexInlineSyntax extends InlineSyntax {\n  static const _delimiters = [\n    _LatexDelimiter(left: r\"$$\", right: r\"$$\", display: true),\n    _LatexDelimiter(left: r\"$\", right: r\"$\", display: false),\n    _LatexDelimiter(left: r\"\\[\", right: r\"\\]\", display: true),\n    _LatexDelimiter(left: r\"\\(\", right: r\"\\)\", display: false),\n    _LatexDelimiter(left: r\"\\ce{\", right: \"}\", display: false),\n    _LatexDelimiter(left: r\"\\pu{\", right: \"}\", display: false),\n  ];\n\n  static String _buildPattern() => _delimiters.map((d) {\n        final right = RegExp.escape(d.right);\n        final left = RegExp.escape(d.left);\n        return \"$left([\\\\s\\\\S]+?)$right\";\n      }).join(\"|\");\n\n  LatexInlineSyntax() : super(_buildPattern());\n\n  @override\n  bool onMatch(InlineParser parser, Match match) {\n    final fullMatch = match[0]!;\n\n    final delimiter = _delimiters.firstWhere(\n      (d) => fullMatch.startsWith(d.left) && fullMatch.endsWith(d.right),\n      orElse: () => _delimiters[1],\n    );\n\n    final content = fullMatch.substring(\n      delimiter.left.length,\n      fullMatch.length - delimiter.right.length,\n    );\n\n    final text = Element.text(\"latex\", content)\n      ..attributes[\"MathStyle\"] = delimiter.display ? \"display\" : \"text\";\n\n    parser.addNode(text);\n    return true;\n  }\n}\n\nclass LatexBlockSyntax extends BlockSyntax {\n  static final dollarPattern = RegExp(r\"^\\$\\$\\s*$\");\n  static final bracketPattern = RegExp(r\"^\\\\\\[\\s*$\");\n  static final endDollarPattern = RegExp(r\"^\\$\\$\\s*$\");\n  static final endBracketPattern = RegExp(r\"^\\\\\\]\\s*$\");\n\n  @override\n  RegExp get pattern => RegExp(r\"^\\$\\$|^\\\\\\[\");\n\n  @override\n  bool canParse(BlockParser parser) {\n    return dollarPattern.hasMatch(parser.current.content) ||\n        bracketPattern.hasMatch(parser.current.content);\n  }\n\n  @override\n  Node parse(BlockParser parser) {\n    final lines = <String>[];\n    final start = parser.current.content;\n    final isDollar = dollarPattern.hasMatch(start);\n\n    parser.advance();\n\n    while (!parser.isDone) {\n      final line = parser.current.content;\n      if ((isDollar && endDollarPattern.hasMatch(line)) ||\n          (!isDollar && endBracketPattern.hasMatch(line))) {\n        parser.advance();\n        break;\n      }\n      lines.add(line);\n      parser.advance();\n    }\n\n    final text = Element.text(\"latex\", lines.join(\"\\n\").trim());\n    text.attributes[\"MathStyle\"] = \"display\";\n    return Element(\"p\", [text]);\n  }\n}\n"
  },
  {
    "path": "lib/markdown/util.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"latex.dart\";\n\nimport \"package:markdown/markdown.dart\";\n\nfinal mdExtensionSet = ExtensionSet(\n  <BlockSyntax>[\n    LatexBlockSyntax(),\n    const TableSyntax(),\n    const FootnoteDefSyntax(),\n    const FencedCodeBlockSyntax(),\n    const OrderedListWithCheckboxSyntax(),\n    const UnorderedListWithCheckboxSyntax(),\n  ],\n  <InlineSyntax>[\n    InlineHtmlSyntax(),\n    LatexInlineSyntax(),\n    StrikethroughSyntax(),\n    AutolinkExtensionSyntax()\n  ],\n);\n\nString markdownToText(String markdown) {\n  final doc = Document(\n    extensionSet: mdExtensionSet,\n  );\n  final buff = StringBuffer();\n  final nodes = doc.parse(markdown);\n\n  for (final node in nodes) {\n    if (node is Element) {\n      buff.write(_elementToText(node));\n    }\n  }\n\n  return buff.toString().trim();\n}\n\nString _elementToText(Element element) {\n  final buff = StringBuffer();\n  final nodes = element.children ?? [];\n\n  if (element.tag == \"ul\") {\n    for (final node in nodes) {\n      if (node is Element && node.tag == \"li\") {\n        buff.write(_elementToText(node));\n      }\n    }\n  } else if (element.tag == \"ol\") {\n    int index = 1;\n    for (final node in nodes) {\n      if (node is Element && node.tag == \"li\") {\n        buff.write(\"${index++}. ${_elementToText(node)}\");\n      }\n    }\n  } else {\n    for (final node in nodes) {\n      if (node is Text) {\n        buff.write(node.text);\n      } else if (node is Element) {\n        final tag = node.tag;\n        if (tag == \"code\") continue;\n        if (tag == \"latex\") continue;\n        if (tag == \"th\" || tag == \"td\") continue;\n        buff.write(_elementToText(node));\n      }\n      buff.write(\"\\n\");\n    }\n  }\n\n  return buff.toString();\n}\n"
  },
  {
    "path": "lib/settings/api.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"dart:convert\";\nimport \"package:http/http.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:animate_do/animate_do.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nfinal apisProvider =\n    NotifierProvider.autoDispose<ApisNotifier, void>(ApisNotifier.new);\n\nclass ApisNotifier extends AutoDisposeNotifier<void> {\n  @override\n  void build() {}\n  void notify() => ref.notifyListeners();\n}\n\nclass ApisTab extends ConsumerWidget {\n  const ApisTab({super.key});\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    ref.watch(apisProvider);\n    final apis = Config.apis.keys.toList();\n\n    return Stack(\n      children: [\n        ListView.separated(\n          padding: const EdgeInsets.all(16),\n          separatorBuilder: (context, index) => const SizedBox(height: 12),\n          itemCount: apis.length,\n          itemBuilder: (context, index) => Card.filled(\n            margin: EdgeInsets.zero,\n            child: ListTile(\n              title: Text(\n                apis[index],\n                overflow: TextOverflow.ellipsis,\n              ),\n              leading: const Icon(Icons.api),\n              contentPadding: const EdgeInsets.only(left: 16, right: 8),\n              onTap: () => Navigator.of(context).push(MaterialPageRoute(\n                builder: (context) => ApiSettings(api: apis[index]),\n              )),\n              shape: const RoundedRectangleBorder(\n                borderRadius: BorderRadius.all(Radius.circular(12)),\n              ),\n            ),\n          ),\n        ),\n        Positioned(\n          right: 16,\n          bottom: 16,\n          child: FloatingActionButton.extended(\n            heroTag: \"api\",\n            icon: const Icon(Icons.api),\n            label: Text(S.of(context).new_api),\n            onPressed: () => Navigator.of(context).push(MaterialPageRoute(\n              builder: (context) => ApiSettings(),\n            )),\n          ),\n        ),\n      ],\n    );\n  }\n}\n\nclass ApiSettings extends ConsumerStatefulWidget {\n  final String? api;\n\n  const ApiSettings({\n    super.key,\n    this.api,\n  });\n\n  @override\n  ConsumerState<ApiSettings> createState() => _ApiSettingsState();\n}\n\nclass _ApiSettingsState extends ConsumerState<ApiSettings> {\n  String? _type;\n  Client? _client;\n  bool _isFetching = false;\n  late final TextEditingController _nameCtrl;\n  late final TextEditingController _modelsCtrl;\n  late final TextEditingController _apiUrlCtrl;\n  late final TextEditingController _apiKeyCtrl;\n\n  @override\n  void initState() {\n    super.initState();\n\n    final api = widget.api;\n    final config = Config.apis[api];\n\n    _type = config?.type;\n    _nameCtrl = TextEditingController(text: api);\n    _apiUrlCtrl = TextEditingController(text: config?.url);\n    _apiKeyCtrl = TextEditingController(text: config?.key);\n    _modelsCtrl = TextEditingController(text: config?.models.join(\", \"));\n  }\n\n  @override\n  void dispose() {\n    _modelsCtrl.dispose();\n    _apiKeyCtrl.dispose();\n    _apiUrlCtrl.dispose();\n    _nameCtrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    final api = widget.api;\n\n    return Scaffold(\n      appBar: AppBar(\n        title: Text(S.of(context).api),\n      ),\n      body: ListView(\n        padding: const EdgeInsets.only(left: 16, right: 16),\n        children: [\n          const SizedBox(height: 16),\n          Row(\n            children: [\n              Expanded(\n                child: DropdownButtonFormField<String>(\n                  value: _type,\n                  items: <DropdownMenuItem<String>>[\n                    DropdownMenuItem(\n                      value: \"openai\",\n                      child: const Text(\"OpenAI\"),\n                    ),\n                    DropdownMenuItem(\n                      value: \"google\",\n                      child: const Text(\"Google\"),\n                    ),\n                  ],\n                  isExpanded: true,\n                  hint: Text(S.of(context).api_type),\n                  onChanged: (it) => setState(() => _type = it),\n                  decoration: const InputDecoration(\n                    border: OutlineInputBorder(),\n                  ),\n                ),\n              ),\n              const SizedBox(width: 12),\n              Expanded(\n                child: TextField(\n                  controller: _nameCtrl,\n                  decoration: InputDecoration(\n                    labelText: S.of(context).name,\n                    border: const OutlineInputBorder(),\n                  ),\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 16),\n          TextField(\n            controller: _apiUrlCtrl,\n            decoration: InputDecoration(\n              labelText: S.of(context).api_url,\n              border: const OutlineInputBorder(),\n            ),\n          ),\n          const SizedBox(height: 16),\n          TextField(\n            controller: _apiKeyCtrl,\n            decoration: InputDecoration(\n              labelText: S.of(context).api_key,\n              border: const OutlineInputBorder(),\n            ),\n          ),\n          const SizedBox(height: 16),\n          Row(\n            children: [\n              Expanded(\n                child: TextField(\n                  maxLines: 4,\n                  controller: _modelsCtrl,\n                  decoration: InputDecoration(\n                    labelText: S.of(context).model_list,\n                    alignLabelWithHint: true,\n                    border: const OutlineInputBorder(),\n                  ),\n                ),\n              ),\n              const SizedBox(width: 12),\n              Column(\n                mainAxisSize: MainAxisSize.min,\n                mainAxisAlignment: MainAxisAlignment.spaceBetween,\n                children: [\n                  Spin(\n                    infinite: true,\n                    animate: _isFetching,\n                    duration: Duration(seconds: 1),\n                    child: IconButton.outlined(\n                      icon: const Icon(Icons.sync),\n                      onPressed: _fetchModels,\n                    ),\n                  ),\n                  const SizedBox(height: 16),\n                  IconButton.outlined(\n                    icon: const Icon(Icons.edit),\n                    onPressed: _editModels,\n                  ),\n                ],\n              )\n            ],\n          ),\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              Expanded(\n                flex: 1,\n                child: FilledButton.tonal(\n                  onPressed: Navigator.of(context).pop,\n                  child: Text(S.of(context).cancel),\n                ),\n              ),\n              const SizedBox(width: 6),\n              if (api != null) ...[\n                const SizedBox(width: 6),\n                Expanded(\n                  flex: 1,\n                  child: FilledButton(\n                    style: FilledButton.styleFrom(\n                      backgroundColor: Theme.of(context).colorScheme.error,\n                      foregroundColor: Theme.of(context).colorScheme.onError,\n                    ),\n                    child: Text(S.of(context).delete),\n                    onPressed: () {\n                      Config.apis.remove(api);\n                      Config.save();\n\n                      ref.read(apisProvider.notifier).notify();\n                      Navigator.of(context).pop();\n                    },\n                  ),\n                ),\n                const SizedBox(width: 6),\n              ],\n              const SizedBox(width: 6),\n              Expanded(\n                flex: 1,\n                child: FilledButton(\n                  onPressed: _save,\n                  child: Text(S.of(context).save),\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 16),\n        ],\n      ),\n    );\n  }\n\n  Future<void> _fetchModels() async {\n    if (_isFetching) {\n      _isFetching = false;\n      _client?.close();\n      _client = null;\n      return;\n    }\n\n    final url = _apiUrlCtrl.text;\n    final key = _apiKeyCtrl.text;\n    final endPoint = switch (_type) {\n      \"google\" => \"$url/models?key=$key\",\n      _ => \"$url/models\",\n    };\n\n    if (url.isEmpty || key.isEmpty) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).complete_all_fields),\n      );\n      return;\n    }\n\n    setState(() => _isFetching = true);\n\n    try {\n      _client ??= Client();\n      final response = await _client!.get(\n        Uri.parse(endPoint),\n        headers: switch (_type) {\n          \"google\" => null,\n          _ => {\"Authorization\": \"Bearer $key\"},\n        },\n      );\n\n      if (response.statusCode != 200) {\n        throw \"${response.statusCode} ${response.body}\";\n      }\n\n      final json = jsonDecode(response.body);\n      List<String> models = switch (_type) {\n        \"google\" => [\n            for (final cell in json[\"models\"]) cell[\"name\"].substring(7),\n          ],\n        _ => [for (final cell in json[\"data\"]) cell[\"id\"]],\n      };\n\n      _modelsCtrl.text = models.join(\", \");\n    } catch (e) {\n      if (_isFetching && mounted) {\n        Dialogs.error(context: context, error: e);\n      }\n    }\n\n    setState(() => _isFetching = false);\n  }\n\n  Future<void> _editModels() async {\n    final text = _modelsCtrl.text;\n    if (text.isEmpty) return;\n\n    final models = text.split(',').map((it) => it.trim()).toList();\n    models.removeWhere((e) => e.isEmpty);\n\n    final chosen = {for (final it in models) it: true};\n    if (chosen.isEmpty) return;\n\n    final result = await showModalBottomSheet<bool>(\n      context: context,\n      scrollControlDisabledMaxHeightRatio: 0.7,\n      builder: (context) => StatefulBuilder(\n        builder: (context, setState) => Column(\n          mainAxisSize: MainAxisSize.min,\n          crossAxisAlignment: CrossAxisAlignment.start,\n          children: [\n            DialogHeader(title: S.of(context).select_models),\n            const Divider(height: 1),\n            Flexible(\n              child: ListView.builder(\n                shrinkWrap: true,\n                itemCount: chosen.length,\n                itemBuilder: (context, index) => CheckboxListTile(\n                  title: Text(models[index]),\n                  value: chosen[models[index]],\n                  contentPadding: const EdgeInsets.only(left: 24, right: 16),\n                  onChanged: (value) =>\n                      setState(() => chosen[models[index]] = value ?? false),\n                ),\n              ),\n            ),\n            const Divider(height: 1),\n            DialogFooter(\n              children: [\n                TextButton(\n                  child: Text(S.of(context).ok),\n                  onPressed: () => Navigator.of(context).pop(true),\n                ),\n                TextButton(\n                  onPressed: Navigator.of(context).pop,\n                  child: Text(S.of(context).cancel),\n                ),\n                TextButton(\n                  child: Text(S.of(context).clear),\n                  onPressed: () => setState(\n                      () => chosen.forEach((it, _) => chosen[it] = false)),\n                ),\n              ],\n            ),\n          ],\n        ),\n      ),\n    );\n    if (!(result ?? false)) return;\n\n    _modelsCtrl.text = [\n      for (final pair in chosen.entries)\n        if (pair.value) pair.key\n    ].join(\", \");\n  }\n\n  void _save() {\n    final name = _nameCtrl.text;\n    final models = _modelsCtrl.text;\n    final apiUrl = _apiUrlCtrl.text;\n    final apiKey = _apiKeyCtrl.text;\n\n    if (name.isEmpty || models.isEmpty || apiUrl.isEmpty || apiKey.isEmpty) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).complete_all_fields),\n      );\n      return;\n    }\n\n    final api = widget.api;\n    if (Config.apis.containsKey(name) && (api == null || name != api)) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).duplicate_api_name),\n      );\n      return;\n    }\n\n    if (api != null) Config.apis.remove(api);\n    final modelList = models.split(',').map((e) => e.trim()).toList();\n    modelList.removeWhere((e) => e.isEmpty);\n\n    Config.apis[name] = ApiConfig(\n      url: apiUrl,\n      key: apiKey,\n      type: _type,\n      models: modelList,\n    );\n    Config.save();\n\n    ref.read(apisProvider.notifier).notify();\n    Navigator.of(context).pop();\n  }\n}\n"
  },
  {
    "path": "lib/settings/bot.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nfinal botsProvider =\n    NotifierProvider.autoDispose<BotsNotifier, void>(BotsNotifier.new);\n\nclass BotsNotifier extends AutoDisposeNotifier<void> {\n  @override\n  void build() {}\n  void notify() => ref.notifyListeners();\n}\n\nclass BotsTab extends ConsumerWidget {\n  const BotsTab({super.key});\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    ref.watch(botsProvider);\n    final bots = Config.bots.keys.toList();\n\n    return Stack(\n      children: [\n        ListView.separated(\n          padding: const EdgeInsets.all(16),\n          separatorBuilder: (context, index) => const SizedBox(height: 12),\n          itemCount: bots.length,\n          itemBuilder: (context, index) => Card.filled(\n            margin: EdgeInsets.zero,\n            child: ListTile(\n              title: Text(\n                bots[index],\n                overflow: TextOverflow.ellipsis,\n              ),\n              leading: const Icon(Icons.smart_toy),\n              contentPadding: const EdgeInsets.only(left: 16, right: 8),\n              onTap: () => Navigator.of(context).push(MaterialPageRoute(\n                builder: (context) => BotSettings(bot: bots[index]),\n              )),\n              shape: const RoundedRectangleBorder(\n                borderRadius: BorderRadius.all(Radius.circular(12)),\n              ),\n            ),\n          ),\n        ),\n        Positioned(\n          right: 16,\n          bottom: 16,\n          child: FloatingActionButton.extended(\n            heroTag: \"bot\",\n            icon: const Icon(Icons.smart_toy),\n            label: Text(S.of(context).new_bot),\n            onPressed: () => Navigator.of(context).push(MaterialPageRoute(\n              builder: (context) => BotSettings(),\n            )),\n          ),\n        ),\n      ],\n    );\n  }\n}\n\nclass BotSettings extends ConsumerStatefulWidget {\n  final String? bot;\n\n  const BotSettings({\n    super.key,\n    this.bot,\n  });\n\n  @override\n  ConsumerState<BotSettings> createState() => _BotSettingsState();\n}\n\nclass _BotSettingsState extends ConsumerState<BotSettings> {\n  bool? _stream;\n  late final TextEditingController _nameCtrl;\n  late final TextEditingController _maxTokensCtrl;\n  late final TextEditingController _temperatureCtrl;\n  late final TextEditingController _systemPromptsCtrl;\n\n  @override\n  void initState() {\n    super.initState();\n\n    final bot = widget.bot;\n    final config = Config.bots[bot];\n\n    _stream = config?.stream;\n    _nameCtrl = TextEditingController(text: bot);\n    _maxTokensCtrl = TextEditingController(text: config?.maxTokens?.toString());\n    _temperatureCtrl =\n        TextEditingController(text: config?.temperature?.toString());\n    _systemPromptsCtrl = TextEditingController(text: config?.systemPrompts);\n  }\n\n  @override\n  void dispose() {\n    _systemPromptsCtrl.dispose();\n    _temperatureCtrl.dispose();\n    _maxTokensCtrl.dispose();\n    _nameCtrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    final bot = widget.bot;\n\n    return Scaffold(\n      appBar: AppBar(\n        title: Text(S.of(context).bot),\n      ),\n      body: ListView(\n        padding: const EdgeInsets.only(left: 16, right: 16),\n        children: [\n          const SizedBox(height: 16),\n          TextField(\n            controller: _nameCtrl,\n            decoration: InputDecoration(\n              labelText: S.of(context).name,\n              border: const OutlineInputBorder(),\n            ),\n          ),\n          const SizedBox(height: 16),\n          Row(\n            children: [\n              Expanded(\n                child: TextField(\n                  controller: _temperatureCtrl,\n                  keyboardType: TextInputType.number,\n                  decoration: InputDecoration(\n                    labelText: S.of(context).temperature,\n                    border: const OutlineInputBorder(),\n                  ),\n                ),\n              ),\n              const SizedBox(width: 12),\n              Expanded(\n                child: TextField(\n                  controller: _maxTokensCtrl,\n                  keyboardType: TextInputType.number,\n                  decoration: InputDecoration(\n                    labelText: S.of(context).max_tokens,\n                    border: const OutlineInputBorder(),\n                  ),\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 16),\n          TextField(\n            maxLines: 4,\n            controller: _systemPromptsCtrl,\n            decoration: InputDecoration(\n              alignLabelWithHint: true,\n              labelText: S.of(context).system_prompts,\n              border: const OutlineInputBorder(),\n            ),\n          ),\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              Flexible(\n                child: SwitchListTile(\n                  value: _stream ?? true,\n                  title: Text(S.of(context).streaming_response),\n                  onChanged: (value) => setState(() => _stream = value),\n                  contentPadding: const EdgeInsets.only(left: 8, right: 8),\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 12),\n          Row(\n            children: [\n              Expanded(\n                child: FilledButton.tonal(\n                  child: Text(S.of(context).reset),\n                  onPressed: () {\n                    _maxTokensCtrl.text = \"\";\n                    _temperatureCtrl.text = \"\";\n                    _systemPromptsCtrl.text = \"\";\n                    setState(() => _stream = null);\n                  },\n                ),\n              ),\n              const SizedBox(width: 6),\n              if (bot != null) ...[\n                const SizedBox(width: 6),\n                Expanded(\n                  child: FilledButton(\n                    style: FilledButton.styleFrom(\n                      backgroundColor: Theme.of(context).colorScheme.error,\n                      foregroundColor: Theme.of(context).colorScheme.onError,\n                    ),\n                    child: Text(S.of(context).delete),\n                    onPressed: () async {\n                      Config.bots.remove(bot);\n                      Config.save();\n\n                      ref.read(botsProvider.notifier).notify();\n                      Navigator.of(context).pop();\n                    },\n                  ),\n                ),\n                const SizedBox(width: 6),\n              ],\n              const SizedBox(width: 6),\n              Expanded(\n                child: FilledButton(\n                  onPressed: _save,\n                  child: Text(S.of(context).save),\n                ),\n              ),\n            ],\n          ),\n          const SizedBox(height: 16),\n        ],\n      ),\n    );\n  }\n\n  void _save() {\n    final name = _nameCtrl.text;\n\n    if (name.isEmpty) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).enter_a_name),\n      );\n      return;\n    }\n\n    final bot = widget.bot;\n    if (Config.bots.containsKey(name) && (bot == null || name != bot)) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).duplicate_bot_name),\n      );\n      return;\n    }\n\n    final maxTokens = int.tryParse(_maxTokensCtrl.text);\n    final temperature = double.tryParse(_temperatureCtrl.text);\n\n    if (_maxTokensCtrl.text.isNotEmpty && maxTokens == null) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).invalid_max_tokens),\n      );\n      return;\n    }\n\n    if (_temperatureCtrl.text.isNotEmpty && temperature == null) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).invalid_temperature),\n      );\n      return;\n    }\n\n    if (bot != null) Config.bots.remove(bot);\n    final text = _systemPromptsCtrl.text;\n    final systemPrompts = text.isEmpty ? null : text;\n\n    Config.bots[name] = BotConfig(\n      stream: _stream,\n      maxTokens: maxTokens,\n      temperature: temperature,\n      systemPrompts: systemPrompts,\n    );\n    Config.save();\n\n    ref.read(botsProvider.notifier).notify();\n    Navigator.of(context).pop();\n  }\n}\n"
  },
  {
    "path": "lib/settings/config.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"bot.dart\";\nimport \"api.dart\";\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../chat/chat.dart\";\nimport \"../chat/current.dart\";\n\nimport \"dart:io\";\nimport \"package:flutter/services.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:file_picker/file_picker.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass ConfigTab extends ConsumerStatefulWidget {\n  const ConfigTab({super.key});\n\n  @override\n  ConsumerState<ConfigTab> createState() => _ConfigTabState();\n}\n\nclass _ConfigTabState extends ConsumerState<ConfigTab> {\n  @override\n  Widget build(BuildContext context) {\n    ref.watch(botsProvider);\n    ref.watch(apisProvider);\n\n    final s = S.of(context);\n    const padding = EdgeInsets.only(left: 24, right: 24);\n    final primaryColor = Theme.of(context).colorScheme.primary;\n\n    return ListView(\n      padding: const EdgeInsets.only(top: 16, bottom: 8),\n      children: [\n        Padding(\n          padding: padding,\n          child: Text(\n            s.default_config,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.bot),\n          contentPadding: padding,\n          subtitle: Text(Config.core.bot ?? s.empty),\n          onTap: () async {\n            if (Config.bots.isEmpty) return;\n\n            final bot = await Dialogs.select(\n              context: context,\n              list: Config.bots.keys.toList(),\n              selected: Config.core.bot,\n              title: s.choose_bot,\n            );\n            if (bot == null) return;\n\n            setState(() => Config.core.bot = bot);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.api),\n          contentPadding: padding,\n          subtitle: Text(Config.core.api ?? s.empty),\n          onTap: () async {\n            if (Config.apis.isEmpty) return;\n\n            final api = await Dialogs.select(\n              context: context,\n              list: Config.apis.keys.toList(),\n              selected: Config.core.api,\n              title: s.choose_api,\n            );\n            if (api == null) return;\n\n            setState(() => Config.core.api = api);\n            ref.read(chatProvider.notifier).notify();\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.model),\n          contentPadding: padding,\n          subtitle: Text(Config.core.model ?? s.empty),\n          onTap: () async {\n            final models = Config.apis[Config.core.api]?.models;\n            if (models == null) return;\n\n            final model = await Dialogs.select(\n              context: context,\n              selected: Config.core.model,\n              title: s.choose_model,\n              list: models,\n            );\n            if (model == null) return;\n\n            setState(() => Config.core.model = model);\n            ref.read(chatProvider.notifier).notify();\n            Config.save();\n          },\n        ),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.text_to_speech,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.api),\n          contentPadding: padding,\n          subtitle: Text(Config.tts.api ?? s.empty),\n          onTap: () async {\n            if (Config.apis.isEmpty) return;\n\n            final api = await Dialogs.select(\n              context: context,\n              list: Config.apis.keys.toList(),\n              selected: Config.tts.api,\n              title: s.choose_api,\n            );\n            if (api == null) return;\n\n            setState(() => Config.tts.api = api);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.model),\n          contentPadding: padding,\n          subtitle: Text(Config.tts.model ?? s.empty),\n          onTap: () async {\n            final models = Config.apis[Config.tts.api]?.models;\n            if (models == null) return;\n\n            final model = await Dialogs.select(\n              context: context,\n              selected: Config.tts.model,\n              title: s.choose_model,\n              list: models,\n            );\n            if (model == null) return;\n\n            setState(() => Config.tts.model = model);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.voice),\n          contentPadding: padding,\n          subtitle: Text(Config.tts.voice ?? s.empty),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.voice,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.tts.voice,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            String? voice;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) voice = text;\n\n            setState(() => Config.tts.voice = voice);\n            Config.save();\n          },\n        ),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.chat_image_compress,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        CheckboxListTile(\n          title: Text(s.enable),\n          contentPadding: const EdgeInsets.only(left: 24, right: 16),\n          value: Config.cic.enable ?? true,\n          subtitle: Text(s.image_enable_hint),\n          onChanged: (value) {\n            setState(() => Config.cic.enable = value);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.quality),\n          contentPadding: padding,\n          subtitle: Text(Config.cic.quality?.toString() ?? s.empty),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.quality,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.cic.quality?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? quality;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              quality = int.tryParse(text);\n              if (quality == null) return;\n            }\n\n            setState(() => Config.cic.quality = quality);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.min_width_height),\n          contentPadding: padding,\n          subtitle: Text(\n            \"${Config.cic.minWidth ?? s.empty} x \"\n            \"${Config.cic.minHeight ?? s.empty}\",\n          ),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.min_width_height,\n              fields: [\n                InputDialogField(\n                  label: s.min_width,\n                  text: Config.cic.minWidth?.toString(),\n                ),\n                InputDialogField(\n                  label: s.min_height,\n                  text: Config.cic.minHeight?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? minWidth;\n            int? minHeight;\n            final text1 = texts[0].trim();\n            final text2 = texts[1].trim();\n            if (text1.isNotEmpty) {\n              minWidth = int.tryParse(text1);\n              if (minWidth == null) return;\n            }\n            if (text2.isNotEmpty) {\n              minHeight = int.tryParse(text2);\n              if (minHeight == null) return;\n            }\n\n            setState(() {\n              Config.cic.minWidth = minWidth;\n              Config.cic.minHeight = minHeight;\n            });\n            Config.save();\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.image_hint),\n        const SizedBox(height: 16),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.config_import_export,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.import_config),\n          contentPadding: padding,\n          onTap: () async {\n            try {\n              final result = await FilePicker.platform.pickFiles();\n              if (result == null || !context.mounted) return;\n\n              Dialogs.loading(context: context, hint: s.importing);\n              final from = result.files.single.path!;\n              await Backup.importConfig(from);\n\n              if (!context.mounted) return;\n              Navigator.of(context).pop();\n              await showDialog(\n                context: context,\n                builder: (context) => AlertDialog(\n                  title: Text(s.imported_successfully),\n                  content: Text(s.restart_app),\n                  actions: [\n                    TextButton(\n                      onPressed: Navigator.of(context).pop,\n                      child: Text(s.ok),\n                    )\n                  ],\n                ),\n              );\n\n              SystemNavigator.pop();\n            } catch (e) {\n              if (!context.mounted) return;\n              Navigator.of(context).pop();\n              Dialogs.error(context: context, error: e);\n            }\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.export_config),\n          contentPadding: padding,\n          onTap: () async {\n            try {\n              final to = await FilePicker.platform.getDirectoryPath();\n              if (to == null || !context.mounted) return;\n\n              Dialogs.loading(context: context, hint: s.exporting);\n              await Backup.exportConfig(to);\n\n              if (!context.mounted) return;\n              Navigator.of(context).pop();\n              Util.showSnackBar(\n                context: context,\n                content: Text(s.exported_successfully),\n              );\n            } on PathAccessException {\n              Navigator.of(context).pop();\n              showDialog(\n                context: context,\n                builder: (context) => AlertDialog(\n                  title: Text(s.error),\n                  content: Text(s.failed_to_export),\n                  actions: [\n                    TextButton(\n                      child: Text(s.ok),\n                      onPressed: () => Navigator.of(context).pop(),\n                    ),\n                  ],\n                ),\n              );\n            } catch (e) {\n              Navigator.of(context).pop();\n              Dialogs.error(context: context, error: e);\n            }\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.config_hint),\n        const SizedBox(height: 16),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.other,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.clear_data),\n          onTap: _clearData,\n          contentPadding: padding,\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.check_for_updates),\n          onTap: () => Util.checkUpdate(\n            context: context,\n            notify: true,\n          ),\n          contentPadding: padding,\n        ),\n      ],\n    );\n  }\n\n  Future<void> _clearData() async {\n    bool chat = false;\n    bool audio = false;\n    bool image = false;\n\n    final s = S.of(context);\n    final result = await showModalBottomSheet<bool>(\n      context: context,\n      builder: (context) => StatefulBuilder(\n        builder: (context, setState) => Column(\n          mainAxisSize: MainAxisSize.min,\n          children: [\n            DialogHeader(title: s.clear_data),\n            const Divider(height: 1),\n            CheckboxListTile(\n              value: chat,\n              title: Text(\"Chat\"),\n              subtitle: Text(s.clear_data_chat),\n              onChanged: (it) => setState(() => chat = it ?? false),\n              contentPadding: const EdgeInsets.only(left: 24, right: 16),\n            ),\n            CheckboxListTile(\n              value: audio,\n              title: Text(\"Audio\"),\n              subtitle: Text(s.clear_data_audio),\n              onChanged: (it) => setState(() => audio = it ?? false),\n              contentPadding: const EdgeInsets.only(left: 24, right: 16),\n            ),\n            CheckboxListTile(\n              value: image,\n              title: Text(\"Image\"),\n              subtitle: Text(s.clear_data_image),\n              onChanged: (it) => setState(() => image = it ?? false),\n              contentPadding: const EdgeInsets.only(left: 24, right: 16),\n            ),\n            const Divider(height: 1),\n            DialogFooter(\n              children: [\n                TextButton(\n                  child: Text(s.ok),\n                  onPressed: () => Navigator.of(context).pop(true),\n                ),\n                TextButton(\n                  onPressed: Navigator.of(context).pop,\n                  child: Text(s.cancel),\n                ),\n              ],\n            ),\n          ],\n        ),\n      ),\n    );\n    if (!(result ?? false)) return;\n\n    if (!mounted) return;\n    Dialogs.loading(context: context, hint: s.clearing);\n\n    await Backup.clearData([\n      \"avatar\",\n      if (chat) \"chat\",\n      if (audio) \"audio\",\n      if (image) \"image\",\n    ]);\n\n    if (chat) {\n      Config.chats.clear();\n      Current.clear();\n      Config.save();\n\n      ref.read(chatProvider.notifier).notify();\n      ref.read(chatsProvider.notifier).notify();\n      ref.read(messagesProvider.notifier).notify();\n    }\n\n    if (!mounted) return;\n    Navigator.of(context).pop();\n\n    Util.showSnackBar(\n      context: context,\n      content: Text(S.of(context).cleared_successfully),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/settings/settings.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"bot.dart\";\nimport \"api.dart\";\nimport \"config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\n\nclass SettingsPage extends StatefulWidget {\n  const SettingsPage({super.key});\n\n  @override\n  State<SettingsPage> createState() => _SettingsPageState();\n}\n\nclass _SettingsPageState extends State<SettingsPage> {\n  @override\n  Widget build(BuildContext context) {\n    return DefaultTabController(\n      length: 3,\n      child: Scaffold(\n        appBar: AppBar(\n          title: Text(S.of(context).settings),\n          bottom: TabBar(\n            tabs: [\n              Tab(text: S.of(context).config),\n              Tab(text: S.of(context).bots),\n              Tab(text: S.of(context).apis),\n            ],\n          ),\n        ),\n        body: TabBarView(\n          children: [\n            const ConfigTab(),\n            const BotsTab(),\n            const ApisTab(),\n          ],\n        ),\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/util.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"config.dart\";\nimport \"../gen/l10n.dart\";\nimport \"chat/current.dart\";\n\nimport \"dart:io\";\nimport \"package:flutter/services.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:share_plus/share_plus.dart\";\nimport \"package:flutter_svg/flutter_svg.dart\";\nimport \"package:url_launcher/url_launcher.dart\";\nimport \"package:image_gallery_saver_plus/image_gallery_saver_plus.dart\";\n\nclass Util {\n  static Future<void> copyText({\n    required BuildContext context,\n    required String text,\n  }) async {\n    await Clipboard.setData(ClipboardData(text: text));\n    if (!context.mounted) return;\n    Util.showSnackBar(\n      context: context,\n      content: Text(S.of(context).copied_successfully),\n    );\n  }\n\n  static Future<void> checkUpdate({\n    required BuildContext context,\n    required bool notify,\n  }) async {\n    try {\n      final info = await Updater.check();\n      if (!context.mounted) return;\n\n      if (info == null) {\n        if (notify) {\n          showSnackBar(\n            context: context,\n            content: Text(S.of(context).up_to_date),\n          );\n        }\n        return;\n      }\n\n      String changeLog = info[\"body\"];\n      String newVersion = info[\"tag_name\"];\n\n      showDialog(\n        context: context,\n        builder: (context) => AlertDialog(\n          title: Text(newVersion),\n          content: SingleChildScrollView(child: Text(changeLog)),\n          actions: [\n            TextButton(\n              onPressed: Navigator.of(context).pop,\n              child: Text(S.of(context).cancel),\n            ),\n            TextButton(\n              child: Text(S.of(context).download),\n              onPressed: () {\n                launchUrl(Uri.parse(Updater.latestUrl));\n                Navigator.of(context).pop();\n              },\n            ),\n          ],\n        ),\n      );\n    } catch (e) {\n      if (notify) Dialogs.error(context: context, error: e);\n    }\n  }\n\n  static bool checkChat(BuildContext context) {\n    final core = Current.core;\n    final coreOk = core.api != null && core.model != null;\n\n    if (!coreOk) {\n      showSnackBar(\n        context: context,\n        content: Text(S.of(context).setup_api_model_first),\n      );\n      return false;\n    }\n\n    if (Preferences.search) {\n      final search = Config.search;\n      final vector = Config.vector;\n      final vectorOk = vector.api != null && vector.model != null;\n      final searchOk = Preferences.googleSearch || search.searxng != null;\n\n      if (!searchOk) {\n        showSnackBar(\n          context: context,\n          content: Text(S.of(context).setup_searxng_first),\n        );\n        return false;\n      }\n\n      if ((search.vector ?? false) && !vectorOk) {\n        showSnackBar(\n          context: context,\n          content: Text(S.of(context).setup_vector_first),\n        );\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  static void showSnackBar({\n    required Text content,\n    required BuildContext context,\n    Duration duration = const Duration(milliseconds: 800),\n    SnackBarBehavior behavior = SnackBarBehavior.floating,\n  }) {\n    ScaffoldMessenger.of(context).showSnackBar(\n      SnackBar(\n        content: content,\n        duration: duration,\n        behavior: behavior,\n        dismissDirection: DismissDirection.down,\n      ),\n    );\n  }\n\n  static String formatDateTime(DateTime time) {\n    String two(int n) => n.toString().padLeft(2, '0');\n\n    return \"${two(time.month)}-${two(time.day)} \"\n        \"${two(time.hour)}:${two(time.minute)}\";\n  }\n}\n\nclass Dialogs {\n  static Future<List<String>?> input({\n    required BuildContext context,\n    required String title,\n    required List<InputDialogField> fields,\n  }) async {\n    return await showModalBottomSheet<List<String>>(\n      context: context,\n      useSafeArea: true,\n      isScrollControlled: true,\n      builder: (context) => Padding(\n        padding: EdgeInsets.only(\n          bottom: MediaQuery.of(context).viewInsets.bottom,\n        ),\n        child: InputDialog(\n          title: title,\n          fields: fields,\n        ),\n      ),\n    );\n  }\n\n  static void error({\n    required BuildContext context,\n    required dynamic error,\n  }) {\n    final info = error.toString();\n    showDialog(\n      context: context,\n      builder: (context) => AlertDialog(\n        title: Text(S.of(context).error),\n        content: SingleChildScrollView(child: SelectableText(info)),\n        actions: [\n          TextButton(\n            onPressed: Navigator.of(context).pop,\n            child: Text(S.of(context).cancel),\n          ),\n          TextButton(\n            onPressed: () {\n              Util.copyText(context: context, text: info);\n              Navigator.of(context).pop();\n            },\n            child: Text(S.of(context).copy),\n          ),\n        ],\n      ),\n    );\n  }\n\n  static Future<String?> select({\n    required BuildContext context,\n    required List<String> list,\n    required String title,\n    String? selected,\n  }) async {\n    return await showModalBottomSheet<String>(\n      context: context,\n      useSafeArea: true,\n      scrollControlDisabledMaxHeightRatio: 0.7,\n      builder: (context) => StatefulBuilder(\n        builder: (context, setState) => Column(\n          mainAxisSize: MainAxisSize.min,\n          crossAxisAlignment: CrossAxisAlignment.start,\n          children: [\n            DialogHeader(title: title),\n            const Divider(height: 1),\n            Flexible(\n              child: ListView.builder(\n                shrinkWrap: true,\n                itemCount: list.length,\n                itemBuilder: (context, index) => RadioListTile(\n                  value: list[index],\n                  groupValue: selected,\n                  title: Text(list[index]),\n                  contentPadding: const EdgeInsets.only(left: 16, right: 24),\n                  onChanged: (value) => setState(() => selected = value),\n                ),\n              ),\n            ),\n            const Divider(height: 1),\n            DialogFooter(\n              children: [\n                TextButton(\n                  onPressed: () => Navigator.of(context).pop(selected),\n                  child: Text(S.of(context).ok),\n                ),\n                TextButton(\n                  onPressed: Navigator.of(context).pop,\n                  child: Text(S.of(context).cancel),\n                ),\n              ],\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  static void loading({\n    required BuildContext context,\n    required String hint,\n    bool canPop = false,\n  }) {\n    showDialog(\n      context: context,\n      barrierDismissible: canPop,\n      builder: (context) => PopScope(\n        canPop: canPop,\n        child: AlertDialog(\n          contentPadding: const EdgeInsets.all(24),\n          content: Row(\n            children: [\n              const CircularProgressIndicator(),\n              const SizedBox(width: 24),\n              Text(hint),\n            ],\n          ),\n        ),\n      ),\n    );\n  }\n\n  static Future<void> openLink({\n    required BuildContext context,\n    required String? link,\n  }) async {\n    if (link == null) {\n      Util.showSnackBar(\n        context: context,\n        content: Text(S.of(context).empty_link),\n      );\n      return;\n    }\n\n    final result = await showDialog<int>(\n      context: context,\n      builder: (context) => AlertDialog(\n        title: Text(S.of(context).link),\n        content: Text(link),\n        actions: [\n          TextButton(\n            onPressed: () => Navigator.of(context).pop(1),\n            child: Text(S.of(context).copy),\n          ),\n          TextButton(\n            onPressed: () => Navigator.of(context).pop(2),\n            child: Text(S.of(context).open),\n          ),\n        ],\n      ),\n    );\n\n    switch (result) {\n      case 1:\n        if (!context.mounted) return;\n        Util.copyText(context: context, text: link);\n        break;\n\n      case 2:\n        final uri = Uri.parse(link);\n        if (await canLaunchUrl(uri)) {\n          launchUrl(uri, mode: LaunchMode.platformDefault);\n        } else {\n          if (!context.mounted) return;\n          Util.showSnackBar(\n            context: context,\n            content: Text(S.of(context).cannot_open),\n          );\n        }\n        break;\n    }\n  }\n\n  static Future<void> handleImage({\n    required BuildContext context,\n    required String path,\n  }) async {\n    final action = await showModalBottomSheet<int>(\n      context: context,\n      builder: (context) => Padding(\n        padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8),\n        child: Column(\n          mainAxisSize: MainAxisSize.min,\n          children: [\n            const DragHandle(),\n            ListTile(\n              minTileHeight: 48,\n              shape: StadiumBorder(),\n              title: Text(S.of(context).share),\n              onTap: () => Navigator.pop(context, 1),\n              leading: const Icon(Icons.share_outlined),\n            ),\n            ListTile(\n              minTileHeight: 48,\n              shape: StadiumBorder(),\n              title: Text(S.of(context).save),\n              onTap: () => Navigator.pop(context, 2),\n              leading: const Icon(Icons.save_outlined),\n            ),\n          ],\n        ),\n      ),\n    );\n    if (action == null) return;\n\n    if (!Platform.isAndroid) {\n      final uri = Uri.file(path);\n      launchUrl(uri);\n      return;\n    }\n\n    switch (action) {\n      case 1:\n        Share.shareXFiles([XFile(path)]);\n        break;\n\n      case 2:\n        final result = await ImageGallerySaverPlus.saveFile(path);\n        if (!context.mounted) return;\n        if (result is Map && result[\"isSuccess\"] == true) {\n          Util.showSnackBar(\n            context: context,\n            content: Text(S.of(context).saved_successfully),\n          );\n        }\n        break;\n    }\n  }\n}\n\nclass InputDialogField {\n  final String? text;\n  final String? hint;\n  final String? help;\n  final String? label;\n  final int? maxLines;\n\n  const InputDialogField({\n    this.hint,\n    this.text,\n    this.help,\n    this.label,\n    this.maxLines = 1,\n  });\n}\n\nclass InputDialog extends StatefulWidget {\n  final String title;\n  final List<InputDialogField> fields;\n\n  const InputDialog({\n    required this.title,\n    required this.fields,\n    super.key,\n  });\n\n  @override\n  State<InputDialog> createState() => _InputDialogState();\n}\n\nclass _InputDialogState extends State<InputDialog> {\n  late final List<TextEditingController> _ctrls;\n\n  @override\n  void initState() {\n    super.initState();\n    _ctrls = [\n      for (final field in widget.fields)\n        TextEditingController(text: field.text),\n    ];\n  }\n\n  @override\n  void dispose() {\n    for (final ctrl in _ctrls) {\n      ctrl.dispose();\n    }\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    final fields = widget.fields;\n\n    return Column(\n      mainAxisSize: MainAxisSize.min,\n      crossAxisAlignment: CrossAxisAlignment.start,\n      children: [\n        DialogHeader(\n          title: widget.title,\n          padding: const EdgeInsets.only(top: 16),\n        ),\n        Flexible(\n          child: ListView.separated(\n            shrinkWrap: true,\n            padding: const EdgeInsets.only(left: 24, right: 24),\n            itemCount: fields.length,\n            itemBuilder: (context, index) => TextField(\n              controller: _ctrls[index],\n              maxLines: fields[index].maxLines,\n              decoration: InputDecoration(\n                hintText: fields[index].hint,\n                labelText: fields[index].label,\n                helperText: fields[index].help,\n                border: const UnderlineInputBorder(),\n              ),\n            ),\n            separatorBuilder: (context, index) => const SizedBox(height: 8),\n          ),\n        ),\n        DialogFooter(\n          padding: const EdgeInsets.only(top: 16, bottom: 16),\n          children: [\n            TextButton(\n              onPressed: () => Navigator.of(context).pop(<String>[\n                for (final ctrl in _ctrls) ctrl.text,\n              ]),\n              child: Text(S.of(context).ok),\n            ),\n            TextButton(\n              onPressed: Navigator.of(context).pop,\n              child: Text(S.of(context).cancel),\n            ),\n          ],\n        ),\n      ],\n    );\n  }\n}\n\nclass InfoCard extends StatelessWidget {\n  final String info;\n\n  const InfoCard({\n    required this.info,\n    super.key,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    return Card.outlined(\n      margin: const EdgeInsets.only(left: 16, right: 16),\n      child: Padding(\n        padding: const EdgeInsets.only(top: 8, left: 12, right: 12, bottom: 8),\n        child: Row(\n          children: [\n            Icon(\n              Icons.info_outlined,\n              color: Theme.of(context).colorScheme.primary,\n              size: 20,\n            ),\n            const SizedBox(width: 8),\n            Expanded(\n              child: Text(\n                info,\n                style: Theme.of(context).textTheme.labelMedium,\n              ),\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n}\n\nclass ModelAvatar extends StatelessWidget {\n  final String? id;\n  static const String _prefix = \"assets/images\";\n  static const Map<String, String> _mappings = {\n    \"o1\": \"openai.svg\",\n    \"gpt\": \"openai.svg\",\n    \"claude\": \"claude.svg\",\n    \"gemini\": \"gemini.svg\",\n    \"grok\": \"grok.svg\",\n    \"qwen\": \"qwen.svg\",\n    \"llama\": \"ollama.svg\",\n    \"deepseek\": \"deepseek.svg\",\n  };\n  static final Map<String, SvgPicture?> _caches = {};\n\n  const ModelAvatar({\n    required this.id,\n    super.key,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    final image = _getImage(context);\n\n    if (image == null) {\n      return const CircleAvatar(\n        child: Icon(Icons.smart_toy),\n      );\n    }\n\n    return CircleAvatar(\n      child: image,\n    );\n  }\n\n  SvgPicture? _getImage(BuildContext context) {\n    if (id == null) return null;\n\n    final brightness = Theme.of(context).brightness;\n    final key = \"$id.${brightness.index}\";\n\n    return _caches.putIfAbsent(key, () {\n      String? fileName;\n      final modelId = id!.toLowerCase();\n\n      for (final pair in _mappings.entries) {\n        if (modelId.contains(pair.key)) {\n          fileName = pair.value;\n          break;\n        }\n      }\n\n      if (fileName == null) return null;\n\n      return SvgPicture.asset(\n        \"$_prefix/$fileName\",\n        colorFilter: ColorFilter.mode(\n          Theme.of(context).iconTheme.color!,\n          BlendMode.srcIn,\n        ),\n      );\n    });\n  }\n}\n\nclass DragHandle extends StatelessWidget {\n  final Size size;\n  final EdgeInsets margin;\n\n  const DragHandle({\n    this.size = const Size(32, 4),\n    this.margin = const EdgeInsets.only(\n      top: 16,\n      bottom: 8,\n    ),\n    super.key,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    return Center(\n      child: Padding(\n        padding: margin,\n        child: DecoratedBox(\n          decoration: BoxDecoration(\n            color: Theme.of(context).colorScheme.onSurfaceVariant,\n            borderRadius: BorderRadius.all(Radius.circular(2)),\n          ),\n          child: SizedBox.fromSize(size: size),\n        ),\n      ),\n    );\n  }\n}\n\nclass DialogHeader extends StatelessWidget {\n  final String title;\n  final EdgeInsets padding;\n\n  const DialogHeader({\n    required this.title,\n    this.padding = const EdgeInsets.only(\n      top: 16,\n      bottom: 16,\n    ),\n    super.key,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    return Padding(\n      padding: padding,\n      child: Row(\n        children: [\n          const SizedBox(width: 24),\n          Expanded(\n            child: Text(\n              title,\n              style: Theme.of(context).textTheme.headlineSmall,\n            ),\n          ),\n          IconButton(\n            icon: const Icon(Icons.close),\n            onPressed: Navigator.of(context).pop,\n          ),\n          const SizedBox(width: 12),\n        ],\n      ),\n    );\n  }\n}\n\nclass DialogFooter extends StatelessWidget {\n  final EdgeInsets padding;\n  final List<Widget> children;\n\n  const DialogFooter({\n    required this.children,\n    this.padding = const EdgeInsets.only(\n      top: 12,\n      bottom: 12,\n    ),\n    super.key,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    final child1 = children.elementAt(0);\n    final child2 = children.elementAtOrNull(1);\n    final child3 = children.elementAtOrNull(2);\n\n    return Padding(\n      padding: padding,\n      child: Row(\n        textDirection: TextDirection.rtl,\n        children: [\n          const SizedBox(width: 24),\n          child1,\n          const SizedBox(width: 8),\n          if (child2 != null) child2,\n          const Expanded(child: SizedBox()),\n          if (child3 != null) child3,\n          const SizedBox(width: 24),\n        ],\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "lib/workspace/document.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass DocumentTab extends ConsumerStatefulWidget {\n  const DocumentTab({super.key});\n\n  @override\n  ConsumerState<DocumentTab> createState() => _DocumentTabState();\n}\n\nclass _DocumentTabState extends ConsumerState<DocumentTab> {\n  @override\n  Widget build(BuildContext context) {\n    final s = S.of(context);\n    const padding = EdgeInsets.only(left: 24, right: 24);\n    final primaryColor = Theme.of(context).colorScheme.primary;\n\n    return ListView(\n      padding: const EdgeInsets.only(top: 16, bottom: 8),\n      children: [\n        Padding(\n          padding: padding,\n          child: Text(\n            s.embedding_vector,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.api),\n          contentPadding: padding,\n          subtitle: Text(Config.vector.api ?? s.empty),\n          onTap: () async {\n            if (Config.apis.isEmpty) return;\n\n            final api = await Dialogs.select(\n              context: context,\n              list: Config.apis.keys.toList(),\n              selected: Config.vector.api,\n              title: s.choose_api,\n            );\n            if (api == null) return;\n\n            setState(() => Config.vector.api = api);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.model),\n          contentPadding: padding,\n          subtitle: Text(Config.vector.model ?? s.empty),\n          onTap: () async {\n            final models = Config.apis[Config.vector.api]?.models;\n            if (models == null) return;\n\n            final model = await Dialogs.select(\n              context: context,\n              selected: Config.vector.model,\n              title: s.choose_model,\n              list: models,\n            );\n            if (model == null) return;\n\n            setState(() => Config.vector.model = model);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.vector_batch_size),\n          contentPadding: padding,\n          subtitle: Text(s.vector_batch_size_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.vector_batch_size,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  hint: \"64\",\n                  text: Config.vector.batchSize?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? value;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              value = int.tryParse(text);\n              if (value == null) return;\n            }\n\n            Config.vector.batchSize = value;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.vector_dimensions),\n          contentPadding: padding,\n          subtitle: Text(s.vector_dimensions_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.vector_dimensions,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.vector.dimensions?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? value;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              value = int.tryParse(text);\n              if (value == null) return;\n            }\n\n            Config.vector.dimensions = value;\n            Config.save();\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.embedding_vector_info),\n        const SizedBox(height: 16),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.document_config,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        ListTile(\n          title: Text(s.chunk_n),\n          contentPadding: padding,\n          subtitle: Text(s.chunk_n_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.chunk_n,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  hint: \"8\",\n                  text: Config.document.n?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? value;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              value = int.tryParse(text);\n              if (value == null) return;\n            }\n\n            Config.document.n = value;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.chunk_size),\n          contentPadding: padding,\n          subtitle: Text(s.chunk_size_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.chunk_size,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  hint: \"2000\",\n                  text: Config.document.size?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? value;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              value = int.tryParse(text);\n              if (value == null) return;\n            }\n\n            Config.document.size = value;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.chunk_overlap),\n          contentPadding: padding,\n          subtitle: Text(s.chunk_overlap_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.chunk_overlap,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  hint: \"100\",\n                  text: Config.document.overlap?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? value;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              value = int.tryParse(text);\n              if (value == null) return;\n            }\n\n            Config.document.overlap = value;\n            Config.save();\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.document_config_hint),\n        const SizedBox(height: 8),\n      ],\n    );\n  }\n}\n"
  },
  {
    "path": "lib/workspace/model.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../gen/l10n.dart\";\nimport \"../chat/chat.dart\";\n\nimport \"package:chatbot/config.dart\";\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass ModelTab extends ConsumerWidget {\n  const ModelTab({super.key});\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    ref.watch(chatProvider);\n\n    final modelSet = <String>{};\n    for (final api in Config.apis.values) {\n      modelSet.addAll(api.models);\n    }\n    final modelList = modelSet.toList();\n\n    return ListView.separated(\n      key: ValueKey(Theme.of(context).brightness),\n      padding: const EdgeInsets.all(16),\n      itemCount: modelList.length,\n      itemBuilder: (context, index) {\n        final id = modelList[index];\n\n        return Card.filled(\n          color: Theme.of(context).colorScheme.surfaceContainer,\n          margin: EdgeInsets.zero,\n          child: ListTile(\n            leading: ModelAvatar(id: id),\n            shape: const RoundedRectangleBorder(\n              borderRadius: BorderRadius.all(Radius.circular(12)),\n            ),\n            title: Text(\n              Config.models[id]?.name ?? id,\n              overflow: TextOverflow.ellipsis,\n            ),\n            subtitle: Text(\n              id,\n              overflow: TextOverflow.ellipsis,\n            ),\n            titleTextStyle: Theme.of(context).textTheme.titleMedium,\n            subtitleTextStyle: Theme.of(context).textTheme.bodySmall,\n            onTap: () => showModalBottomSheet(\n              context: context,\n              useSafeArea: true,\n              isScrollControlled: true,\n              builder: (context) => Padding(\n                padding: EdgeInsets.only(\n                  bottom: MediaQuery.of(context).viewInsets.bottom,\n                ),\n                child: ModelSettings(id: id),\n              ),\n            ),\n          ),\n        );\n      },\n      separatorBuilder: (context, index) => const SizedBox(height: 12),\n    );\n  }\n}\n\nclass ModelSettings extends ConsumerStatefulWidget {\n  final String id;\n\n  const ModelSettings({\n    required this.id,\n    super.key,\n  });\n\n  @override\n  ConsumerState<ModelSettings> createState() => _ModelEditorState();\n}\n\nclass _ModelEditorState extends ConsumerState<ModelSettings> {\n  late String _id;\n  late bool? _chat;\n  late final ModelConfig? _model;\n  late final TextEditingController _ctrl;\n\n  @override\n  void initState() {\n    super.initState();\n    _id = widget.id;\n    _model = Config.models[_id];\n    _chat = _model?.chat;\n    _ctrl = TextEditingController(\n      text: _model?.name ?? _id,\n    );\n  }\n\n  @override\n  void dispose() {\n    _ctrl.dispose();\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Column(\n      mainAxisSize: MainAxisSize.min,\n      crossAxisAlignment: CrossAxisAlignment.start,\n      children: [\n        DialogHeader(title: S.of(context).model),\n        const Divider(height: 1),\n        const SizedBox(height: 8),\n        Row(\n          children: [\n            const SizedBox(width: 24),\n            Expanded(\n              child: TextField(\n                controller: _ctrl,\n                decoration: InputDecoration(\n                  labelText: S.of(context).model_name,\n                  border: const UnderlineInputBorder(),\n                ),\n              ),\n            ),\n            IconButton(\n              icon: const Icon(Icons.transform),\n              onPressed: _idToName,\n            ),\n            const SizedBox(width: 12),\n          ],\n        ),\n        const SizedBox(height: 8),\n        CheckboxListTile(\n          value: _chat ?? true,\n          title: Text(S.of(context).chat_model),\n          subtitle: Text(S.of(context).chat_model_hint),\n          onChanged: (value) => setState(() => _chat = value),\n          contentPadding: const EdgeInsets.only(left: 24, right: 16),\n        ),\n        const Divider(height: 1),\n        DialogFooter(\n          children: [\n            TextButton(\n              onPressed: _save,\n              child: Text(S.of(context).ok),\n            ),\n            TextButton(\n              onPressed: Navigator.of(context).pop,\n              child: Text(S.of(context).cancel),\n            ),\n          ],\n        ),\n      ],\n    );\n  }\n\n  void _idToName() {\n    String name = _id;\n    final slash = name.indexOf('/');\n    if (slash != -1) name = name.substring(slash + 1);\n\n    var parts = name.split('-');\n    parts.removeWhere((it) => it.isEmpty);\n    parts =\n        parts.map((it) => \"${it[0].toUpperCase()}${it.substring(1)}\").toList();\n\n    _ctrl.text = parts.join(' ');\n  }\n\n  Future<void> _save() async {\n    final name = _ctrl.text;\n    if (name.isEmpty) return;\n\n    final chat = _chat ?? true;\n    Config.models[_id] = ModelConfig(\n      name: name,\n      chat: chat,\n    );\n    Config.save();\n\n    ref.read(messagesProvider.notifier).notify();\n    ref.read(chatProvider.notifier).notify();\n    if (mounted) Navigator.of(context).pop();\n  }\n}\n"
  },
  {
    "path": "lib/workspace/task.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"../util.dart\";\nimport \"../config.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass TaskTab extends ConsumerStatefulWidget {\n  const TaskTab({super.key});\n\n  @override\n  ConsumerState<TaskTab> createState() => _TaskTabState();\n}\n\nclass _TaskTabState extends ConsumerState<TaskTab> {\n  @override\n  Widget build(BuildContext context) {\n    final s = S.of(context);\n    const padding = EdgeInsets.only(left: 24, right: 24);\n    final primaryColor = Theme.of(context).colorScheme.primary;\n\n    return ListView(\n      padding: const EdgeInsets.only(top: 16, bottom: 8),\n      children: [\n        Padding(\n          padding: padding,\n          child: Text(\n            s.title_generation,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        CheckboxListTile(\n          title: Text(s.enable),\n          subtitle: Text(s.title_enable_hint),\n          contentPadding: const EdgeInsets.only(left: 24, right: 16),\n          value: Config.title.enable ?? false,\n          onChanged: (value) {\n            setState(() => Config.title.enable = value);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.api),\n          contentPadding: padding,\n          subtitle: Text(Config.title.api ?? s.empty),\n          onTap: () async {\n            if (Config.apis.isEmpty) return;\n\n            final api = await Dialogs.select(\n              context: context,\n              list: Config.apis.keys.toList(),\n              selected: Config.title.api,\n              title: s.choose_api,\n            );\n            if (api == null) return;\n\n            setState(() => Config.title.api = api);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.model),\n          contentPadding: padding,\n          subtitle: Text(Config.title.model ?? s.empty),\n          onTap: () async {\n            final models = Config.apis[Config.title.api]?.models;\n            if (models == null) return;\n\n            final model = await Dialogs.select(\n              context: context,\n              selected: Config.title.model,\n              title: s.choose_model,\n              list: models,\n            );\n            if (model == null) return;\n\n            setState(() => Config.title.model = model);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.title_prompt),\n          contentPadding: padding,\n          subtitle: Text(s.title_prompt_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.title_prompt,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.title.prompt,\n                  maxLines: null,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            String? prompt;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) prompt = text;\n\n            Config.title.prompt = prompt;\n            Config.save();\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.title_generation_hint(\"{text}\")),\n        const SizedBox(height: 16),\n        Padding(\n          padding: padding,\n          child: Text(\n            s.web_search,\n            style: TextStyle(color: primaryColor),\n          ),\n        ),\n        CheckboxListTile(\n          title: Text(s.search_vector),\n          subtitle: Text(s.search_vector_hint),\n          contentPadding: const EdgeInsets.only(left: 24, right: 16),\n          value: Config.search.vector ?? false,\n          onChanged: (value) {\n            setState(() => Config.search.vector = value);\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.search_searxng),\n          contentPadding: padding,\n          subtitle: Text(s.search_searxng_hint),\n          onTap: () async {\n            String? base;\n            String? extra;\n\n            final searxng = Config.search.searxng;\n            const fixedPart = \"q={text}&format=json\";\n\n            if (searxng != null) {\n              final uri = Uri.parse(searxng);\n              base = \"${uri.scheme}://${uri.host}\";\n              extra = uri.queryParameters.entries\n                  .map((it) => \"${it.key}=${it.value}\")\n                  .join('&');\n              extra = extra.replaceFirst(fixedPart, \"\");\n              if (extra.startsWith('&')) extra = extra.replaceFirst('&', \"\");\n            }\n\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.search_searxng,\n              fields: [\n                InputDialogField(\n                  text: base,\n                  label: s.search_searxng_base,\n                  hint: \"https://your.searxng.com\",\n                ),\n                InputDialogField(\n                  text: extra,\n                  label: s.search_searxng_extra,\n                  help: s.search_searxng_extra_help,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            String? newBase;\n            String? newExtra;\n            final text1 = texts[0].trim();\n            final text2 = texts[1].trim();\n            if (text1.isNotEmpty) newBase = text1;\n            if (text2.isNotEmpty) newExtra = text2;\n\n            String? full;\n            if (newBase != null) {\n              full = \"$newBase/search?$fixedPart\";\n              if (newExtra != null) full += \"&$newExtra\";\n            }\n\n            Config.search.searxng = full;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.search_timeout),\n          contentPadding: padding,\n          subtitle: Text(s.search_timeout_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.search_timeout,\n              fields: [\n                InputDialogField(\n                  hint: \"3000\",\n                  label: s.search_timeout_query,\n                  help: s.search_timeout_query_help,\n                  text: Config.search.queryTime?.toString(),\n                ),\n                InputDialogField(\n                  hint: \"2000\",\n                  label: s.search_timeout_fetch,\n                  help: s.search_timeout_fetch_help,\n                  text: Config.search.fetchTime?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? query;\n            int? fetch;\n            final text1 = texts[0].trim();\n            final text2 = texts[1].trim();\n            if (text1.isNotEmpty) {\n              query = int.tryParse(text1);\n              if (query == null) return;\n            }\n            if (text2.isNotEmpty) {\n              fetch = int.tryParse(text2);\n              if (fetch == null) return;\n            }\n\n            Config.search.queryTime = query;\n            Config.search.fetchTime = fetch;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.search_n),\n          contentPadding: padding,\n          subtitle: Text(s.search_n_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.search_n,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  hint: \"64\",\n                  text: Config.search.n?.toString(),\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            int? n;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) {\n              n = int.tryParse(text);\n              if (n == null) return;\n            }\n\n            Config.search.n = n;\n            Config.save();\n          },\n        ),\n        const Divider(height: 1),\n        ListTile(\n          title: Text(s.search_prompt),\n          contentPadding: padding,\n          subtitle: Text(s.search_prompt_hint),\n          onTap: () async {\n            final texts = await Dialogs.input(\n              context: context,\n              title: s.search_prompt,\n              fields: [\n                InputDialogField(\n                  label: s.please_input,\n                  text: Config.search.prompt,\n                ),\n              ],\n            );\n            if (texts == null) return;\n\n            String? prompt;\n            final text = texts[0].trim();\n            if (text.isNotEmpty) prompt = text;\n\n            Config.search.prompt = prompt;\n            Config.save();\n          },\n        ),\n        const SizedBox(height: 4),\n        InfoCard(info: s.search_prompt_info(\"{pages}\", \"{text}\")),\n        const SizedBox(height: 8),\n      ],\n    );\n  }\n}\n"
  },
  {
    "path": "lib/workspace/workspace.dart",
    "content": "// This file is part of ChatBot.\n//\n// ChatBot is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// ChatBot is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with ChatBot. If not, see <https://www.gnu.org/licenses/>.\n\nimport \"task.dart\";\nimport \"model.dart\";\nimport \"document.dart\";\nimport \"../gen/l10n.dart\";\n\nimport \"package:flutter/material.dart\";\nimport \"package:flutter_riverpod/flutter_riverpod.dart\";\n\nclass WorkspacePage extends ConsumerWidget {\n  const WorkspacePage({super.key});\n\n  @override\n  Widget build(BuildContext context, WidgetRef ref) {\n    return DefaultTabController(\n      length: 3,\n      child: Scaffold(\n        appBar: AppBar(\n          title: Text(S.of(context).workspace),\n          bottom: TabBar(\n            tabs: [\n              Tab(text: S.of(context).model),\n              Tab(text: S.of(context).task),\n              Tab(text: S.of(context).document),\n            ],\n          ),\n        ),\n        body: TabBarView(\n          children: [\n            const ModelTab(),\n            const TaskTab(),\n            const DocumentTab(),\n          ],\n        ),\n      ),\n    );\n  }\n}\n"
  },
  {
    "path": "linux/.gitignore",
    "content": "flutter/ephemeral\n"
  },
  {
    "path": "linux/CMakeLists.txt",
    "content": "# Project-level configuration.\ncmake_minimum_required(VERSION 3.10)\nproject(runner LANGUAGES CXX)\n\n# The name of the executable created for the application. Change this to change\n# the on-disk name of your application.\nset(BINARY_NAME \"chatbot\")\n# The unique GTK application identifier for this application. See:\n# https://wiki.gnome.org/HowDoI/ChooseApplicationID\nset(APPLICATION_ID \"cc.arthur63.chatbot\")\n\n# Explicitly opt in to modern CMake behaviors to avoid warnings with recent\n# versions of CMake.\ncmake_policy(SET CMP0063 NEW)\n\n# Load bundled libraries from the lib/ directory relative to the binary.\nset(CMAKE_INSTALL_RPATH \"$ORIGIN/lib\")\n\n# Root filesystem for cross-building.\nif(FLUTTER_TARGET_PLATFORM_SYSROOT)\n  set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})\n  set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})\n  set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n  set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)\n  set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\n  set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\nendif()\n\n# Define build configuration options.\nif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)\n  set(CMAKE_BUILD_TYPE \"Debug\" CACHE\n    STRING \"Flutter build mode\" FORCE)\n  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS\n    \"Debug\" \"Profile\" \"Release\")\nendif()\n\n# Compilation settings that should be applied to most targets.\n#\n# Be cautious about adding new options here, as plugins use this function by\n# default. In most cases, you should add new options to specific targets instead\n# of modifying this function.\nfunction(APPLY_STANDARD_SETTINGS TARGET)\n  target_compile_features(${TARGET} PUBLIC cxx_std_14)\n  target_compile_options(${TARGET} PRIVATE -Wall -Werror)\n  target_compile_options(${TARGET} PRIVATE \"$<$<NOT:$<CONFIG:Debug>>:-O3>\")\n  target_compile_definitions(${TARGET} PRIVATE \"$<$<NOT:$<CONFIG:Debug>>:NDEBUG>\")\nendfunction()\n\n# Flutter library and tool build rules.\nset(FLUTTER_MANAGED_DIR \"${CMAKE_CURRENT_SOURCE_DIR}/flutter\")\nadd_subdirectory(${FLUTTER_MANAGED_DIR})\n\n# System-level dependencies.\nfind_package(PkgConfig REQUIRED)\npkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)\n\nadd_definitions(-DAPPLICATION_ID=\"${APPLICATION_ID}\")\n\n# Define the application target. To change its name, change BINARY_NAME above,\n# not the value here, or `flutter run` will no longer work.\n#\n# Any new source files that you add to the application should be added here.\nadd_executable(${BINARY_NAME}\n  \"main.cc\"\n  \"my_application.cc\"\n  \"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc\"\n)\n\n# Apply the standard set of build settings. This can be removed for applications\n# that need different build settings.\napply_standard_settings(${BINARY_NAME})\n\n# Add dependency libraries. Add any application-specific dependencies here.\ntarget_link_libraries(${BINARY_NAME} PRIVATE flutter)\ntarget_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)\n\n# Run the Flutter tool portions of the build. This must not be removed.\nadd_dependencies(${BINARY_NAME} flutter_assemble)\n\n# Only the install-generated bundle's copy of the executable will launch\n# correctly, since the resources must in the right relative locations. To avoid\n# people trying to run the unbundled copy, put it in a subdirectory instead of\n# the default top-level location.\nset_target_properties(${BINARY_NAME}\n  PROPERTIES\n  RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/intermediates_do_not_run\"\n)\n\n\n# Generated plugin build rules, which manage building the plugins and adding\n# them to the application.\ninclude(flutter/generated_plugins.cmake)\n\n\n# === Installation ===\n# By default, \"installing\" just makes a relocatable bundle in the build\n# directory.\nset(BUILD_BUNDLE_DIR \"${PROJECT_BINARY_DIR}/bundle\")\nif(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)\n  set(CMAKE_INSTALL_PREFIX \"${BUILD_BUNDLE_DIR}\" CACHE PATH \"...\" FORCE)\nendif()\n\n# Start with a clean build bundle directory every time.\ninstall(CODE \"\n  file(REMOVE_RECURSE \\\"${BUILD_BUNDLE_DIR}/\\\")\n  \" COMPONENT Runtime)\n\nset(INSTALL_BUNDLE_DATA_DIR \"${CMAKE_INSTALL_PREFIX}/data\")\nset(INSTALL_BUNDLE_LIB_DIR \"${CMAKE_INSTALL_PREFIX}/lib\")\n\ninstall(TARGETS ${BINARY_NAME} RUNTIME DESTINATION \"${CMAKE_INSTALL_PREFIX}\"\n  COMPONENT Runtime)\n\ninstall(FILES \"${FLUTTER_ICU_DATA_FILE}\" DESTINATION \"${INSTALL_BUNDLE_DATA_DIR}\"\n  COMPONENT Runtime)\n\ninstall(FILES \"${FLUTTER_LIBRARY}\" DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n  COMPONENT Runtime)\n\nforeach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})\n  install(FILES \"${bundled_library}\"\n    DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n    COMPONENT Runtime)\nendforeach(bundled_library)\n\n# Copy the native assets provided by the build.dart from all packages.\nset(NATIVE_ASSETS_DIR \"${PROJECT_BUILD_DIR}native_assets/linux/\")\ninstall(DIRECTORY \"${NATIVE_ASSETS_DIR}\"\n   DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n   COMPONENT Runtime)\n\n# Fully re-copy the assets directory on each build to avoid having stale files\n# from a previous install.\nset(FLUTTER_ASSET_DIR_NAME \"flutter_assets\")\ninstall(CODE \"\n  file(REMOVE_RECURSE \\\"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\\\")\n  \" COMPONENT Runtime)\ninstall(DIRECTORY \"${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}\"\n  DESTINATION \"${INSTALL_BUNDLE_DATA_DIR}\" COMPONENT Runtime)\n\n# Install the AOT library on non-Debug builds only.\nif(NOT CMAKE_BUILD_TYPE MATCHES \"Debug\")\n  install(FILES \"${AOT_LIBRARY}\" DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n    COMPONENT Runtime)\nendif()\n"
  },
  {
    "path": "linux/flutter/CMakeLists.txt",
    "content": "# This file controls Flutter-level build steps. It should not be edited.\ncmake_minimum_required(VERSION 3.10)\n\nset(EPHEMERAL_DIR \"${CMAKE_CURRENT_SOURCE_DIR}/ephemeral\")\n\n# Configuration provided via flutter tool.\ninclude(${EPHEMERAL_DIR}/generated_config.cmake)\n\n# TODO: Move the rest of this into files in ephemeral. See\n# https://github.com/flutter/flutter/issues/57146.\n\n# Serves the same purpose as list(TRANSFORM ... PREPEND ...),\n# which isn't available in 3.10.\nfunction(list_prepend LIST_NAME PREFIX)\n    set(NEW_LIST \"\")\n    foreach(element ${${LIST_NAME}})\n        list(APPEND NEW_LIST \"${PREFIX}${element}\")\n    endforeach(element)\n    set(${LIST_NAME} \"${NEW_LIST}\" PARENT_SCOPE)\nendfunction()\n\n# === Flutter Library ===\n# System-level dependencies.\nfind_package(PkgConfig REQUIRED)\npkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)\npkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)\npkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)\n\nset(FLUTTER_LIBRARY \"${EPHEMERAL_DIR}/libflutter_linux_gtk.so\")\n\n# Published to parent scope for install step.\nset(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)\nset(FLUTTER_ICU_DATA_FILE \"${EPHEMERAL_DIR}/icudtl.dat\" PARENT_SCOPE)\nset(PROJECT_BUILD_DIR \"${PROJECT_DIR}/build/\" PARENT_SCOPE)\nset(AOT_LIBRARY \"${PROJECT_DIR}/build/lib/libapp.so\" PARENT_SCOPE)\n\nlist(APPEND FLUTTER_LIBRARY_HEADERS\n  \"fl_basic_message_channel.h\"\n  \"fl_binary_codec.h\"\n  \"fl_binary_messenger.h\"\n  \"fl_dart_project.h\"\n  \"fl_engine.h\"\n  \"fl_json_message_codec.h\"\n  \"fl_json_method_codec.h\"\n  \"fl_message_codec.h\"\n  \"fl_method_call.h\"\n  \"fl_method_channel.h\"\n  \"fl_method_codec.h\"\n  \"fl_method_response.h\"\n  \"fl_plugin_registrar.h\"\n  \"fl_plugin_registry.h\"\n  \"fl_standard_message_codec.h\"\n  \"fl_standard_method_codec.h\"\n  \"fl_string_codec.h\"\n  \"fl_value.h\"\n  \"fl_view.h\"\n  \"flutter_linux.h\"\n)\nlist_prepend(FLUTTER_LIBRARY_HEADERS \"${EPHEMERAL_DIR}/flutter_linux/\")\nadd_library(flutter INTERFACE)\ntarget_include_directories(flutter INTERFACE\n  \"${EPHEMERAL_DIR}\"\n)\ntarget_link_libraries(flutter INTERFACE \"${FLUTTER_LIBRARY}\")\ntarget_link_libraries(flutter INTERFACE\n  PkgConfig::GTK\n  PkgConfig::GLIB\n  PkgConfig::GIO\n)\nadd_dependencies(flutter flutter_assemble)\n\n# === Flutter tool backend ===\n# _phony_ is a non-existent file to force this command to run every time,\n# since currently there's no way to get a full input/output list from the\n# flutter tool.\nadd_custom_command(\n  OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}\n    ${CMAKE_CURRENT_BINARY_DIR}/_phony_\n  COMMAND ${CMAKE_COMMAND} -E env\n    ${FLUTTER_TOOL_ENVIRONMENT}\n    \"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh\"\n      ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}\n  VERBATIM\n)\nadd_custom_target(flutter_assemble DEPENDS\n  \"${FLUTTER_LIBRARY}\"\n  ${FLUTTER_LIBRARY_HEADERS}\n)\n"
  },
  {
    "path": "linux/flutter/generated_plugin_registrant.cc",
    "content": "//\n//  Generated file. Do not edit.\n//\n\n// clang-format off\n\n#include \"generated_plugin_registrant.h\"\n\n#include <audioplayers_linux/audioplayers_linux_plugin.h>\n#include <file_selector_linux/file_selector_plugin.h>\n#include <objectbox_flutter_libs/objectbox_flutter_libs_plugin.h>\n#include <url_launcher_linux/url_launcher_plugin.h>\n\nvoid fl_register_plugins(FlPluginRegistry* registry) {\n  g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar =\n      fl_plugin_registry_get_registrar_for_plugin(registry, \"AudioplayersLinuxPlugin\");\n  audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar);\n  g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =\n      fl_plugin_registry_get_registrar_for_plugin(registry, \"FileSelectorPlugin\");\n  file_selector_plugin_register_with_registrar(file_selector_linux_registrar);\n  g_autoptr(FlPluginRegistrar) objectbox_flutter_libs_registrar =\n      fl_plugin_registry_get_registrar_for_plugin(registry, \"ObjectboxFlutterLibsPlugin\");\n  objectbox_flutter_libs_plugin_register_with_registrar(objectbox_flutter_libs_registrar);\n  g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =\n      fl_plugin_registry_get_registrar_for_plugin(registry, \"UrlLauncherPlugin\");\n  url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);\n}\n"
  },
  {
    "path": "linux/flutter/generated_plugin_registrant.h",
    "content": "//\n//  Generated file. Do not edit.\n//\n\n// clang-format off\n\n#ifndef GENERATED_PLUGIN_REGISTRANT_\n#define GENERATED_PLUGIN_REGISTRANT_\n\n#include <flutter_linux/flutter_linux.h>\n\n// Registers Flutter plugins.\nvoid fl_register_plugins(FlPluginRegistry* registry);\n\n#endif  // GENERATED_PLUGIN_REGISTRANT_\n"
  },
  {
    "path": "linux/flutter/generated_plugins.cmake",
    "content": "#\n# Generated file, do not edit.\n#\n\nlist(APPEND FLUTTER_PLUGIN_LIST\n  audioplayers_linux\n  file_selector_linux\n  objectbox_flutter_libs\n  url_launcher_linux\n)\n\nlist(APPEND FLUTTER_FFI_PLUGIN_LIST\n)\n\nset(PLUGIN_BUNDLED_LIBRARIES)\n\nforeach(plugin ${FLUTTER_PLUGIN_LIST})\n  add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})\n  target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})\nendforeach(plugin)\n\nforeach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})\n  add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})\nendforeach(ffi_plugin)\n"
  },
  {
    "path": "linux/main.cc",
    "content": "#include \"my_application.h\"\n\nint main(int argc, char** argv) {\n  g_autoptr(MyApplication) app = my_application_new();\n  return g_application_run(G_APPLICATION(app), argc, argv);\n}\n"
  },
  {
    "path": "linux/my_application.cc",
    "content": "#include \"my_application.h\"\n\n#include <flutter_linux/flutter_linux.h>\n#ifdef GDK_WINDOWING_X11\n#include <gdk/gdkx.h>\n#endif\n\n#include \"flutter/generated_plugin_registrant.h\"\n\nstruct _MyApplication {\n  GtkApplication parent_instance;\n  char** dart_entrypoint_arguments;\n};\n\nG_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)\n\n// Implements GApplication::activate.\nstatic void my_application_activate(GApplication* application) {\n  MyApplication* self = MY_APPLICATION(application);\n  GtkWindow* window =\n      GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));\n\n  // Use a header bar when running in GNOME as this is the common style used\n  // by applications and is the setup most users will be using (e.g. Ubuntu\n  // desktop).\n  // If running on X and not using GNOME then just use a traditional title bar\n  // in case the window manager does more exotic layout, e.g. tiling.\n  // If running on Wayland assume the header bar will work (may need changing\n  // if future cases occur).\n  gboolean use_header_bar = TRUE;\n#ifdef GDK_WINDOWING_X11\n  GdkScreen* screen = gtk_window_get_screen(window);\n  if (GDK_IS_X11_SCREEN(screen)) {\n    const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);\n    if (g_strcmp0(wm_name, \"GNOME Shell\") != 0) {\n      use_header_bar = FALSE;\n    }\n  }\n#endif\n  if (use_header_bar) {\n    GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());\n    gtk_widget_show(GTK_WIDGET(header_bar));\n    gtk_header_bar_set_title(header_bar, \"chatbot\");\n    gtk_header_bar_set_show_close_button(header_bar, TRUE);\n    gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));\n  } else {\n    gtk_window_set_title(window, \"chatbot\");\n  }\n\n  gtk_window_set_default_size(window, 1280, 720);\n  gtk_widget_show(GTK_WIDGET(window));\n\n  g_autoptr(FlDartProject) project = fl_dart_project_new();\n  fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);\n\n  FlView* view = fl_view_new(project);\n  gtk_widget_show(GTK_WIDGET(view));\n  gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));\n\n  fl_register_plugins(FL_PLUGIN_REGISTRY(view));\n\n  gtk_widget_grab_focus(GTK_WIDGET(view));\n}\n\n// Implements GApplication::local_command_line.\nstatic gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {\n  MyApplication* self = MY_APPLICATION(application);\n  // Strip out the first argument as it is the binary name.\n  self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);\n\n  g_autoptr(GError) error = nullptr;\n  if (!g_application_register(application, nullptr, &error)) {\n     g_warning(\"Failed to register: %s\", error->message);\n     *exit_status = 1;\n     return TRUE;\n  }\n\n  g_application_activate(application);\n  *exit_status = 0;\n\n  return TRUE;\n}\n\n// Implements GApplication::startup.\nstatic void my_application_startup(GApplication* application) {\n  //MyApplication* self = MY_APPLICATION(object);\n\n  // Perform any actions required at application startup.\n\n  G_APPLICATION_CLASS(my_application_parent_class)->startup(application);\n}\n\n// Implements GApplication::shutdown.\nstatic void my_application_shutdown(GApplication* application) {\n  //MyApplication* self = MY_APPLICATION(object);\n\n  // Perform any actions required at application shutdown.\n\n  G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);\n}\n\n// Implements GObject::dispose.\nstatic void my_application_dispose(GObject* object) {\n  MyApplication* self = MY_APPLICATION(object);\n  g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);\n  G_OBJECT_CLASS(my_application_parent_class)->dispose(object);\n}\n\nstatic void my_application_class_init(MyApplicationClass* klass) {\n  G_APPLICATION_CLASS(klass)->activate = my_application_activate;\n  G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;\n  G_APPLICATION_CLASS(klass)->startup = my_application_startup;\n  G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;\n  G_OBJECT_CLASS(klass)->dispose = my_application_dispose;\n}\n\nstatic void my_application_init(MyApplication* self) {}\n\nMyApplication* my_application_new() {\n  return MY_APPLICATION(g_object_new(my_application_get_type(),\n                                     \"application-id\", APPLICATION_ID,\n                                     \"flags\", G_APPLICATION_NON_UNIQUE,\n                                     nullptr));\n}\n"
  },
  {
    "path": "linux/my_application.h",
    "content": "#ifndef FLUTTER_MY_APPLICATION_H_\n#define FLUTTER_MY_APPLICATION_H_\n\n#include <gtk/gtk.h>\n\nG_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,\n                     GtkApplication)\n\n/**\n * my_application_new:\n *\n * Creates a new Flutter-based application.\n *\n * Returns: a new #MyApplication.\n */\nMyApplication* my_application_new();\n\n#endif  // FLUTTER_MY_APPLICATION_H_\n"
  },
  {
    "path": "pubspec.yaml",
    "content": "name: chatbot\nversion: 0.3.5+15\ndescription: ChatBot\n\nenvironment:\n  sdk: ^3.5.4\n\ndependencies:\n  flutter:\n    sdk: flutter\n  flutter_localizations:\n    sdk: flutter\n\n  http: ^1.2.2\n  intl: ^0.19.0\n  archive: ^4.0.2\n\n  animate_do: ^3.3.4\n  flutter_svg: ^2.0.16\n  flutter_spinkit: ^5.2.1\n  flutter_riverpod: ^2.6.1\n\n  markdown: ^7.2.2\n  flutter_math_fork: ^0.7.2\n  flutter_markdown: ^0.7.4+2\n  flutter_highlighter: ^0.1.1\n\n  file_picker: ^8.1.4\n  image_picker: ^1.1.2\n  path_provider: ^2.1.5\n  shared_preferences: ^2.3.4\n  flutter_image_compress: ^2.3.0\n\n  langchain: ^0.7.7+2\n  langchain_core: ^0.3.6+1\n  langchain_openai: ^0.7.3\n  langchain_google: ^0.6.4+2\n  langchain_community: ^0.3.3\n\n  objectbox: ^4.0.3\n  objectbox_flutter_libs: ^4.0.3\n\n  screenshot: ^3.0.0\n  share_plus: ^10.1.2\n  url_launcher: ^6.3.1\n  audioplayers: ^6.1.0\n  package_info_plus: ^8.1.2\n  beautiful_soup_dart: ^0.3.0\n  image_gallery_saver_plus: ^3.0.5\n\ndependency_overrides:\n  path: 1.9.1\n\ndev_dependencies:\n  intl_utils: ^2.8.8\n  build_runner: ^2.4.13\n  flutter_lints: ^5.0.0\n  objectbox_generator: ^4.0.3\n\nflutter:\n  assets:\n    - assets/images/\n  uses-material-design: true\n\nflutter_intl:\n  enabled: true\n  class_name: S\n  main_locale: en\n  arb_dir: lib/l10n\n  output_dir: lib/gen\n"
  },
  {
    "path": "windows/.gitignore",
    "content": "flutter/ephemeral/\n\n# Visual Studio user-specific files.\n*.suo\n*.user\n*.userosscache\n*.sln.docstates\n\n# Visual Studio build-related files.\nx64/\nx86/\n\n# Visual Studio cache files\n# files ending in .cache can be ignored\n*.[Cc]ache\n# but keep track of directories ending in .cache\n!*.[Cc]ache/\n"
  },
  {
    "path": "windows/CMakeLists.txt",
    "content": "# Project-level configuration.\ncmake_minimum_required(VERSION 3.14)\nproject(chatbot LANGUAGES CXX)\n\n# The name of the executable created for the application. Change this to change\n# the on-disk name of your application.\nset(BINARY_NAME \"chatbot\")\n\n# Explicitly opt in to modern CMake behaviors to avoid warnings with recent\n# versions of CMake.\ncmake_policy(VERSION 3.14...3.25)\n\n# Define build configuration option.\nget_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)\nif(IS_MULTICONFIG)\n  set(CMAKE_CONFIGURATION_TYPES \"Debug;Profile;Release\"\n    CACHE STRING \"\" FORCE)\nelse()\n  if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)\n    set(CMAKE_BUILD_TYPE \"Debug\" CACHE\n      STRING \"Flutter build mode\" FORCE)\n    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS\n      \"Debug\" \"Profile\" \"Release\")\n  endif()\nendif()\n# Define settings for the Profile build mode.\nset(CMAKE_EXE_LINKER_FLAGS_PROFILE \"${CMAKE_EXE_LINKER_FLAGS_RELEASE}\")\nset(CMAKE_SHARED_LINKER_FLAGS_PROFILE \"${CMAKE_SHARED_LINKER_FLAGS_RELEASE}\")\nset(CMAKE_C_FLAGS_PROFILE \"${CMAKE_C_FLAGS_RELEASE}\")\nset(CMAKE_CXX_FLAGS_PROFILE \"${CMAKE_CXX_FLAGS_RELEASE}\")\n\n# Use Unicode for all projects.\nadd_definitions(-DUNICODE -D_UNICODE)\n\n# Compilation settings that should be applied to most targets.\n#\n# Be cautious about adding new options here, as plugins use this function by\n# default. In most cases, you should add new options to specific targets instead\n# of modifying this function.\nfunction(APPLY_STANDARD_SETTINGS TARGET)\n  target_compile_features(${TARGET} PUBLIC cxx_std_17)\n  target_compile_options(${TARGET} PRIVATE /W4 /WX /wd\"4100\")\n  target_compile_options(${TARGET} PRIVATE /EHsc)\n  target_compile_definitions(${TARGET} PRIVATE \"_HAS_EXCEPTIONS=0\")\n  target_compile_definitions(${TARGET} PRIVATE \"$<$<CONFIG:Debug>:_DEBUG>\")\nendfunction()\n\n# Flutter library and tool build rules.\nset(FLUTTER_MANAGED_DIR \"${CMAKE_CURRENT_SOURCE_DIR}/flutter\")\nadd_subdirectory(${FLUTTER_MANAGED_DIR})\n\n# Application build; see runner/CMakeLists.txt.\nadd_subdirectory(\"runner\")\n\n\n# Generated plugin build rules, which manage building the plugins and adding\n# them to the application.\ninclude(flutter/generated_plugins.cmake)\n\n\n# === Installation ===\n# Support files are copied into place next to the executable, so that it can\n# run in place. This is done instead of making a separate bundle (as on Linux)\n# so that building and running from within Visual Studio will work.\nset(BUILD_BUNDLE_DIR \"$<TARGET_FILE_DIR:${BINARY_NAME}>\")\n# Make the \"install\" step default, as it's required to run.\nset(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)\nif(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)\n  set(CMAKE_INSTALL_PREFIX \"${BUILD_BUNDLE_DIR}\" CACHE PATH \"...\" FORCE)\nendif()\n\nset(INSTALL_BUNDLE_DATA_DIR \"${CMAKE_INSTALL_PREFIX}/data\")\nset(INSTALL_BUNDLE_LIB_DIR \"${CMAKE_INSTALL_PREFIX}\")\n\ninstall(TARGETS ${BINARY_NAME} RUNTIME DESTINATION \"${CMAKE_INSTALL_PREFIX}\"\n  COMPONENT Runtime)\n\ninstall(FILES \"${FLUTTER_ICU_DATA_FILE}\" DESTINATION \"${INSTALL_BUNDLE_DATA_DIR}\"\n  COMPONENT Runtime)\n\ninstall(FILES \"${FLUTTER_LIBRARY}\" DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n  COMPONENT Runtime)\n\nif(PLUGIN_BUNDLED_LIBRARIES)\n  install(FILES \"${PLUGIN_BUNDLED_LIBRARIES}\"\n    DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n    COMPONENT Runtime)\nendif()\n\n# Copy the native assets provided by the build.dart from all packages.\nset(NATIVE_ASSETS_DIR \"${PROJECT_BUILD_DIR}native_assets/windows/\")\ninstall(DIRECTORY \"${NATIVE_ASSETS_DIR}\"\n   DESTINATION \"${INSTALL_BUNDLE_LIB_DIR}\"\n   COMPONENT Runtime)\n\n# Fully re-copy the assets directory on each build to avoid having stale files\n# from a previous install.\nset(FLUTTER_ASSET_DIR_NAME \"flutter_assets\")\ninstall(CODE \"\n  file(REMOVE_RECURSE \\\"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\\\")\n  \" COMPONENT Runtime)\ninstall(DIRECTORY \"${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}\"\n  DESTINATION \"${INSTALL_BUNDLE_DATA_DIR}\" COMPONENT Runtime)\n\n# Install the AOT library on non-Debug builds only.\ninstall(FILES \"${AOT_LIBRARY}\" DESTINATION \"${INSTALL_BUNDLE_DATA_DIR}\"\n  CONFIGURATIONS Profile;Release\n  COMPONENT Runtime)\n"
  },
  {
    "path": "windows/flutter/CMakeLists.txt",
    "content": "# This file controls Flutter-level build steps. It should not be edited.\ncmake_minimum_required(VERSION 3.14)\n\nset(EPHEMERAL_DIR \"${CMAKE_CURRENT_SOURCE_DIR}/ephemeral\")\n\n# Configuration provided via flutter tool.\ninclude(${EPHEMERAL_DIR}/generated_config.cmake)\n\n# TODO: Move the rest of this into files in ephemeral. See\n# https://github.com/flutter/flutter/issues/57146.\nset(WRAPPER_ROOT \"${EPHEMERAL_DIR}/cpp_client_wrapper\")\n\n# Set fallback configurations for older versions of the flutter tool.\nif (NOT DEFINED FLUTTER_TARGET_PLATFORM)\n  set(FLUTTER_TARGET_PLATFORM \"windows-x64\")\nendif()\n\n# === Flutter Library ===\nset(FLUTTER_LIBRARY \"${EPHEMERAL_DIR}/flutter_windows.dll\")\n\n# Published to parent scope for install step.\nset(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)\nset(FLUTTER_ICU_DATA_FILE \"${EPHEMERAL_DIR}/icudtl.dat\" PARENT_SCOPE)\nset(PROJECT_BUILD_DIR \"${PROJECT_DIR}/build/\" PARENT_SCOPE)\nset(AOT_LIBRARY \"${PROJECT_DIR}/build/windows/app.so\" PARENT_SCOPE)\n\nlist(APPEND FLUTTER_LIBRARY_HEADERS\n  \"flutter_export.h\"\n  \"flutter_windows.h\"\n  \"flutter_messenger.h\"\n  \"flutter_plugin_registrar.h\"\n  \"flutter_texture_registrar.h\"\n)\nlist(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND \"${EPHEMERAL_DIR}/\")\nadd_library(flutter INTERFACE)\ntarget_include_directories(flutter INTERFACE\n  \"${EPHEMERAL_DIR}\"\n)\ntarget_link_libraries(flutter INTERFACE \"${FLUTTER_LIBRARY}.lib\")\nadd_dependencies(flutter flutter_assemble)\n\n# === Wrapper ===\nlist(APPEND CPP_WRAPPER_SOURCES_CORE\n  \"core_implementations.cc\"\n  \"standard_codec.cc\"\n)\nlist(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND \"${WRAPPER_ROOT}/\")\nlist(APPEND CPP_WRAPPER_SOURCES_PLUGIN\n  \"plugin_registrar.cc\"\n)\nlist(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND \"${WRAPPER_ROOT}/\")\nlist(APPEND CPP_WRAPPER_SOURCES_APP\n  \"flutter_engine.cc\"\n  \"flutter_view_controller.cc\"\n)\nlist(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND \"${WRAPPER_ROOT}/\")\n\n# Wrapper sources needed for a plugin.\nadd_library(flutter_wrapper_plugin STATIC\n  ${CPP_WRAPPER_SOURCES_CORE}\n  ${CPP_WRAPPER_SOURCES_PLUGIN}\n)\napply_standard_settings(flutter_wrapper_plugin)\nset_target_properties(flutter_wrapper_plugin PROPERTIES\n  POSITION_INDEPENDENT_CODE ON)\nset_target_properties(flutter_wrapper_plugin PROPERTIES\n  CXX_VISIBILITY_PRESET hidden)\ntarget_link_libraries(flutter_wrapper_plugin PUBLIC flutter)\ntarget_include_directories(flutter_wrapper_plugin PUBLIC\n  \"${WRAPPER_ROOT}/include\"\n)\nadd_dependencies(flutter_wrapper_plugin flutter_assemble)\n\n# Wrapper sources needed for the runner.\nadd_library(flutter_wrapper_app STATIC\n  ${CPP_WRAPPER_SOURCES_CORE}\n  ${CPP_WRAPPER_SOURCES_APP}\n)\napply_standard_settings(flutter_wrapper_app)\ntarget_link_libraries(flutter_wrapper_app PUBLIC flutter)\ntarget_include_directories(flutter_wrapper_app PUBLIC\n  \"${WRAPPER_ROOT}/include\"\n)\nadd_dependencies(flutter_wrapper_app flutter_assemble)\n\n# === Flutter tool backend ===\n# _phony_ is a non-existent file to force this command to run every time,\n# since currently there's no way to get a full input/output list from the\n# flutter tool.\nset(PHONY_OUTPUT \"${CMAKE_CURRENT_BINARY_DIR}/_phony_\")\nset_source_files_properties(\"${PHONY_OUTPUT}\" PROPERTIES SYMBOLIC TRUE)\nadd_custom_command(\n  OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}\n    ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}\n    ${CPP_WRAPPER_SOURCES_APP}\n    ${PHONY_OUTPUT}\n  COMMAND ${CMAKE_COMMAND} -E env\n    ${FLUTTER_TOOL_ENVIRONMENT}\n    \"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat\"\n      ${FLUTTER_TARGET_PLATFORM} $<CONFIG>\n  VERBATIM\n)\nadd_custom_target(flutter_assemble DEPENDS\n  \"${FLUTTER_LIBRARY}\"\n  ${FLUTTER_LIBRARY_HEADERS}\n  ${CPP_WRAPPER_SOURCES_CORE}\n  ${CPP_WRAPPER_SOURCES_PLUGIN}\n  ${CPP_WRAPPER_SOURCES_APP}\n)\n"
  },
  {
    "path": "windows/flutter/generated_plugin_registrant.cc",
    "content": "//\n//  Generated file. Do not edit.\n//\n\n// clang-format off\n\n#include \"generated_plugin_registrant.h\"\n\n#include <audioplayers_windows/audioplayers_windows_plugin.h>\n#include <file_selector_windows/file_selector_windows.h>\n#include <objectbox_flutter_libs/objectbox_flutter_libs_plugin.h>\n#include <share_plus/share_plus_windows_plugin_c_api.h>\n#include <url_launcher_windows/url_launcher_windows.h>\n\nvoid RegisterPlugins(flutter::PluginRegistry* registry) {\n  AudioplayersWindowsPluginRegisterWithRegistrar(\n      registry->GetRegistrarForPlugin(\"AudioplayersWindowsPlugin\"));\n  FileSelectorWindowsRegisterWithRegistrar(\n      registry->GetRegistrarForPlugin(\"FileSelectorWindows\"));\n  ObjectboxFlutterLibsPluginRegisterWithRegistrar(\n      registry->GetRegistrarForPlugin(\"ObjectboxFlutterLibsPlugin\"));\n  SharePlusWindowsPluginCApiRegisterWithRegistrar(\n      registry->GetRegistrarForPlugin(\"SharePlusWindowsPluginCApi\"));\n  UrlLauncherWindowsRegisterWithRegistrar(\n      registry->GetRegistrarForPlugin(\"UrlLauncherWindows\"));\n}\n"
  },
  {
    "path": "windows/flutter/generated_plugin_registrant.h",
    "content": "//\n//  Generated file. Do not edit.\n//\n\n// clang-format off\n\n#ifndef GENERATED_PLUGIN_REGISTRANT_\n#define GENERATED_PLUGIN_REGISTRANT_\n\n#include <flutter/plugin_registry.h>\n\n// Registers Flutter plugins.\nvoid RegisterPlugins(flutter::PluginRegistry* registry);\n\n#endif  // GENERATED_PLUGIN_REGISTRANT_\n"
  },
  {
    "path": "windows/flutter/generated_plugins.cmake",
    "content": "#\n# Generated file, do not edit.\n#\n\nlist(APPEND FLUTTER_PLUGIN_LIST\n  audioplayers_windows\n  file_selector_windows\n  objectbox_flutter_libs\n  share_plus\n  url_launcher_windows\n)\n\nlist(APPEND FLUTTER_FFI_PLUGIN_LIST\n)\n\nset(PLUGIN_BUNDLED_LIBRARIES)\n\nforeach(plugin ${FLUTTER_PLUGIN_LIST})\n  add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})\n  target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})\nendforeach(plugin)\n\nforeach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})\n  add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})\n  list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})\nendforeach(ffi_plugin)\n"
  },
  {
    "path": "windows/runner/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.14)\nproject(runner LANGUAGES CXX)\n\n# Define the application target. To change its name, change BINARY_NAME in the\n# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer\n# work.\n#\n# Any new source files that you add to the application should be added here.\nadd_executable(${BINARY_NAME} WIN32\n  \"flutter_window.cpp\"\n  \"main.cpp\"\n  \"utils.cpp\"\n  \"win32_window.cpp\"\n  \"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc\"\n  \"Runner.rc\"\n  \"runner.exe.manifest\"\n)\n\n# Apply the standard set of build settings. This can be removed for applications\n# that need different build settings.\napply_standard_settings(${BINARY_NAME})\n\n# Add preprocessor definitions for the build version.\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"FLUTTER_VERSION=\\\"${FLUTTER_VERSION}\\\"\")\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}\")\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}\")\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}\")\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}\")\n\n# Disable Windows macros that collide with C++ standard library functions.\ntarget_compile_definitions(${BINARY_NAME} PRIVATE \"NOMINMAX\")\n\n# Add dependency libraries and include directories. Add any application-specific\n# dependencies here.\ntarget_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)\ntarget_link_libraries(${BINARY_NAME} PRIVATE \"dwmapi.lib\")\ntarget_include_directories(${BINARY_NAME} PRIVATE \"${CMAKE_SOURCE_DIR}\")\n\n# Run the Flutter tool portions of the build. This must not be removed.\nadd_dependencies(${BINARY_NAME} flutter_assemble)\n"
  },
  {
    "path": "windows/runner/Runner.rc",
    "content": "// Microsoft Visual C++ generated resource script.\n//\n#pragma code_page(65001)\n#include \"resource.h\"\n\n#define APSTUDIO_READONLY_SYMBOLS\n/////////////////////////////////////////////////////////////////////////////\n//\n// Generated from the TEXTINCLUDE 2 resource.\n//\n#include \"winres.h\"\n\n/////////////////////////////////////////////////////////////////////////////\n#undef APSTUDIO_READONLY_SYMBOLS\n\n/////////////////////////////////////////////////////////////////////////////\n// English (United States) resources\n\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\n\n#ifdef APSTUDIO_INVOKED\n/////////////////////////////////////////////////////////////////////////////\n//\n// TEXTINCLUDE\n//\n\n1 TEXTINCLUDE\nBEGIN\n    \"resource.h\\0\"\nEND\n\n2 TEXTINCLUDE\nBEGIN\n    \"#include \"\"winres.h\"\"\\r\\n\"\n    \"\\0\"\nEND\n\n3 TEXTINCLUDE\nBEGIN\n    \"\\r\\n\"\n    \"\\0\"\nEND\n\n#endif    // APSTUDIO_INVOKED\n\n\n/////////////////////////////////////////////////////////////////////////////\n//\n// Icon\n//\n\n// Icon with lowest ID value placed first to ensure application icon\n// remains consistent on all systems.\nIDI_APP_ICON            ICON                    \"resources\\\\app_icon.ico\"\n\n\n/////////////////////////////////////////////////////////////////////////////\n//\n// Version\n//\n\n#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)\n#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD\n#else\n#define VERSION_AS_NUMBER 1,0,0,0\n#endif\n\n#if defined(FLUTTER_VERSION)\n#define VERSION_AS_STRING FLUTTER_VERSION\n#else\n#define VERSION_AS_STRING \"1.0.0\"\n#endif\n\nVS_VERSION_INFO VERSIONINFO\n FILEVERSION VERSION_AS_NUMBER\n PRODUCTVERSION VERSION_AS_NUMBER\n FILEFLAGSMASK VS_FFI_FILEFLAGSMASK\n#ifdef _DEBUG\n FILEFLAGS VS_FF_DEBUG\n#else\n FILEFLAGS 0x0L\n#endif\n FILEOS VOS__WINDOWS32\n FILETYPE VFT_APP\n FILESUBTYPE 0x0L\nBEGIN\n    BLOCK \"StringFileInfo\"\n    BEGIN\n        BLOCK \"040904e4\"\n        BEGIN\n            VALUE \"CompanyName\", \"cc.arthur63\" \"\\0\"\n            VALUE \"FileDescription\", \"chatbot\" \"\\0\"\n            VALUE \"FileVersion\", VERSION_AS_STRING \"\\0\"\n            VALUE \"InternalName\", \"chatbot\" \"\\0\"\n            VALUE \"LegalCopyright\", \"Copyright (C) 2024 cc.arthur63. All rights reserved.\" \"\\0\"\n            VALUE \"OriginalFilename\", \"chatbot.exe\" \"\\0\"\n            VALUE \"ProductName\", \"chatbot\" \"\\0\"\n            VALUE \"ProductVersion\", VERSION_AS_STRING \"\\0\"\n        END\n    END\n    BLOCK \"VarFileInfo\"\n    BEGIN\n        VALUE \"Translation\", 0x409, 1252\n    END\nEND\n\n#endif    // English (United States) resources\n/////////////////////////////////////////////////////////////////////////////\n\n\n\n#ifndef APSTUDIO_INVOKED\n/////////////////////////////////////////////////////////////////////////////\n//\n// Generated from the TEXTINCLUDE 3 resource.\n//\n\n\n/////////////////////////////////////////////////////////////////////////////\n#endif    // not APSTUDIO_INVOKED\n"
  },
  {
    "path": "windows/runner/flutter_window.cpp",
    "content": "#include \"flutter_window.h\"\n\n#include <optional>\n\n#include \"flutter/generated_plugin_registrant.h\"\n\nFlutterWindow::FlutterWindow(const flutter::DartProject& project)\n    : project_(project) {}\n\nFlutterWindow::~FlutterWindow() {}\n\nbool FlutterWindow::OnCreate() {\n  if (!Win32Window::OnCreate()) {\n    return false;\n  }\n\n  RECT frame = GetClientArea();\n\n  // The size here must match the window dimensions to avoid unnecessary surface\n  // creation / destruction in the startup path.\n  flutter_controller_ = std::make_unique<flutter::FlutterViewController>(\n      frame.right - frame.left, frame.bottom - frame.top, project_);\n  // Ensure that basic setup of the controller was successful.\n  if (!flutter_controller_->engine() || !flutter_controller_->view()) {\n    return false;\n  }\n  RegisterPlugins(flutter_controller_->engine());\n  SetChildContent(flutter_controller_->view()->GetNativeWindow());\n\n  flutter_controller_->engine()->SetNextFrameCallback([&]() {\n    this->Show();\n  });\n\n  // Flutter can complete the first frame before the \"show window\" callback is\n  // registered. The following call ensures a frame is pending to ensure the\n  // window is shown. It is a no-op if the first frame hasn't completed yet.\n  flutter_controller_->ForceRedraw();\n\n  return true;\n}\n\nvoid FlutterWindow::OnDestroy() {\n  if (flutter_controller_) {\n    flutter_controller_ = nullptr;\n  }\n\n  Win32Window::OnDestroy();\n}\n\nLRESULT\nFlutterWindow::MessageHandler(HWND hwnd, UINT const message,\n                              WPARAM const wparam,\n                              LPARAM const lparam) noexcept {\n  // Give Flutter, including plugins, an opportunity to handle window messages.\n  if (flutter_controller_) {\n    std::optional<LRESULT> result =\n        flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,\n                                                      lparam);\n    if (result) {\n      return *result;\n    }\n  }\n\n  switch (message) {\n    case WM_FONTCHANGE:\n      flutter_controller_->engine()->ReloadSystemFonts();\n      break;\n  }\n\n  return Win32Window::MessageHandler(hwnd, message, wparam, lparam);\n}\n"
  },
  {
    "path": "windows/runner/flutter_window.h",
    "content": "#ifndef RUNNER_FLUTTER_WINDOW_H_\n#define RUNNER_FLUTTER_WINDOW_H_\n\n#include <flutter/dart_project.h>\n#include <flutter/flutter_view_controller.h>\n\n#include <memory>\n\n#include \"win32_window.h\"\n\n// A window that does nothing but host a Flutter view.\nclass FlutterWindow : public Win32Window {\n public:\n  // Creates a new FlutterWindow hosting a Flutter view running |project|.\n  explicit FlutterWindow(const flutter::DartProject& project);\n  virtual ~FlutterWindow();\n\n protected:\n  // Win32Window:\n  bool OnCreate() override;\n  void OnDestroy() override;\n  LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,\n                         LPARAM const lparam) noexcept override;\n\n private:\n  // The project to run.\n  flutter::DartProject project_;\n\n  // The Flutter instance hosted by this window.\n  std::unique_ptr<flutter::FlutterViewController> flutter_controller_;\n};\n\n#endif  // RUNNER_FLUTTER_WINDOW_H_\n"
  },
  {
    "path": "windows/runner/main.cpp",
    "content": "#include <flutter/dart_project.h>\n#include <flutter/flutter_view_controller.h>\n#include <windows.h>\n\n#include \"flutter_window.h\"\n#include \"utils.h\"\n\nint APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,\n                      _In_ wchar_t *command_line, _In_ int show_command) {\n  // Attach to console when present (e.g., 'flutter run') or create a\n  // new console when running with a debugger.\n  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {\n    CreateAndAttachConsole();\n  }\n\n  // Initialize COM, so that it is available for use in the library and/or\n  // plugins.\n  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);\n\n  flutter::DartProject project(L\"data\");\n\n  std::vector<std::string> command_line_arguments =\n      GetCommandLineArguments();\n\n  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));\n\n  FlutterWindow window(project);\n  Win32Window::Point origin(10, 10);\n  Win32Window::Size size(1280, 720);\n  if (!window.Create(L\"chatbot\", origin, size)) {\n    return EXIT_FAILURE;\n  }\n  window.SetQuitOnClose(true);\n\n  ::MSG msg;\n  while (::GetMessage(&msg, nullptr, 0, 0)) {\n    ::TranslateMessage(&msg);\n    ::DispatchMessage(&msg);\n  }\n\n  ::CoUninitialize();\n  return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "windows/runner/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\n// Microsoft Visual C++ generated include file.\n// Used by Runner.rc\n//\n#define IDI_APP_ICON                    101\n\n// Next default values for new objects\n//\n#ifdef APSTUDIO_INVOKED\n#ifndef APSTUDIO_READONLY_SYMBOLS\n#define _APS_NEXT_RESOURCE_VALUE        102\n#define _APS_NEXT_COMMAND_VALUE         40001\n#define _APS_NEXT_CONTROL_VALUE         1001\n#define _APS_NEXT_SYMED_VALUE           101\n#endif\n#endif\n"
  },
  {
    "path": "windows/runner/runner.exe.manifest",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n  <application xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n    <windowsSettings>\n      <dpiAwareness xmlns=\"http://schemas.microsoft.com/SMI/2016/WindowsSettings\">PerMonitorV2</dpiAwareness>\n    </windowsSettings>\n  </application>\n  <compatibility xmlns=\"urn:schemas-microsoft-com:compatibility.v1\">\n    <application>\n      <!-- Windows 10 and Windows 11 -->\n      <supportedOS Id=\"{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}\"/>\n    </application>\n  </compatibility>\n</assembly>\n"
  },
  {
    "path": "windows/runner/utils.cpp",
    "content": "#include \"utils.h\"\n\n#include <flutter_windows.h>\n#include <io.h>\n#include <stdio.h>\n#include <windows.h>\n\n#include <iostream>\n\nvoid CreateAndAttachConsole() {\n  if (::AllocConsole()) {\n    FILE *unused;\n    if (freopen_s(&unused, \"CONOUT$\", \"w\", stdout)) {\n      _dup2(_fileno(stdout), 1);\n    }\n    if (freopen_s(&unused, \"CONOUT$\", \"w\", stderr)) {\n      _dup2(_fileno(stdout), 2);\n    }\n    std::ios::sync_with_stdio();\n    FlutterDesktopResyncOutputStreams();\n  }\n}\n\nstd::vector<std::string> GetCommandLineArguments() {\n  // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.\n  int argc;\n  wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);\n  if (argv == nullptr) {\n    return std::vector<std::string>();\n  }\n\n  std::vector<std::string> command_line_arguments;\n\n  // Skip the first argument as it's the binary name.\n  for (int i = 1; i < argc; i++) {\n    command_line_arguments.push_back(Utf8FromUtf16(argv[i]));\n  }\n\n  ::LocalFree(argv);\n\n  return command_line_arguments;\n}\n\nstd::string Utf8FromUtf16(const wchar_t* utf16_string) {\n  if (utf16_string == nullptr) {\n    return std::string();\n  }\n  unsigned int target_length = ::WideCharToMultiByte(\n      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,\n      -1, nullptr, 0, nullptr, nullptr)\n    -1; // remove the trailing null character\n  int input_length = (int)wcslen(utf16_string);\n  std::string utf8_string;\n  if (target_length == 0 || target_length > utf8_string.max_size()) {\n    return utf8_string;\n  }\n  utf8_string.resize(target_length);\n  int converted_length = ::WideCharToMultiByte(\n      CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,\n      input_length, utf8_string.data(), target_length, nullptr, nullptr);\n  if (converted_length == 0) {\n    return std::string();\n  }\n  return utf8_string;\n}\n"
  },
  {
    "path": "windows/runner/utils.h",
    "content": "#ifndef RUNNER_UTILS_H_\n#define RUNNER_UTILS_H_\n\n#include <string>\n#include <vector>\n\n// Creates a console for the process, and redirects stdout and stderr to\n// it for both the runner and the Flutter library.\nvoid CreateAndAttachConsole();\n\n// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string\n// encoded in UTF-8. Returns an empty std::string on failure.\nstd::string Utf8FromUtf16(const wchar_t* utf16_string);\n\n// Gets the command line arguments passed in as a std::vector<std::string>,\n// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.\nstd::vector<std::string> GetCommandLineArguments();\n\n#endif  // RUNNER_UTILS_H_\n"
  },
  {
    "path": "windows/runner/win32_window.cpp",
    "content": "#include \"win32_window.h\"\n\n#include <dwmapi.h>\n#include <flutter_windows.h>\n\n#include \"resource.h\"\n\nnamespace {\n\n/// Window attribute that enables dark mode window decorations.\n///\n/// Redefined in case the developer's machine has a Windows SDK older than\n/// version 10.0.22000.0.\n/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute\n#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE\n#define DWMWA_USE_IMMERSIVE_DARK_MODE 20\n#endif\n\nconstexpr const wchar_t kWindowClassName[] = L\"FLUTTER_RUNNER_WIN32_WINDOW\";\n\n/// Registry key for app theme preference.\n///\n/// A value of 0 indicates apps should use dark mode. A non-zero or missing\n/// value indicates apps should use light mode.\nconstexpr const wchar_t kGetPreferredBrightnessRegKey[] =\n  L\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Themes\\\\Personalize\";\nconstexpr const wchar_t kGetPreferredBrightnessRegValue[] = L\"AppsUseLightTheme\";\n\n// The number of Win32Window objects that currently exist.\nstatic int g_active_window_count = 0;\n\nusing EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);\n\n// Scale helper to convert logical scaler values to physical using passed in\n// scale factor\nint Scale(int source, double scale_factor) {\n  return static_cast<int>(source * scale_factor);\n}\n\n// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.\n// This API is only needed for PerMonitor V1 awareness mode.\nvoid EnableFullDpiSupportIfAvailable(HWND hwnd) {\n  HMODULE user32_module = LoadLibraryA(\"User32.dll\");\n  if (!user32_module) {\n    return;\n  }\n  auto enable_non_client_dpi_scaling =\n      reinterpret_cast<EnableNonClientDpiScaling*>(\n          GetProcAddress(user32_module, \"EnableNonClientDpiScaling\"));\n  if (enable_non_client_dpi_scaling != nullptr) {\n    enable_non_client_dpi_scaling(hwnd);\n  }\n  FreeLibrary(user32_module);\n}\n\n}  // namespace\n\n// Manages the Win32Window's window class registration.\nclass WindowClassRegistrar {\n public:\n  ~WindowClassRegistrar() = default;\n\n  // Returns the singleton registrar instance.\n  static WindowClassRegistrar* GetInstance() {\n    if (!instance_) {\n      instance_ = new WindowClassRegistrar();\n    }\n    return instance_;\n  }\n\n  // Returns the name of the window class, registering the class if it hasn't\n  // previously been registered.\n  const wchar_t* GetWindowClass();\n\n  // Unregisters the window class. Should only be called if there are no\n  // instances of the window.\n  void UnregisterWindowClass();\n\n private:\n  WindowClassRegistrar() = default;\n\n  static WindowClassRegistrar* instance_;\n\n  bool class_registered_ = false;\n};\n\nWindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;\n\nconst wchar_t* WindowClassRegistrar::GetWindowClass() {\n  if (!class_registered_) {\n    WNDCLASS window_class{};\n    window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);\n    window_class.lpszClassName = kWindowClassName;\n    window_class.style = CS_HREDRAW | CS_VREDRAW;\n    window_class.cbClsExtra = 0;\n    window_class.cbWndExtra = 0;\n    window_class.hInstance = GetModuleHandle(nullptr);\n    window_class.hIcon =\n        LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));\n    window_class.hbrBackground = 0;\n    window_class.lpszMenuName = nullptr;\n    window_class.lpfnWndProc = Win32Window::WndProc;\n    RegisterClass(&window_class);\n    class_registered_ = true;\n  }\n  return kWindowClassName;\n}\n\nvoid WindowClassRegistrar::UnregisterWindowClass() {\n  UnregisterClass(kWindowClassName, nullptr);\n  class_registered_ = false;\n}\n\nWin32Window::Win32Window() {\n  ++g_active_window_count;\n}\n\nWin32Window::~Win32Window() {\n  --g_active_window_count;\n  Destroy();\n}\n\nbool Win32Window::Create(const std::wstring& title,\n                         const Point& origin,\n                         const Size& size) {\n  Destroy();\n\n  const wchar_t* window_class =\n      WindowClassRegistrar::GetInstance()->GetWindowClass();\n\n  const POINT target_point = {static_cast<LONG>(origin.x),\n                              static_cast<LONG>(origin.y)};\n  HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);\n  UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);\n  double scale_factor = dpi / 96.0;\n\n  HWND window = CreateWindow(\n      window_class, title.c_str(), WS_OVERLAPPEDWINDOW,\n      Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),\n      Scale(size.width, scale_factor), Scale(size.height, scale_factor),\n      nullptr, nullptr, GetModuleHandle(nullptr), this);\n\n  if (!window) {\n    return false;\n  }\n\n  UpdateTheme(window);\n\n  return OnCreate();\n}\n\nbool Win32Window::Show() {\n  return ShowWindow(window_handle_, SW_SHOWNORMAL);\n}\n\n// static\nLRESULT CALLBACK Win32Window::WndProc(HWND const window,\n                                      UINT const message,\n                                      WPARAM const wparam,\n                                      LPARAM const lparam) noexcept {\n  if (message == WM_NCCREATE) {\n    auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);\n    SetWindowLongPtr(window, GWLP_USERDATA,\n                     reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));\n\n    auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);\n    EnableFullDpiSupportIfAvailable(window);\n    that->window_handle_ = window;\n  } else if (Win32Window* that = GetThisFromHandle(window)) {\n    return that->MessageHandler(window, message, wparam, lparam);\n  }\n\n  return DefWindowProc(window, message, wparam, lparam);\n}\n\nLRESULT\nWin32Window::MessageHandler(HWND hwnd,\n                            UINT const message,\n                            WPARAM const wparam,\n                            LPARAM const lparam) noexcept {\n  switch (message) {\n    case WM_DESTROY:\n      window_handle_ = nullptr;\n      Destroy();\n      if (quit_on_close_) {\n        PostQuitMessage(0);\n      }\n      return 0;\n\n    case WM_DPICHANGED: {\n      auto newRectSize = reinterpret_cast<RECT*>(lparam);\n      LONG newWidth = newRectSize->right - newRectSize->left;\n      LONG newHeight = newRectSize->bottom - newRectSize->top;\n\n      SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,\n                   newHeight, SWP_NOZORDER | SWP_NOACTIVATE);\n\n      return 0;\n    }\n    case WM_SIZE: {\n      RECT rect = GetClientArea();\n      if (child_content_ != nullptr) {\n        // Size and position the child window.\n        MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,\n                   rect.bottom - rect.top, TRUE);\n      }\n      return 0;\n    }\n\n    case WM_ACTIVATE:\n      if (child_content_ != nullptr) {\n        SetFocus(child_content_);\n      }\n      return 0;\n\n    case WM_DWMCOLORIZATIONCOLORCHANGED:\n      UpdateTheme(hwnd);\n      return 0;\n  }\n\n  return DefWindowProc(window_handle_, message, wparam, lparam);\n}\n\nvoid Win32Window::Destroy() {\n  OnDestroy();\n\n  if (window_handle_) {\n    DestroyWindow(window_handle_);\n    window_handle_ = nullptr;\n  }\n  if (g_active_window_count == 0) {\n    WindowClassRegistrar::GetInstance()->UnregisterWindowClass();\n  }\n}\n\nWin32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {\n  return reinterpret_cast<Win32Window*>(\n      GetWindowLongPtr(window, GWLP_USERDATA));\n}\n\nvoid Win32Window::SetChildContent(HWND content) {\n  child_content_ = content;\n  SetParent(content, window_handle_);\n  RECT frame = GetClientArea();\n\n  MoveWindow(content, frame.left, frame.top, frame.right - frame.left,\n             frame.bottom - frame.top, true);\n\n  SetFocus(child_content_);\n}\n\nRECT Win32Window::GetClientArea() {\n  RECT frame;\n  GetClientRect(window_handle_, &frame);\n  return frame;\n}\n\nHWND Win32Window::GetHandle() {\n  return window_handle_;\n}\n\nvoid Win32Window::SetQuitOnClose(bool quit_on_close) {\n  quit_on_close_ = quit_on_close;\n}\n\nbool Win32Window::OnCreate() {\n  // No-op; provided for subclasses.\n  return true;\n}\n\nvoid Win32Window::OnDestroy() {\n  // No-op; provided for subclasses.\n}\n\nvoid Win32Window::UpdateTheme(HWND const window) {\n  DWORD light_mode;\n  DWORD light_mode_size = sizeof(light_mode);\n  LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,\n                               kGetPreferredBrightnessRegValue,\n                               RRF_RT_REG_DWORD, nullptr, &light_mode,\n                               &light_mode_size);\n\n  if (result == ERROR_SUCCESS) {\n    BOOL enable_dark_mode = light_mode == 0;\n    DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,\n                          &enable_dark_mode, sizeof(enable_dark_mode));\n  }\n}\n"
  },
  {
    "path": "windows/runner/win32_window.h",
    "content": "#ifndef RUNNER_WIN32_WINDOW_H_\n#define RUNNER_WIN32_WINDOW_H_\n\n#include <windows.h>\n\n#include <functional>\n#include <memory>\n#include <string>\n\n// A class abstraction for a high DPI-aware Win32 Window. Intended to be\n// inherited from by classes that wish to specialize with custom\n// rendering and input handling\nclass Win32Window {\n public:\n  struct Point {\n    unsigned int x;\n    unsigned int y;\n    Point(unsigned int x, unsigned int y) : x(x), y(y) {}\n  };\n\n  struct Size {\n    unsigned int width;\n    unsigned int height;\n    Size(unsigned int width, unsigned int height)\n        : width(width), height(height) {}\n  };\n\n  Win32Window();\n  virtual ~Win32Window();\n\n  // Creates a win32 window with |title| that is positioned and sized using\n  // |origin| and |size|. New windows are created on the default monitor. Window\n  // sizes are specified to the OS in physical pixels, hence to ensure a\n  // consistent size this function will scale the inputted width and height as\n  // as appropriate for the default monitor. The window is invisible until\n  // |Show| is called. Returns true if the window was created successfully.\n  bool Create(const std::wstring& title, const Point& origin, const Size& size);\n\n  // Show the current window. Returns true if the window was successfully shown.\n  bool Show();\n\n  // Release OS resources associated with window.\n  void Destroy();\n\n  // Inserts |content| into the window tree.\n  void SetChildContent(HWND content);\n\n  // Returns the backing Window handle to enable clients to set icon and other\n  // window properties. Returns nullptr if the window has been destroyed.\n  HWND GetHandle();\n\n  // If true, closing this window will quit the application.\n  void SetQuitOnClose(bool quit_on_close);\n\n  // Return a RECT representing the bounds of the current client area.\n  RECT GetClientArea();\n\n protected:\n  // Processes and route salient window messages for mouse handling,\n  // size change and DPI. Delegates handling of these to member overloads that\n  // inheriting classes can handle.\n  virtual LRESULT MessageHandler(HWND window,\n                                 UINT const message,\n                                 WPARAM const wparam,\n                                 LPARAM const lparam) noexcept;\n\n  // Called when CreateAndShow is called, allowing subclass window-related\n  // setup. Subclasses should return false if setup fails.\n  virtual bool OnCreate();\n\n  // Called when Destroy is called.\n  virtual void OnDestroy();\n\n private:\n  friend class WindowClassRegistrar;\n\n  // OS callback called by message pump. Handles the WM_NCCREATE message which\n  // is passed when the non-client area is being created and enables automatic\n  // non-client DPI scaling so that the non-client area automatically\n  // responds to changes in DPI. All other messages are handled by\n  // MessageHandler.\n  static LRESULT CALLBACK WndProc(HWND const window,\n                                  UINT const message,\n                                  WPARAM const wparam,\n                                  LPARAM const lparam) noexcept;\n\n  // Retrieves a class instance pointer for |window|\n  static Win32Window* GetThisFromHandle(HWND const window) noexcept;\n\n  // Update the window frame's theme to match the system theme.\n  static void UpdateTheme(HWND const window);\n\n  bool quit_on_close_ = false;\n\n  // window handle for top level window.\n  HWND window_handle_ = nullptr;\n\n  // window handle for hosted content.\n  HWND child_content_ = nullptr;\n};\n\n#endif  // RUNNER_WIN32_WINDOW_H_\n"
  }
]